在使用keras搭建神經網絡時,有時需要查看一下預測值和真是值的具體數值,然后可以進行一些其他的操作。這幾天查閱了很多資料。好像沒辦法直接access到訓練時的數據。所以我們可以通過回調函數,傳入新的數據,然后查看預測值和真是值。參考這篇解決:
我的解決方法是這樣的:
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))
畫一下知識點,我們在繼承的callback中實現 on_epoch_end方法:
x_test,y_test=next(self.dataGen)
這個數據生成方法是這樣的
import numpy as np def shuffleDatas(x,y): shuffleIndex=np.arange(len(x)) np.random.shuffle(shuffleIndex) x=x[shuffleIndex] y=y[shuffleIndex] return x,y def dataGen(x,y,batchsize=8,shuffle=True): assert len(x) == len(y) while True: if shuffle: x,y=shuffleDatas(x,y) index=0 while index+batchsize<len(x): yield (x[index:index+batchsize],y[index:index+batchsize]) index=index+batchsize
使用yield可以減少內存的使用,而且顯得很高級。
