Python/Keras-为每个时期创建一个具有一个预测的回调 [英] Python/Keras - Creating a callback with one prediction for each epoch
问题描述
我正在使用Keras预测时间序列.作为标准,我使用20个纪元.我想知道我的神经网络对20个纪元中的每个纪元有什么预测.
I'm using Keras to predict a time series. As standard I'm using 20 epochs. I want to know what did my neural network predict for each one of the 20 epochs.
通过使用model.predict,我在所有时期中只得到一个预测(不确定Keras如何选择它).我想要所有预测,或者至少是10个最佳预测.
By using model.predict I'm getting only one prediction among all epochs (not sure how Keras select it). I want all predictions, or at least the 10 best.
根据我以前得到的答案,我应该在每个训练纪元之后通过子类化Callback()
并在on_epoch_end
函数内部的模型上调用predict来实现适当的回调,来计算预测.
According to a previous answer I got, I should compute the predictions after each training epoch by implementing an appropriate callback by subclassing Callback()
and calling predict on the model inside the on_epoch_end
function.
嗯,理论看起来很不错,但是我很难编写代码.有人可以为此提供代码示例吗?
Well, the theory seems in shape but I'm in trouble to code that. Would anyone be able to give a code example on that?
既不确定如何实现Callback()
子类,也不确定如何将其与model.predict
混合到on_epoch_end
函数中.
Not sure how to implement the Callback()
subclassing and neither how to mix that with the model.predict
inside an on_epoch_end
function.
我们将非常感谢您的帮助:)
Your help will be highly appreciated :)
编辑
好吧,我有所进步. 了解如何创建子类以及如何将其链接到model.predict. 但是,我正在为如何创建包含所有预测的列表而绞尽脑汁.下面是我当前的代码:
Well, I evolved a little bit. Found out how to create the subclass and how to link it to the model.predict. However, I'm burning my brain on how to create a list with all the predictions. Below is my current code:
#Creating a Callback subclass that stores each epoch prediction
class prediction_history(Callback):
def on_epoch_end(self, epoch, logs={}):
self.predhis=(model.predict(predictor_train))
#Calling the subclass
predictions=prediction_history()
#Executing the model.fit of the neural network
model.fit(X=predictor_train, y=target_train, nb_epoch=2, batch_size=batch,validation_split=0.1,callbacks=[predictions])
#Printing the prediction history
print predictions.predhis
但是,我所得到的只是最后一个时期的预测列表(与打印模型的效果相同.predict(predictor_train)).
However, all I'm getting with that is a list of predictions of the last epoch (same effect as printing model.predict(predictor_train)).
现在的问题是:如何修改我的代码,以便将其添加到predhis
每个时期的预测?
The question now is: How do I adapt my code so it adds to predhis
the predictions of each one of the epochs?
推荐答案
您正在覆盖每个时期的预测,这就是为什么它不起作用的原因.我会这样:
You are overwriting the prediction for each epoch, that is why it doesn't work. I would do it like this:
class prediction_history(Callback):
def __init__(self):
self.predhis = []
def on_epoch_end(self, epoch, logs={}):
self.predhis.append(model.predict(predictor_train))
通过这种方式,self.predhis现在是一个列表,并且每个预测都在每个时期的末尾附加到列表中.
This way self.predhis is now a list and each prediction is appended to the list at the end of each epoch.
这篇关于Python/Keras-为每个时期创建一个具有一个预测的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!