在keras中实现查看其训练loss值

作者:感到鸭力 时间:2021-03-05 05:29:44 

想要查看每次训练模型后的 loss 值变化需要如下操作


loss_value= [ ]
self.history = model.fit(state,target_f,epochs=1, batch_size =32)
b = abs(float(self.history.history[‘loss'][0]))
loss_value.append(b)
print(loss_value)
loss_value = np.array( loss_value)
x = np.array(range(len( loss_value)))
plt.plot(x, loss_value, c = ‘g')
pt.svefit('c地址‘, dpi= 100)
plt.show()

scipy.sparse 稀疏矩阵 函数集合

pandas 用于在各种文件中提取,并处理分析数据; 有DataFrame数据结构,类似表格。

x=np.linspace(-10, 10, 100) 生成100个在-10到10之间的数组

补充知识:对keras训练过程中loss,val_loss,以及accuracy,val_accuracy的可视化

我就废话不多说了,大家还是直接看代码吧!


hist = model.fit_generator(generator=data_generator_reg(X=x_train, Y=[y_train_a,y_train_g], batch_size=batch_size),
        steps_per_epoch=train_num // batch_size,
        validation_data=(x_test, [y_test_a,y_test_g]),
        epochs=nb_epochs, verbose=1,
        workers=8, use_multiprocessing=True,
        callbacks=callbacks)

logging.debug("Saving weights...")
model.save_weights(os.path.join(db_name+"_models/"+save_name, save_name+'.h5'), overwrite=True)
pd.DataFrame(hist.history).to_hdf(os.path.join(db_name+"_models/"+save_name, 'history_'+save_name+'.h5'), "history")

在训练时,会输出如下打印:

640/640 [==============================] - 35s 55ms/step - loss: 4.0216 - mean_absolute_error: 4.6525 - val_loss: 3.2888 - val_mean_absolute_error: 3.9109

有训练loss,训练预测准确度,以及测试loss,以及测试准确度,将文件保存后,使用下面的代码可以对训练以及评估进行可视化,下面有对应的参数名称:

loss,mean_absolute_error,val_loss,val_mean_absolute_error


import pandas as pd
import matplotlib.pyplot as plt
import argparse
import os
import numpy as np

def get_args():
parser = argparse.ArgumentParser(description="This script shows training graph from history file.")
parser.add_argument("--input", "-i", type=str, required=True,
     help="path to input history h5 file")
args = parser.parse_args()
return args

def main():
args = get_args()
input_path = args.input

df = pd.read_hdf(input_path, "history")
print(np.min(df['val_mean_absolute_error']))
input_dir = os.path.dirname(input_path)
plt.plot(df["loss"], '-o', label="loss (age)", linewidth=2.0)
plt.plot(df["val_loss"], '-o', label="val_loss (age)", linewidth=2.0)
plt.xlabel("Number of epochs", fontsize=20)
plt.ylabel("Loss", fontsize=20)
plt.legend()
plt.grid()
plt.savefig(os.path.join(input_dir, "loss.pdf"), bbox_inches='tight', pad_inches=0)
plt.cla()

plt.plot(df["mean_absolute_error"], '-o', label="training", linewidth=2.0)
plt.plot(df["val_mean_absolute_error"], '-o', label="validation", linewidth=2.0)
ax = plt.gca()
ax.set_ylim([2,13])
ax.set_aspect(0.6/ax.get_data_ratio())
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.xlabel("Number of epochs", fontsize=20)
plt.ylabel("Mean absolute error", fontsize=20)
plt.legend(fontsize=20)
plt.grid()
plt.savefig(os.path.join(input_dir, "performance.pdf"), bbox_inches='tight', pad_inches=0)

if __name__ == '__main__':
main()

来源:https://blog.csdn.net/qq_37640545/article/details/88979428

标签:keras,训练,loss
0
投稿

猜你喜欢

  • Python容器类型转换的3种方法实例

    2022-06-03 13:32:32
  • python 5个实用的技巧

    2022-12-23 14:17:05
  • 5招优化MySQL插入方法

    2009-04-02 10:49:00
  • 使用pycharm和pylint检查python代码规范操作

    2023-06-06 08:02:38
  • 网页栅格系统研究:960的秘密

    2008-10-24 17:03:00
  • Python简单遍历字典及删除元素的方法

    2021-12-31 08:57:51
  • Python matplotlib画图时图例说明(legend)放到图像外侧详解

    2021-03-05 13:42:45
  • 整理一个asp多级树型分类问题的解决方法

    2007-10-17 18:38:00
  • Python读取stdin方法实例

    2022-09-07 19:03:00
  • 对Tensorflow中权值和feature map的可视化详解

    2021-03-31 22:24:39
  • selenium使用chrome浏览器测试(附chromedriver与chrome的对应关系表)

    2022-08-16 16:42:00
  • 楼层数横排比竖排好

    2008-04-26 07:28:00
  • 详解python中的生成器、迭代器、闭包、装饰器

    2023-06-25 19:39:57
  • Python+OpenCV实现将图像转换为二进制格式

    2021-06-25 08:10:33
  • 通过定位控制信息列表下往上的增加

    2008-06-30 14:27:00
  • 分享很实用的css圆角写法[百度有啊提取]

    2009-01-06 13:05:00
  • Python脚本实现格式化css文件

    2023-01-09 19:00:37
  • Pandas中两个dataframe的交集和差集的示例代码

    2022-05-24 14:52:37
  • Python实现以主程序的形式执行模块

    2022-01-14 01:37:00
  • pandas中DataFrame重置索引的几种方法

    2023-06-10 00:26:45
  • asp之家 网络编程 m.aspxhome.com