loss曲线绘制出错---字符串修改为float型(附代码)

将字符串数组变成数值型数组

想根据存储下来的损失值绘制损失函数图,现已将损失值以列表得形式存储到 .txt 文件中,这时使用读取出来的数据直接绘图,用到的代码如下所示:

dir_path = r"E:\relate_code\Gaitpart-master\loss_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_code\Gaitpart-master\train_loss.txt"
    # val_loss_path = r"E:\relate_code\Gaitpart-master\val_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, linestyle="solid", label="validation loss")

    plt.legend()

    plt.title('Loss curve')
    plt.show()

日常学习记录,一起交流讨论吧!侵权联系~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WYKB_Mr_Q

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值