在使用keras搭建神经网络时,有时需要查看一下预测值和真是值的具体数值,然后可以进行一些其他的操作。这几天查阅了很多资料。好像没办法直接access到训练时的数据。所以我们可以通过回调函数,传入新的数据,然后查看预测值和真是值。参考这篇解决:

https://stackoverflow.com/questions/47079111/create-keras-callback-to-save-model-predictions-and-targets-for-each-batch-durin

我的解决方法是这样的:

from keras.callbacks import Callback
import tensorflow as tf
import numpy as np
class my_callback(Callback):
    def __init__(self,dataGen,showTestDetail=True):
        self.dataGen=dataGen
        self.showTestDetail=showTestDetail
        self.predhis = []
        self.targets = []
    def mape(self,y,predict):
        diff = np.abs(np.array(y) - np.array(predict))
        return np.mean(diff / y)
    def on_epoch_end(self, epoch, logs=None):
        x_test,y_test=next(self.dataGen)
        prediction = self.model.predict(x_test)
        self.predhis.append(prediction)
        #print("Prediction shape: {}".format(prediction.shape))
        #print("Targets shape: {}".format(y_test.shape))
        if self.showTestDetail:
            for index,item in enumerate(prediction):
                print(item,"=====",y_test[index],"====",y_test[index]-item)
        testLoss=self.mape(y_test,prediction)
        print("test loss is :{}".format(testLoss))

View Code