質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

0回答

1062閲覧

VAEを用いて画像をマッピングしたい。

takesiiii

総合スコア0

Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2020/12/12 17:45

前提・実現したいこと

VAEを用いて自作のデータセットからマッピングを行おうとしています。
調べたところ、同じような事をしている記事があったので、それを参考にやったのですがうまくできませんでした。
参考サイト

発生している問題・エラーメッセージ

下記ソースコードを実行したところ、エラーは出なかったのですが、マッピングができておらず真っ暗な画像が表示されてしまいました。

該当のソースコード

データセット作成部分

python

1 2import glob 3import cv2 4import matplotlib.pyplot 5import numpy as np 6x=glob.glob('{}/*.jpg'.format("/content/gdrive/My Drive/test/test1")) 7image = [] 8for i in x: 9 img = cv2.imread(i) 10 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 11 img = cv2.resize(img,(256,256)) 12 img = np.asarray(img) 13 image.append(img) 14 image.append(img[:, ::-1])

メイン

python

1 2import tensorflow as tf 3tf.compat.v1.disable_eager_execution() 4import matplotlib.pyplot as plt 5from keras import optimizers 6%matplotlib inline 7from keras.datasets import mnist 8import keras 9from keras import layers 10from keras import backend as K 11from keras.models import Model 12import numpy as np 13import glob 14from keras.utils import np_utils 15from PIL import Image 16from scipy.stats import norm 17 18image = np.asarray(image) 19(x_train), (x_test) = image[:-32],image[-32:] 20x_train = x_train.astype('float32') / 255. 21x_train = np.reshape(x_train, (len(x_train), 256, 256, 3)) 22print(x_train.shape) 23x_test = x_test.astype('float32') / 255. 24x_test = np.reshape(x_test, (len(x_test), 256, 256, 3)) 25 26fig = plt.figure(figsize=(10, 10)) 27fig.subplots_adjust(left=0, right=1, bottom=0, top=0.5, hspace=0.01, wspace=0.01) 28for i in range(100): 29 ax = fig.add_subplot(10, 10, i + 1, xticks=[], yticks=[]) 30 ax.imshow(x_train[i].reshape((256, 256,3)), cmap='gray') 31 32 33K.clear_session() 34 35img_shape = (256, 256,3) 36epochs = 1 37batch_size = 32 38latent_dim = 2 39 40input_img = keras.Input(shape=img_shape) 41 42x = layers.Conv2D(3, 3, padding='same',activation='relu')(input_img) 43x = layers.Conv2D(32, 3, 44 padding='same',strides=2,activation='relu')(x) 45x = layers.Conv2D(32, 3,padding='same',activation='relu')(x) 46x = layers.Conv2D(32, 3, padding='same',activation='relu')(x) 47shape_before_flattening = K.int_shape(x) 48 49x = layers.Flatten()(x) 50x = layers.Dense(128, activation='relu')(x) 51 52z_mean = layers.Dense(latent_dim)(x) 53z_log_var = layers.Dense(latent_dim)(x) 54def sampling(args): 55 z_mean, z_log_var = args 56 epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim), 57 mean=0., stddev=1.) 58 return z_mean + K.exp(z_log_var) * epsilon 59 60z = layers.Lambda(sampling)([z_mean, z_log_var]) 61encoder = Model(input_img,z) 62 63x = layers.Dense(128, activation='relu')(decoder_input) 64x = layers.Dense(shape_before_flattening[1]*shape_before_flattening[2]*shape_before_flattening[3], activation='relu')(x) 65 66print(shape_before_flattening[1:]) 67x = layers.Reshape(shape_before_flattening[1:])(x) 68x = layers.Conv2DTranspose(32, 3,padding='same',activation='relu',)(x) 69x = layers.Conv2DTranspose(32, 3,padding='same',activation='relu',)(x) 70x = layers.Conv2DTranspose(32, 3,padding='same',strides=2,activation='relu',)(x) 71x = layers.Conv2D(3, 3,padding='same',activation='relu',)(x) 72decoder = Model(decoder_input, x) 73 74z_decoded = decoder(z) 75class CustomVariationalLayer(keras.layers.Layer): 76 77 def vae_loss(self, x, z_decoded): 78 x = K.flatten(x) 79 z_decoded = K.flatten(z_decoded) 80 xent_loss = keras.metrics.binary_crossentropy(x, z_decoded) 81 kl_loss = -5e-4 * K.mean( 82 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1) 83 return K.mean(xent_loss + kl_loss) 84 85 def call(self, inputs): 86 x = inputs[0] 87 z_decoded = inputs[1] 88 loss = self.vae_loss(x, z_decoded) 89 self.add_loss(loss, inputs=inputs) 90 return x 91 92y = CustomVariationalLayer()([input_img, z_decoded]) 93vae = Model(input_img, y) 94sgd = optimizers.SGD(lr=0.0001, momentum=0.9) 95adm = optimizers.Adam(lr=0.0001) 96vae.compile(optimizer='rmsprop', loss=None) 97vae.summary() 98callbacks = [ 99 keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, verbose=0, mode='auto'), 100] 101history = vae.fit(x=x_train, y=None, 102 shuffle=True, 103 epochs=epochs, 104 batch_size=batch_size, 105 callbacks=callbacks, 106 validation_data=(x_test, None)) 107with open('loss.txt', 'a') as f: 108 for loss in history.history['loss']: 109 f.write(str(loss) + '\r') 110 111n = 15 112digit_size = 256 113figure = np.zeros((digit_size*n, digit_size*n,3)) 114grid_x = norm.ppf(np.linspace(0.05, 0.95, n)) 115grid_y = norm.ppf(np.linspace(0.05, 0.95, n)) 116 117for i, yi in enumerate(grid_y): 118 for j, xi in enumerate(grid_x): 119 z_sample = np.array([[xi, yi]]) 120 z_sample = np.tile(z_sample, batch_size).reshape(batch_size, 2) 121 x_decoded = decoder.predict(z_sample, batch_size) 122 digit = x_decoded[0].reshape(digit_size,digit_size,3) 123 figure[i*digit_size:(i+1)*digit_size, 124 j*digit_size:(j+1)*digit_size] = digit 125plt.figure(figsize=(10,10)) 126plt.imshow(figure, cmap='Greys_r') 127plt.show() 128

試したこと

上記のソースコードを実行してtest1の中にある画像で二次元マッピングを行おうとしました。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問