保存并继续培训LSTM网络

时间:2018-11-21 13:47:26

标签: python machine-learning keras lstm recurrent-neural-network

我试图使LSTM模型在上一次运行中断之前继续运行。一切顺利,直到我尝试适应网络。然后给出一个错误:

  

ValueError:检查目标时出错:预期density_29具有3个维度,但数组的形状为(672,1)

我查看了thisthis等各种文章,但是我看不出代码有什么问题。

from keras import Sequential
from keras.preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split
from keras.models import Sequential,Model
from keras.layers import LSTM, Dense, Bidirectional, Input,Dropout,BatchNormalization
from keras import backend as K
from keras.engine.topology import Layer
from keras import initializers, regularizers, constraints

from keras.callbacks import ModelCheckpoint
from keras.models import load_model
import os.path
import os
filepath="Train-weights.best.hdf5"
act = 'relu'

model = Sequential()
model.add(BatchNormalization(input_shape=(10, 128)))
model.add(Bidirectional(LSTM(128, dropout=0.5, activation=act, return_sequences=True)))
model.add(Dense(1,activation='sigmoid'))

if (os.path.exists(filepath)):
   print("extending training of previous run")
   model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
   with open('model_architecture.json', 'r') as f:
      model = model_from_json(f.read())
   model.load_weights(filepath)
else:
   print("First run")      
   model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
   model.fit(x_train, y_train, validation_data=(x_val, y_val), epochs=100, batch_size=32, callbacks=callbacks_list, verbose=2)
   model.save_weights(filepath)
   with open('model_architecture.json', 'w') as f:
       f.write(model.to_json())

 checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
 callbacks_list = [checkpoint]

 model.fit(x_train, y_train, validation_data=(x_val, y_val), epochs=100, batch_size=32, callbacks=callbacks_list, verbose=0)

1 个答案:

答案 0 :(得分:1)

尝试add_filter( 'post_class', function($classes){ $product = wc_get_product(); return ($product) ? array('product' 'or-any-class-you-want') : $classes; } , 9999 ); ,您会看到网络中最后一层(即密集层)的输出形状为model.summary()。因此,您提供给模型的标签(即(None, 10, 1))也必须具有y_train的形状。

如果输出形状(num_samples, 10, 1)不是您想要的形状(例如,您希望(None, 10, 1)作为模型的输出形状),则需要修改模型定义。一个简单的修改就是从LSTM层中删除(None, 1)参数。

相关问题