前提・実現したいこと
現在、LSTMを用いたGANの作成をしています。
gan.train_on_batch()を実行するとエラーが出てしまいます。
発生している問題・エラーメッセージ
ValueError Traceback (most recent call last) <ipython-input-36-3c093be40048> in <module> 7 sample_interval = 1 8 ----> 9 train(iterations,batch_size,sample_interval) <ipython-input-35-eb3bb21db1a1> in train(iterations, batch_size, sample_interval) 58 59 #生成器の訓練 ---> 60 g_loss = gan.train_on_batch(z,real) 61 #g_loss = discriminator.train_on_batch(z,real) 62 ~字数制限のため割愛~ ~\anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py in wrapper(*args, **kwargs) 971 except Exception as e: # pylint:disable=broad-except 972 if hasattr(e, "ag_error_metadata"): --> 973 raise e.ag_error_metadata.to_exception(e) 974 else: 975 raise ValueError: in user code: ~字数制限のため割愛~ ValueError: No gradients provided for any variable: ['LSTM_G/lstm_cell_7/kernel:0', 'LSTM_G/lstm_cell_7/recurrent_kernel:0', 'LSTM_G/lstm_cell_7/bias:0', 'dense_7/kernel:0', 'dense_7/bias:0'].
keras
1#実際関数を呼び出してGANのモデルをコンパイルしてあげる 2discriminator = build_discriminatior() 3discriminator.compile(loss='binary_crossentropy', optimizer=Adam(), metrics=['accuracy']) 4generator = build_generator(seq_length,z_dim) 5 6#識別器の学習機能をオフにしてあげる。識別器と生成器を別々に学習させてあげられる 7discriminator.trainable = False 8 9gan = build_gan(generator, discriminator) 10gan.compile(loss='binary_crossentropy', optimizer=Adam())
keras
1generator(生成器)の定義するための関数 2def build_generator(seq_length,z_dim): 3 model = Sequential() 4 model.add(Embedding(input_dim=tango_kazu+1, 5 output_dim=1, 6 #weights=embedding_matrix, # 埋め込み行列を指定 7 trainable=False, # 埋め込み行列を固定(学習時に更新しない) 8 mask_zero=True, 9 name="Embedding_G")) 10 model.add(LSTM(16,input_shape=(seq_length,1),return_sequences=False,name="LSTM_G")) 11 model.add(Dense(seq_length*jigen_length, activation='tanh')) 12 model.add(Reshape((5, 1))) 13 model.summary() 14 return model
試したこと
エラーメッセージ最後の
ValueError: No gradients provided for any variable: ['LSTM_G/lstm_cell_7/kernel:0', 'LSTM_G/lstm_cell_7/recurrent_kernel:0', 'LSTM_G/lstm_cell_7/bias:0', 'dense_7/kernel:0', 'dense_7/bias:0'].
を調べたところ、海外のサイトでよく分かりませんでしたが、タプルや辞書の記述があったので、
keras
1#逆引き辞書作成 2indices_char = dict([(value, key) for (key, value) in char_indices.items()]) 3#上記を下記に書き換え 4indices_char = dict(((value, key) for (key, value) in char_indices.items()))
と書き換えましたが直らず・・・
###コード全文(実装中のため変な部分もあると思います)
# ------------------------------------------------------- # メモリの制限 tensorflow-gpu (2.0.0) # ------------------------------------------------------- import tensorflow as tf physical_devices = tf.config.experimental.list_physical_devices('GPU') if len(physical_devices) > 0: for k in range(len(physical_devices)): tf.config.experimental.set_memory_growth(physical_devices[k], True) print('memory growth:', tf.config.experimental.get_memory_growth(physical_devices[k])) else: print("Not enough GPU hardware devices available") # ------------------------------------------------------- %matplotlib inline import numpy as np import matplotlib.pyplot as plt import sys import os import re import random from keras.datasets import mnist from keras.layers import Dense, Flatten, Reshape, LSTM, Activation, Embedding from keras.layers.advanced_activations import LeakyReLU from keras.models import Sequential from keras.optimizers import Adam from keras.preprocessing.text import Tokenizer from keras.preprocessing import sequence from keras.utils import np_utils from sklearn.neighbors import KNeighborsClassifier #ファイル読み込み path = r'C:\Users\gest\Desktop\ronbun\kasi\sample\1.txt' with open(path, "r", encoding="utf-8") as data: text = data.read().split(",") text = [item.split() for item in text] #print(text,'\n') #list = list.splitlines() #辞書作成 tokenizer = Tokenizer() tokenizer.fit_on_texts(text) char_indices = tokenizer.word_index #print(char_indices,'\n') #逆引き辞書作成 indices_char = dict([(value, key) for (key, value) in char_indices.items()]) print("辞書",indices_char,'\n') tango_kazu = len(indices_char) print("単語数",tango_kazu) #コード表現から数字の表現の変換 list_tokenized = tokenizer.texts_to_sequences(text) print(list_tokenized,'\n') #固定長へ変換 maxlen = 50 texts_vec = sequence.pad_sequences(list_tokenized, maxlen,padding='pre') print("text_vec",texts_vec) #データセットの作成(5は変える余地あり) seq_length = 5 jigen_length = 1 out_size = (seq_length, jigen_length) x = [] #xはモデルに与える入力値、値を5つ保持している y = [] #yは答え、6つ目の値を保持 for line in range(len(texts_vec)): for i in range(len(texts_vec[line])-5): x.append(texts_vec[line][i:i+5]) y.append(texts_vec[line][i+5]) print("x_len",len(x)) x = np.reshape(x,(len(x),seq_length,1))#三次元に変換 #yをone-hot形式へ変換 y = np_utils.to_categorical(y, len(char_indices)+1) #generatorが生成するために入力させてあげるノイズの次元 z_dim = 100 embedding_matrix = np.array([[0.0], [0.0], [1.0]], dtype="float32") #generator(生成器)の定義するための関数 def build_generator(seq_length,z_dim): model = Sequential() model.add(Embedding(input_dim=tango_kazu+1, output_dim=1, #weights=embedding_matrix, # 埋め込み行列を指定 trainable=False, # 埋め込み行列を固定(学習時に更新しない) mask_zero=True, name="Embedding_G")) model.add(LSTM(16,input_shape=(seq_length,1),return_sequences=False,name="LSTM_G") model.add(Dense(seq_length*jigen_length, activation='tanh')) model.add(Reshape((5, 1))) model.summary() return model #discriminator(識別器)の定義するための関数 def build_discriminatior(): model = Sequential() model.add(Embedding(input_dim=tango_kazu+1, output_dim=1, #weights=embedding_matrix, # 埋め込み行列を指定 trainable=False, # 埋め込み行列を固定(学習時に更新しない) mask_zero=True, name="Embedding_D")) model.add(LSTM(16,input_shape=(seq_length,1),return_sequences=False,name="LSTM_D")) model.add(Dense(1, activation='sigmoid')) model.summary() return model #Ganのモデル定義する(生成器と識別器をつなげてあげる)ための関数 def build_gan(generator, discriminator): model = Sequential() model.add(generator) model.add(discriminator) return model #実際関数を呼び出してGANのモデルをコンパイルしてあげる discriminator = build_discriminatior() discriminator.compile(loss='binary_crossentropy', optimizer=Adam(), metrics=['accuracy']) generator = build_generator(seq_length,z_dim) #識別器の学習機能をオフにしてあげる。識別器と生成器を別々に学習させてあげられる discriminator.trainable = False gan = build_gan(generator, discriminator) gan.compile(loss='binary_crossentropy', optimizer=Adam()) losses = [] accuracies = [] #正確さ iteration_checkpoint = [] #学習させてあげるための関数。イテレーション数、バッチサイズ、 何イテレーションで画像を生成して可視化するかを引数にとる def train(iterations, batch_size, sample_interval): x_train = x real = np.ones((batch_size, 1)) fake = np.zeros((batch_size, 1)) for iteration in range(iterations): #本物のデータでバッチを作る #randint(どこから,どこまで,配列の形状) idx = np.random.randint(0, x_train.shape[0], batch_size) print("idx",idx) rtext = x_train[idx] #偽のバッチを作成する #random.normal(平均、分散、出力配列のサイズ) #predict()予測メソッド #z = np.random.normal(0, 1, (batch_size, 100)) z= [[random.randint(1,tango_kazu) for i in range(5)]for j in range(batch_size)] z=np.reshape(z,(len(z),seq_length,1)) gen_text = generator.predict(z) #------------ #識別機の訓練 #------------ #train_on_batch()勾配の更新 #add()対応する要素同士の和を返す d_loss_real = discriminator.train_on_batch(rtext, real) d_loss_fake = discriminator.train_on_batch(gen_text, fake) d_loss, acc = 0.5 * np.add(d_loss_real, d_loss_fake) #------------ #生成器の訓練 #------------ #偽のバッチを作成する z=[[random.randint(1,tango_kazu) for i in range(5)]for j in range(batch_size)] z=np.reshape(z,(len(z),seq_length,1)) gen_text = generator.predict(z) #生成器の訓練 g_loss = gan.train_on_batch(z,real) #g_loss = discriminator.train_on_batch(z,real) #sample_intervalごとに損失値と精度、チェックポイントを保存 if (iteration+1) % sample_interval == 0: #losses.append((d_loss, g_loss)) accuracies.append(acc) iteration_checkpoint.append(iteration+1) #訓練の進捗を出力する print("%d [D loss: %f, acc.: %.2f%%][G loss: %f]" % (iteration + 1, d_loss, 100.0 * accuracies, g_loss)) #答えを生成 sample_texts(generator) #サンプルとしてtextを生成するための関数 def sample_texts(generator, x_train, text_grid_rows =4): z = np.random.normal(0, 1, (text_grid_rows, z_dim)) gen_text = generator.predict(z) cnt = 0 for i in range(text_grid_rows): print(gen_text) cnt += 1 iterations = len(texts_vec) batch_size = 32#round(x.shape[0] / len(texts_vec)) sample_interval = 1 train(iterations,batch_size,sample_interval)
どうかよろしくお願いします。
あなたの回答
tips
プレビュー