Keras在训练期间可视化训练误差和测试误差实例

 更新时间:2020年06月16日 10:46:32   作者:bebr  
这篇文章主要介绍了Keras在训练期间可视化训练误差和测试误差实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

详细的解释,读者自行打开这个链接查看,我这里只把最重要的说下

fit() 方法会返回一个训练期间历史数据记录对象,包含 training error, training accuracy, validation error, validation accuracy 字段,如下打印

# list all data in history
print(history.history.keys())

完整代码

# Visualize training history
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy
 
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]
# create model
model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu'))
model.add(Dense(8, kernel_initializer='uniform', activation='relu'))
model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid'))
 
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 
# Fit the model
history = model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10, verbose=0)
 
# list all data in history
print(history.history.keys())
 
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
 
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

补充知识:训练时同时输出实时cost、准确率图

首先定义画图函数:

train_prompt = "Train cost"
cost_ploter = Ploter(train_prompt)
def event_handler_plot(ploter_title, step, cost):
 cost_ploter.append(ploter_title, step, cost)
 cost_ploter.plot()

在训练时如下方式使用:


EPOCH_NUM = 8
# 开始训练
lists = []
step = 0
for epochs in range(EPOCH_NUM):
 # 开始训练
 for batch_id, train_data in enumerate(train_reader()):    #遍历train_reader的迭代器,并为数据加上索引batch_id
  train_cost,sult,lab,vgg = exe.run(program=main_program,  #运行主程序
        feed=feeder.feed(train_data),    #喂入一个batch的数据
        fetch_list=[avg_cost,predict,label,VGG])   #fetch均方误差和准确率
  if step % 10 == 0:    
   event_handler_plot(train_prompt,step,train_cost[0])
  # print(batch_id)
  if batch_id % 10 == 0:         #每100次batch打印一次训练、进行一次测试
   p = [np.sum(pre) for pre in sult]
   l = [np.sum(pre) for pre in lab]
   print(p,l,np.sum(sult),np.sum(lab))
   print('Pass:%d, Batch:%d, Cost:%0.5f' % (epochs, batch_id, train_cost[0]))
  step += 1
 # 保存模型
 if model_save_dir is not None:
  fluid.io.save_inference_model(model_save_dir, ['images'], [predict], exe)

print('训练模型保存完成!')
end = time.time()
print(time.strftime('V100训练用时:%M分%S秒',time.localtime(end-start)))

实时显示准确率用同样的方法

以上这篇Keras在训练期间可视化训练误差和测试误差实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 详解如何在Python中有效调用JavaScript

    详解如何在Python中有效调用JavaScript

    JavaScript和Python都是极为流行的编程语言,并在前端开发和后端开发领域扮演着重要的角色,那么Python如何更好的契合JavaScript呢,下面就跟随小编一起学习一下吧
    2024-02-02
  • python pyinstaller打包exe报错的解决方法

    python pyinstaller打包exe报错的解决方法

    这篇文章主要给大家介绍了关于python pyinstaller打包exe报错的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者使用python具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-11-11
  • 详解Appium+Python之生成html测试报告

    详解Appium+Python之生成html测试报告

    这篇文章主要介绍了详解Appium+Python之生成html测试报告,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01
  • Python小实例混合使用turtle和tkinter让小海龟互动起来

    Python小实例混合使用turtle和tkinter让小海龟互动起来

    Tkinter模块("Tk 接口")是Python的标准Tk GUI工具包的接口.Tk和Tkinter可以在大多数的Unix平台下使用,同样可以应用在Windows和Macintosh系统里.Tk8.0的后续版本可以实现本地窗口风格,并良好地运行在绝大多数平台中
    2021-10-10
  • python实现对服务器脚本敏感信息的加密解密功能

    python实现对服务器脚本敏感信息的加密解密功能

    这篇文章主要介绍了python实现对服务器脚本敏感信息的加密解密功能,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-08-08
  • PyTorch中topk函数的用法详解

    PyTorch中topk函数的用法详解

    今天小编就为大家分享一篇PyTorch中topk函数的用法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this T

    tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU

    这篇文章主要介绍了tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this T的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-06-06
  • VScode连接远程服务器上的jupyter notebook的实现

    VScode连接远程服务器上的jupyter notebook的实现

    这篇文章主要介绍了VScode连接远程服务器上的jupyter notebook的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • Python正则表达式匹配中文用法示例

    Python正则表达式匹配中文用法示例

    这篇文章主要介绍了Python正则表达式匹配中文用法,结合实例形式分析了Python针对中文的正则与文件操作相关技巧,需要的朋友可以参考下
    2017-01-01
  • Python datetime模块的使用示例

    Python datetime模块的使用示例

    这篇文章主要介绍了Python datetime模块的使用示例,帮助大家更好的理解和使用python处理时间,感兴趣的朋友可以了解下
    2021-02-02

最新评论