预测

时间:2015-11-02 09:28:45

标签: python neural-network theano keras

我使用Keras库创建神经网络。我有一个iPython笔记本,以便加载训练数据,初始化网络和#34; fit"神经网络的权重。 最后,我使用save_weights()方法保存权重。 代码如下:

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 Notebook中,我只想使用这些权重并根据输入预测一些输出值。我初始化相同的神经网络,然后加载权重。

# 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'

有什么想法吗? 非常感谢。

1 个答案:

答案 0 :(得分:12)

您需要致电model.compile。这可以在model.load_weights调用之前或之后完成,但必须在指定模型体系结构之后和model.predict调用之前完成。