zoukankan      html  css  js  c++  java
  • 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可以减少内存的使用,而且显得很高级。

  • 相关阅读:
    文件下载链接
    Python Web服务器
    打印字符串替换
    python 将数据写入excel
    python Telnet通讯
    Python 串口通讯
    monkey 原理,环境搭建、命令详解
    Andriod 四大组件,六大布局
    python练习题100例
    Activity的基本概念与Activity的生命周期
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/10820199.html
Copyright © 2011-2022 走看看