网络编程
位置:首页>> 网络编程>> Python编程>> keras输出预测值和真实值方式

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

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

标签: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))

画一下知识点,我们在继承的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

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com