keras輸出預測值和真實值


在使用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

畫一下知識點,我們在繼承的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
View Code

使用yield可以減少內存的使用,而且顯得很高級。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM