keras输出预测值和真实值方式

作者:超级学渣渣 时间:2021-11-26 20:25:18 

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

画一下知识点,我们在继承的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可以减少内存的使用,而且显得很高级。

补充知识:keras从训练到预测,函数的选择:fit,fit_generator, predict,predict_generator

如下所示:

keras输出预测值和真实值方式

留下回调函数和如何通过预处理来建立生成输入的函数这两个问题

来源:https://www.cnblogs.com/superxuezhazha/p/10820199.html

标签:keras,预测值,真实值
0
投稿

猜你喜欢

  • 从开发人员角度看IE8的开发新特性

    2010-02-26 10:48:00
  • asp如何制作一个小巧的购物车?

    2010-07-07 12:25:00
  • SQL Server日志文件总结及日志满的处理

    2009-03-25 16:17:00
  • PHP如何从txt文件中读取数据详解

    2023-11-15 02:37:32
  • numpy中np.c_和np.r_的用法解析

    2021-02-09 17:54:06
  • Python使用TextRank算法提取关键词

    2021-05-31 07:29:44
  • Python Matplotlib中使用plt.savefig存储图片的方法举例

    2021-11-19 14:08:55
  • 一个简单的像素画小工具

    2010-01-01 15:33:00
  • python切换hosts文件代码示例

    2023-07-19 15:41:43
  • JavaScript match() 方法

    2007-11-04 13:28:00
  • 15个滑动门效果CSS导航菜单实例教程

    2010-02-20 13:02:00
  • 隐藏你的.php文件的实现方法

    2023-10-20 22:58:01
  • 利用Pytorch实现简单的线性回归算法

    2022-09-08 00:00:09
  • 由 IE8 User-Agent 更新想到的

    2009-01-12 18:33:00
  • 关于django python manage.py startapp 应用名出错异常原因解析

    2023-04-04 08:57:28
  • 使用python实现数组、链表、队列、栈的方法

    2021-01-03 22:40:20
  • 通过Turtle库在Python中绘制一个鼠年福鼠

    2021-03-01 03:48:12
  • 用js实现放大镜效果

    2023-09-19 18:29:29
  • phpmyadmin中禁止外网使用的方法

    2023-09-12 01:10:22
  • 网页设计:巧用记事本编辑网页

    2008-02-05 09:00:00
  • asp之家 网络编程 m.aspxhome.com