[python]如何自己跟踪训练过程中的损失值并可视化出来

本文介绍如何在深度学习训练过程中记录损失值,并使用Python和Matplotlib将其可视化,以便于调整超参数和监控模型训练状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 跟踪训练函数的损失值
如果跑的代码中没有显示损失函数的变化趋势,而自己需要根据这个来调整超参,那么可以自己编写函数去实现这一个需求。
首先应该将每次的损失值记录并储存下来。这里以CornerNet的代码为例,代码链接如下:
CornerNet
在train.py函数中,损失值在如下的部分得到:

with stdout_to_tqdm() as save_stdout:
    for iteration in tqdm(range(start_iter + 1, max_iteration + 1), file=save_stdout, ncols=80):
        training = pinned_training_queue.get(block=True)
        training_loss = nnet.train(**training)

        if display and iteration % display == 0:
            print("training loss at iteration {}: {}".format(iteration, training_loss.item()))
        del training_loss

        # if val_iter and validation_db.db_inds.size and iteration % val_iter == 0:
        #     nnet.eval_mode()
        #     validation = pinned_validation_queue.get(block=True)
        #     validation_loss = nnet.validate(**validation)
        #     print("validation loss at iteration {}: {}".format(iteration, validation_loss.item()))
        #     nnet.train_mode()

        if iteration % snapshot == 0:
            nnet.save_params(iteration)

        if iteration % stepsize == 0:
            learning_rate /= decay_rate
            nnet.set_lr(learning_rate)

如果想要记录并储存好其值,加入以下代码即可:

with stdout_to_tqdm() as save_stdout:
    for iteration in tqdm(range(start_iter + 1, max_iteration + 1), file=save_stdout, ncols=80):
        training = pinned_training_queue.get(block=True)
        training_loss = nnet.train(**training)
        loss = training_loss.cpu()
        loss_ = str(loss.data.numpy())
        with open('path', 'a') as f:
            f.write(str(iteration))
            f.write(' ')
            f.write(loss_)
            if iteration < max_iteration:
                f.write(' \r\n')
        if display and iteration % display == 0:
            print("training loss at iteration {}: {}".format(iteration, training_loss.item()))
        del training_loss

        # if val_iter and validation_db.db_inds.size and iteration % val_iter == 0:
        #     nnet.eval_mode()
        #     validation = pinned_validation_queue.get(block=True)
        #     validation_loss = nnet.validate(**validation)
        #     print("validation loss at iteration {}: {}".format(iteration, validation_loss.item()))
        #     nnet.train_mode()

        if iteration % snapshot == 0:
            nnet.save_params(iteration)

        if iteration % stepsize == 0:
            learning_rate /= decay_rate
            nnet.set_lr(learning_rate)

加入的部分为:

        loss = training_loss.cpu()
        loss_ = str(loss.data.numpy())
        with open('path', 'a') as f:
            f.write(str(iteration))
            f.write(' ')
            f.write(loss_)
            if iteration < max_iteration:
                f.write(' \r\n')

解释一下代码
由于深度学习计算loss的时候基本上loss都是cuda的一个tensor变量,储存在cuda中的。是不能够直接复制过来的,所以需要用.cpu()把cuda中的值转移给cpu中储存
然后由于此时转移过去以后还是一个variable变量(就是可以backpropogation来计算grad的一种变量),所以需要用variable.data把其中的数据单独取出来,但是此时还是一个tensor,需要转换成numpy,所以再通过一个.numpy()
f.write()中的必须是一个string类型的数据,所以要转成string
最后if语句是为了在最后一行的时候不要再写入回车了。
path:就是你想把记录下来的数据储存在哪个文件夹下,比如./loss.txt,就是储存在当前路径下的txt文件。这里建议保存成txt文件,以后要用的话就很方便处理。这个txt文件不需要自己新建一个空白,没有的话python会自己建立一个的
open函数中我选择用a参数,而不是用w,这是因为w会抹去之前写过的重新写,最后只剩下最后一对数据了,而我们的目的明显不是这样的,a是从上一次的位置接着写,这就nice了。

2 根据保存好的训练过程中的损失值可视化
“”"

Note: The code is used to show the change trende via the whole training procession.
First: You need to mark all the loss of every iteration
Second: You need to write these data into a txt file with the format like:

iter loss
iter loss

Third: the path is the txt file path of your loss

“”"

import matplotlib.pyplot as plt

def read_txt(path):
with open(path, ‘r’) as f:
lines = f.readlines()
splitlines = [x.strip().split(’ ') for x in lines]
return splitlines

Referenced from Tensorboard(a smooth_loss function:https://blog.youkuaiyun.com/charel_chen/article/details/80364841)

def smooth_loss(path, weight=0.85):
iter = []
loss = []
data = read_txt(path)
for value in data:
iter.append(int(value[0]))
loss.append(int(float(value[1])))
# Note a str like ‘3.552’ can not be changed to int type directly
# You need to change it to float first, can then you can change the float type ton int type
last = loss[0]
smoothed = []
for point in loss:
smoothed_val = last * weight + (1 - weight) * point
smoothed.append(smoothed_val)
last = smoothed_val
return iter, smoothed

if name == “main”:
path = ‘./loss.txt’
loss = []
iter = []
iter, loss = smooth_loss(path)
plt.plot(iter, loss, linewidth=2)
plt.title(“Loss-iters”, fontsize=24)
plt.xlabel(“iters”, fontsize=14)
plt.ylabel(“loss”, fontsize=14)
plt.tick_params(axis=‘both’, labelsize=14)
plt.savefig(’./loss_func.png’)
plt.show()

这里借用了tensorboard 平滑损失曲线代码
————————————————
版权声明:本文为优快云博主「Kurt Sun」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/weixin_43748786/article/details/96432391

### IsaacSim 可视化功能概述 IsaacSim 是 NVIDIA 提供的一个高性能仿真平台,主要用于机器人技术、自主系统和其他复杂物理环境的模拟。在训练过程中启用 IsaacSim 的可视化功能可以帮助开发者更好地监控和调试实验过程。 以下是有关 IsaacSim 可视化的相关内容: #### 启动 IsaacSim 可视化功能的关键组件 IsaacSim 的可视化功能依赖于 Omniverse 平台的核心渲染引擎和技术支持。为了实现高效的可视化效果,通常需要以下几个关键部分的支持: - **Omniverse Kit**: 这是 IsaacSim 的基础框架之一,提供了强大的场景管理和渲染能力[^1]。 - **Experiment Management**: 类似 Neptune 中提到的概念,可以通过标记 (Tag) 和指标 (Metric) 来跟踪不同的实验状态进行可视化展示。 - **Simulation Environment**: 定义仿真的物理特性及其交互行为,这些都可以通过内置工具或自定义脚本进行调整[^3]。 #### 配置与启动流程说明 要成功开启 IsaacSim 的可视化模式,在实际操作前需完成必要的初始化设置工作。这主要包括但不限于以下几点: 1. 确认已安装最新版本的 IsaacGym 或其他相关 SDK; 2. 设置好 GPU 加速选项以提高性能表现; 3. 编写 Python 脚本来加载预构建资产文件 (.usd),同时指定相机视角位置以及其他显示参数; 下面给出一段简单的代码片段作为示例演示如何创建基本窗口布局将摄像头绑定至特定节点上查看整个场景情况: ```python from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) # Import extensions and initialize necessary components here... def setup_camera(): from pxr import Gf, UsdGeom stage = simulation_app.get_stage() camera_path = "/World/Camera" UsdGeom.Camera.Define(stage, camera_path) # Set the transform of the camera to a desired position. camera_xform_cache = UsdGeom.XformCache(0) camera_translation = Gf.Vec3d(-5, -5, 5) camera_rotation = Gf.Rotation(Gf.Vec3d(0, 0, 1), Gf.Vec3d(45, 45, 0)) camera_transform = Gf.Matrix4d().SetTranslateRotateScale( translation=camera_translation, rotation=camera_rotation.GetQuat(), scale=Gf.Vec3d(1., 1., 1.) ) stage.SetDefaultPrim(stage.GetPrimAtPath(camera_path)) setup_camera() while not simulation_app.context.needs_stop(): pass simulation_app.close() ``` 此段程序展示了怎样利用 OmniKit API 构建一个带固定角度摄像机的基础架构,持续更新直至手动停止为止。 #### 数据追踪与呈现方式 除了常规的画面输出外,还可以借助第三方库或者插件进一步增强数据分析能力。例如采用 TensorBoardX 将损失曲线绘制成图表形式直观反映优化进度[^3];又或者是运用 Netron 查看神经网络结构以便快速定位潜在问题所在之处等等。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值