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

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

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

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

Google Colaboratory

Google Colaboratoryとは、無償のJupyterノートブック環境。教育や研究機関の機械学習の普及のためのGoogleの研究プロジェクトです。PythonやNumpyといった機械学習で要する大方の環境がすでに構築されており、コードの記述・実行、解析の保存・共有などが可能です。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

1646閲覧

KerasとTensorflowのバージョンを変更するとエラーが発生する

TOMO6181

総合スコア39

Keras

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

Google Colaboratory

Google Colaboratoryとは、無償のJupyterノートブック環境。教育や研究機関の機械学習の普及のためのGoogleの研究プロジェクトです。PythonやNumpyといった機械学習で要する大方の環境がすでに構築されており、コードの記述・実行、解析の保存・共有などが可能です。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2020/05/01 15:12

編集2020/05/04 11:11

mnistから画像をダウンロードして学習データとして使用し、数値の画像を作成するGANのプログラムについての質問です。
コードはGoogle Colaboratory上で実行しており、Google Colaboratory上の環境は以下です。
・CUDA:Ver10.1.243
・cudnn:7.6.5
・tensorflow-2.2.0rc3
・Keras:2.3.1
・ハードウェアアクセラレータ:GPU

実行したコードは以下です。

Python

1### -*-coding:utf-8-*- 2from __future__ import print_function, division 3 4from keras.datasets import mnist 5from keras.layers import Input, Dense, Reshape, Flatten, Dropout 6from keras.layers import BatchNormalization, Activation, ZeroPadding2D 7from keras.layers.advanced_activations import LeakyReLU 8from keras.layers.convolutional import UpSampling2D, Conv2D 9from keras.models import Sequential, Model 10from keras.optimizers import Adam 11 12import matplotlib.pyplot as plt 13import sys 14import numpy as np 15 16# GANで使う処理をまとめたデータクラス 17class GAN(): 18 # コンストラクタ 19 def __init__(self): 20 #mnistデータ用の入力データサイズ 21 self.img_rows = 28 22 self.img_cols = 28 23 self.channels = 1 24 self.img_shape = (self.img_rows, self.img_cols, self.channels) 25 26 # 潜在変数の次元数 27 self.z_dim = 100 28 optimizer = Adam(0.0002, 0.5) 29 30 # discriminatorモデル 31 self.discriminator = self.build_discriminator() 32 self.discriminator.compile(loss='binary_crossentropy', 33 optimizer=optimizer, 34 metrics=['accuracy']) 35 36 # Generatorモデル 37 self.generator = self.build_generator() 38 self.combined = self.build_combined1() 39 self.combined.compile(loss='binary_crossentropy', optimizer=optimizer) 40 41 def build_generator(self): 42 noise_shape = (self.z_dim,) 43 model = Sequential() 44 45 model.add(Dense(256, input_shape=noise_shape)) 46 model.add(LeakyReLU(alpha=0.2)) 47 model.add(BatchNormalization(momentum=0.8)) 48 model.add(Dense(512)) 49 model.add(LeakyReLU(alpha=0.2)) 50 model.add(BatchNormalization(momentum=0.8)) 51 model.add(Dense(1024)) 52 model.add(LeakyReLU(alpha=0.2)) 53 model.add(BatchNormalization(momentum=0.8)) 54 # Discriminatorへの入力になるため、Discriminatorの入力に次元数を合わせる 55 model.add(Dense(np.prod(self.img_shape), activation='tanh')) 56 model.add(Reshape(self.img_shape)) 57 model.summary() 58 59 return model 60 61 def build_discriminator(self): 62 img_shape = (self.img_rows, self.img_cols, self.channels) 63 model = Sequential() 64 65 model.add(Flatten(input_shape=img_shape)) 66 model.add(Dense(512)) 67 model.add(LeakyReLU(alpha=0.2)) 68 model.add(Dense(256)) 69 model.add(LeakyReLU(alpha=0.2)) 70 model.add(Dense(1, activation='sigmoid')) 71 model.summary() 72 73 return model 74 75 def build_combined1(self): 76 self.discriminator.trainable = False 77 model = Sequential([self.generator, self.discriminator]) 78 return model 79 80 def train(self, epochs, batch_size=128, save_interval=50): 81 82 # nb_samples, 28, 28)の白黒画像 83 # nb_samples:trainなら60000画像 84 (X_train, _), (_, _) = mnist.load_data() 85 86 # normalize 87 X_train = (X_train.astype(np.float32) - 127.5) / 127.5 88 X_train = np.expand_dims(X_train, axis=3) 89 90 half_batch = int(batch_size / 2) 91 92 # 画像枚数 / バッチサイズ で、バッチ数を取得 93 num_batches = int(X_train.shape[0] / half_batch) 94 print('Number of batches:', num_batches) 95 96 for epoch in range(epochs): 97 for iteration in range(num_batches): 98 99 # --------------------- 100 # Discriminator learning 101 # --------------------- 102 103 # pickup images (half-batch size) from generator 104 noise = np.random.normal(0, 1, (half_batch, self.z_dim)) 105 gen_imgs = self.generator.predict(noise) 106 107 # pickup images (half-batch size) from dataset 108 # 学習用データから、0~60000の乱数を、half_batch数分取得 109 idx = np.random.randint(0, X_train.shape[0], half_batch) 110 # バッチ数分の画像データを取得 111 imgs = X_train[idx] 112 113 # learn discriminator 114 # learning discriminator with real-data and fake-data seperately 115 # リアルデータなら1 116 # Generatorからのデータなら0 117 d_loss_real = self.discriminator.train_on_batch(imgs, np.ones((half_batch, 1))) 118 d_loss_fake = self.discriminator.train_on_batch(gen_imgs, np.zeros((half_batch, 1))) 119 # average each loss 120 d_loss = 0.5 * np.add(d_loss_real, d_loss_fake) 121 122 # --------------------- 123 # Generator learning 124 # --------------------- 125 126 noise = np.random.normal(0, 1, (batch_size, self.z_dim)) 127 128 # make label (gen data: 1) 129 valid_y = np.array([1] * batch_size) 130 131 # Train the generator 132 g_loss = self.combined.train_on_batch(noise, valid_y) 133 134 # progress 135 print ("epoch:%d, iter:%d, [D loss: %f, acc.: %.2f%%] [G loss: %f]" % (epoch, iteration, d_loss[0], 100*d_loss[1], g_loss)) 136 137 # save images 138 if epoch % save_interval == 0: 139 self.save_imgs(epoch) 140 141 def save_imgs(self, epoch): 142 # row,col 143 r, c = 5, 5 144 145 noise = np.random.normal(0, 1, (r * c, self.z_dim)) 146 gen_imgs = self.generator.predict(noise) 147 148 # rescale [-1, 1] to [0, 1] 149 gen_imgs = 0.5 * gen_imgs + 0.5 150 151 fig, axs = plt.subplots(r, c) 152 cnt = 0 153 154 # 1画像ずつ、subplot用の枠に入れていく 155 for i in range(r): 156 for j in range(c): 157 axs[i,j].imshow(gen_imgs[cnt, :,:,0], cmap='gray') 158 axs[i,j].axis('off') 159 cnt += 1 160 fig.savefig("images/mnist_%d.png" % epoch) 161 plt.close() 162 163 164if __name__ == '__main__': 165 gan = GAN() 166 gan.train(epochs=30000, batch_size=32, save_interval=1)

上記のコードを実行すると、d_loss_real = self.discriminator.train_on_batch(imgs, np.ones((half_batch, 1)))の
当たりで、下記のエラーが発生します。

FailedPreconditionError: Error while reading resource variable _AnonymousVar37 from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource localhost/_AnonymousVar37/N10tensorflow3VarE does not exist.
[[node mul_21/ReadVariableOp (defined at /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:3009) ]] [Op:__inference_keras_scratch_graph_1851]

上記コードは、Kerasのバージョンが2.1.3、Tensorflowがtensorflow-gpu 1.14.0のときはエラーなく動いていたのですが、
バージョン変更するとエラーが発生して途中で止まってしまいます。※1
エラーの原因、改善方法等分かる方がおられましたら宜しくお願い致します。

※前回質問時からの変更点。
・調査して分かったことがあったため、タイトルを「Google Colaboratory上でGANを実行するとFailedPreconditionErrorが発生する」から
「KerasとTensorflowのバージョンを変更するとエラーが発生する」に変更しました。
・KerasとTensorflowのバージョンによってエラー発生有無が変わることが分かったため、※1部分の説明を修正しました。

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

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

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

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

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

guest

回答1

0

自己解決

Google Colaboratory上でGPUを動かしたかったので最新のTensorflowとKerasで動く方法を知りたかったのですが、Tensorflow-gpu 1.15.0、Keras 2.1.3にすることで、動かすことができたので解決済と致します。

投稿2020/05/09 12:58

TOMO6181

総合スコア39

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問