Kerasで次のようなLSTMオートエンコーダーが実装されています。
python
1import numpy as np 2from keras.layers import Input, GRU 3from keras.models import Model 4 5input_feat = Input(shape=(30, 2000)) 6l = GRU( 100, return_sequences=True, activation="tanh", recurrent_activation="hard_sigmoid")(input_feat) 7l = GRU(2000, return_sequences=True, activation="tanh", recurrent_activation="hard_sigmoid")(l) 8model = Model(input_feat, l) 9model.compile(optimizer="RMSprop", loss="mean_squared_error") 10 11feat = np.load("feat.npy") 12model.fit(feat, feat[:, ::-1, :], epochs=200, batch_size=250)
ここで、featは3次元配列で、feat.shape = (269, 30, 2000) です。
このコードをChainerに書き直すために次のようなコードを書きましたが、学習結果をみるに、どこかが間違っているようです。どこに間違いがあるかわかるでしょうか。
python
1import numpy as np 2from chainer import Chain, Variable, optimizers 3import chainer.functions as F 4import chainer.links as L 5 6class GRUAutoEncoder(Chain): 7 def __init__(self): 8 super().__init__() 9 with self.init_scope(): 10 self.encode = L.GRU(2000, 100) 11 self.decode = L.GRU(100, 2000) 12 13 def __call__(self, h, mode): 14 if mode == "encode": 15 h = F.tanh(self.encode(h)) 16 return h 17 18 if mode == "decode": 19 h = F.tanh(self.decode(h)) 20 return h 21 22 def reset(self): 23 self.encode.reset_state() 24 self.decode.reset_state() 25 26 27def main(): 28 feat = np.load("feat.npy") #(269, 30, 2000) 29 30 gru_autoencoder = GRUAutoEncoder() 31 optimizer = optimizers.RMSprop(lr=0.01).setup(gru_autoencoder) 32 33 N = len(feat) 34 batch_size = 250 35 for epoch in range(200): 36 index = np.random.randint(0, N-batch_size+1) 37 input_splices = feat[index:index+batch_size] #(250, 30, 2000) 38 #Encoding 39 input_vector = np.zeros((30, batch_size, 2000), dtype="float32") 40 h = [] 41 for i in range(frame_rate): 42 input_vector[i] = input_splices[:, i, :] #(250, 1, 2000) 43 tmp = Variable(input_vector[i]) 44 h.append(gru_autoencoder(tmp, "encode")) #(250, 100) 45 46 #Decoding 47 output_vector = [] 48 for i in range(frame_rate): 49 tmp = h[i] 50 output_vector.append(gru_autoencoder(tmp, "decode")) 51 52 x = input_vector[0] 53 t = output_vector[0] 54 for i in range(len(output_vector)): 55 x = F.concat((x,input_vector[i]), axis=1) 56 t = F.concat((t,output_vector[i]), axis=1) 57 58 loss = F.mean_squared_error(x, t) 59 gru_autoencoder.cleargrads() 60 loss.backward() 61 optimizer.update() 62 gru_autoencoder.reset() 63 64 65if __name__ == "__main__": 66 main()
Kerasのコードではfit(feat, feat[:, ::-1, :])となっているので、x = input_vector[0]の直前でoutput_vector.reverse()とするべきかと思って、それで学習をさせてみましたが、やはり結果がおかしいです。
ご助言いただけると幸いです。
よろしくお願いします。
追記
L.GRUではなく、 L.NStepGRUを使うべきだったのでしょうか
回答1件
あなたの回答
tips
プレビュー