我正在使用Keras来预测时间序列。作为标准,我使用 20 个纪元。我想通过预测 20 个时期中的每一个来检查我的模型是否学习良好。
通过使用model.predict()
我在所有纪元中只得到一个预测(不确定 Keras 如何选择它)。我想要所有的预测,或者至少是最好的 10 个。
有人知道如何帮助我吗?
我认为这里有点混乱。
纪元仅在训练神经网络时使用,因此当训练停止时(在本例中,在第 20 个纪元之后),则权重对应于在最后一个纪元上计算的权重。
Keras 在每个 epoch 之后的训练期间在验证集上打印当前损失值。如果每个纪元之后的权重没有保存,那么它们就会丢失。 您可以使用 ModelCheckpoint 回调为每个纪元保存权重,然后在模型上加载load_weights重新加载它们。
您可以通过子类化 Callback 并在 on_epoch_end 函数内对模型调用预测来实现适当的回调,从而在每个训练时期后计算预测。
然后要使用它,您可以实例化您的回调,创建一个列表并将其用作 model.fit 的关键字参数回调。
以下代码将完成所需的工作:
import tensorflow as tf
import keras
# define your custom callback for prediction
class PredictionCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
y_pred = self.model.predict(self.validation_data[0])
print('prediction: {} at epoch: {}'.format(y_pred, epoch))
# ...
# register the callback before training starts
model.fit(X_train, y_train, batch_size=32, epochs=25,
validation_data=(X_valid, y_valid),
callbacks=[PredictionCallback()])
如果你想对测试数据进行预测,在训练进行的每个时期之后,你可以试试这个
class CustomCallback(keras.callbacks.Callback):
def __init__(self, model, x_test, y_test):
self.model = model
self.x_test = x_test
self.y_test = y_test
def on_epoch_end(self, epoch, logs={}):
y_pred = self.model.predict(self.x_test, self.y_test)
print('y predicted: ', y_pred)
您需要在 model.fit 期间提及回调
model.sequence()
# your model architecture
model.fit(x_train, y_train, epochs=10,
callbacks=[CustomCallback(model, x_test, y_test)])
与on_epoch_end
类似,keras 还提供了许多其他方法
on_train_begin, on_train_end, on_epoch_begin, on_epoch_end, on_test_begin,
on_test_end, on_predict_begin, on_predict_end, on_train_batch_begin, on_train_batch_end,
on_test_batch_begin, on_test_batch_end, on_predict_batch_begin,on_predict_batch_end