6
我正在使用Keras庫創建神經網絡。我有一個iPython Notebook來加載訓練數據,初始化網絡並「適應」神經網絡的權重。 最後,我使用save_weights()方法保存了權重。 代碼如下:Keras加載神經網絡的權重/預測時出錯
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
from keras.regularizers import l2
from keras.callbacks import History
[...]
input_size = data_X.shape[1]
output_size = data_Y.shape[1]
hidden_size = 100
learning_rate = 0.01
num_epochs = 100
batch_size = 75
model = Sequential()
model.add(Dense(hidden_size, input_dim=input_size, init='uniform'))
model.add(Activation('tanh'))
model.add(Dropout(0.2))
model.add(Dense(hidden_size))
model.add(Activation('tanh'))
model.add(Dropout(0.2))
model.add(Dense(output_size))
model.add(Activation('tanh'))
sgd = SGD(lr=learning_rate, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mse', optimizer=sgd)
model.fit(X_NN_part1, Y_NN_part1, batch_size=batch_size, nb_epoch=num_epochs, validation_data=(X_NN_part2, Y_NN_part2), callbacks=[history])
y_pred = model.predict(X_NN_part2) # works well
model.save_weights('keras_w')
然後,在另一個IPython的筆記本電腦,我只是想用這些權重和預測給出輸入某些輸出值。我初始化相同的神經網絡,然後加載權重。
# same headers
input_size = 37
output_size = 40
hidden_size = 100
model = Sequential()
model.add(Dense(hidden_size, input_dim=input_size, init='uniform'))
model.add(Activation('tanh'))
model.add(Dropout(0.2))
model.add(Dense(hidden_size))
model.add(Activation('tanh'))
model.add(Dropout(0.2))
model.add(Dense(output_size))
model.add(Activation('tanh'))
model.load_weights('keras_w')
#no error until here
y_pred = model.predict(X_nn)
問題是,顯然,load_weights方法不足以擁有功能模型。我得到一個錯誤:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-17-e6d32bc0d547> in <module>()
1
----> 2 y_pred = model.predict(X_nn)
C:\XXXXXXX\Local\Continuum\Anaconda\lib\site-packages\keras\models.pyc in predict(self, X, batch_size, verbose)
491 def predict(self, X, batch_size=128, verbose=0):
492 X = standardize_X(X)
--> 493 return self._predict_loop(self._predict, X, batch_size, verbose)[0]
494
495 def predict_proba(self, X, batch_size=128, verbose=1):
AttributeError: 'Sequential' object has no attribute '_predict'
任何想法? 非常感謝。
謝謝。有效 :) – Julian