想根据存储下来的损失值绘制损失函数图,现已将损失值以列表得形式存储到 .txt 文件中,这时使用读取出来的数据直接绘图,用到的代码如下所示:
dir_path = r"E:relate_codeGaitpart-masterloss_value.txt"
with open(dir_path, "r") as f:
raw_data = f.read()
data = raw_data[1:-1].split(", ")
然而使用这个数据直接绘图,会出现奇奇怪怪的问题,比如这样:
怎么看,怎么不对!这哪是loss曲线图???
找了很久问题,原来是读取的数据类型出错,读取到的数据为字符串格式,需要把它转化为数值-- float 型
这时候怎么办呢?很简单,一个函数搞定!
import numpy as np x = np.array(['1.1', '2.2', '3.3']) x = np.asfarray(x, float)
重新输出loss曲线:
以下是绘制loss曲线的完整代码:如果存储的有验证过程的损失,把下面代码中的注释部分取消就可以了!
import numpy as np
import matplotlib.pyplot as plt
# 读取存储为txt文件的数据
def data_read(dir_path):
with open(dir_path, "r") as f:
raw_data = f.read()
data = raw_data[1:-1].split(", ")
return np.asfarray(data, float)
# 不同长度数据,统一为一个标准,倍乘x轴
def multiple_equal(x, y):
x_len = len(x)
y_len = len(y)
times = x_len/y_len
y_times = [i * times for i in y]
return y_times
if __name__ == "__main__":
train_loss_path = r"E:relate_codeGaitpart-mastertrain_loss.txt"
# val_loss_path = r"E:relate_codeGaitpart-masterval_loss.txt"
y_train_loss = data_read(train_loss_path)
# y_val_loss = data_read(val_loss_path)
x_train_loss = range(len(y_train_loss))
# x_val_loss = multiple_equal(x_train_loss, range(len(y_val_loss)))
plt.figure()
# 去除顶部和右边框框
ax = plt.axes()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.xlabel('iters')
plt.ylabel('loss')
plt.plot(x_train_loss, y_train_loss, linewidth=1, linestyle="solid", label="train loss")
# plt.plot(x_val_loss, y_val_loss, color="red", linewidth=1, line, label="validation loss")
plt.legend()
plt.title('Loss curve')
plt.show()
日常学习记录,一起交流讨论吧!侵权联系~



