Faster-Rcnn的loss曲线可视化

本文介绍了一种简单的方法来绘制Faster R-CNN训练过程中的Loss曲线。作者利用Python脚本解析训练日志文件,并提取迭代次数及Loss值,最终使用Matplotlib绘制出Loss变化趋势图。

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

       由于要写论文需要画loss曲线,查找网上的loss曲线可视化的方法发现大多数是基于Imagenat的一些方法,在运用到Faster-Rcnn上时没法用,本人不怎么会编写代码,所以想到能否用python直接写一个代码,读取txt然后画出来,参考大神们的博客,然后总和总算一下午时间,搞出来了,大牛们不要见笑。

        首先,在训练Faster-Rcnn时会自己生成log文件,大概在/py-faster-rcnn/experiments/logs文件下,把他直接拿出来,放在任意位置即可,因为是txt格式,可以直接用,如果嫌麻烦重命名1.txt.接下来就是编写程序了

一下为log基本的格式

I0530 08:54:19.183091 10143 solver.cpp:229] Iteration 22000, loss = 0.173712
I0530 08:54:19.183137 10143 solver.cpp:245]     Train net output #0: rpn_cls_loss = 0.101713 (* 1 = 0.101713 loss)
I0530 08:54:19.183145 10143 solver.cpp:245]     Train net output #1: rpn_loss_bbox = 0.071999 (* 1 = 0.071999 loss)
I0530 08:54:19.183148 10143 sgd_solver.cpp:106] Iteration 22000, lr = 0.001

通过发现,我们只需获得 Iteration 和loss就行

#!/usr/bin/env python
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import math
import re
import pylab
from pylab import figure, show, legend
from mpl_toolkits.axes_grid1 import host_subplot

# read the log file
fp = open('2.txt', 'r')

train_iterations = []
train_loss = []
test_iterations = []
#test_accuracy = []

for ln in fp:
  # get train_iterations and train_loss
  if '] Iteration ' in ln and 'loss = ' in ln:
    arr = re.findall(r'ion \b\d+\b,',ln)
    train_iterations.append(int(arr[0].strip(',')[4:]))
    train_loss.append(float(ln.strip().split(' = ')[-1]))
    
fp.close()

host = host_subplot(111)
plt.subplots_adjust(right=0.8) # ajust the right boundary of the plot window
#par1 = host.twinx()
# set labels
host.set_xlabel("iterations")
host.set_ylabel("RPN loss")
#par1.set_ylabel("validation accuracy")

# plot curves
p1, = host.plot(train_iterations, train_loss, label="train RPN loss")
#p2, = par1.plot(test_iterations, test_accuracy, label="validation accuracy")

# set location of the legend, 
# 1->rightup corner, 2->leftup corner, 3->leftdown corner
# 4->rightdown corner, 5->rightmid ...
host.legend(loc=1)

# set label color
host.axis["left"].label.set_color(p1.get_color())
#par1.axis["right"].label.set_color(p2.get_color())
# set the range of x axis of host and y axis of par1
host.set_xlim([-1500,60000])
host.set_ylim([0., 1.6])

plt.draw()
plt.show()
绘图结果

参考博客地址:

http://blog.youkuaiyun.com/YhL_Leo/article/details/51774966

### 如何实现 Faster R-CNN 结果的可视化 为了实现 Faster R-CNN 的结果可视化,通常会利用 `demo.py` 文件来加载预训练模型并对单张图片执行目标检测并绘制边界框。此过程涉及准备环境、设置配置文件以及编写或调整 Python 脚本来完成绘图操作。 #### 准备工作 确保已经安装了必要的依赖库,并且按照官方指南设置了开发环境[^4]。对于 PyTorch 版本的 Faster R-CNN 实现来说,还需要确认已成功构建好 GeneralizedRCNN 类实例及其组件(backbone, rpn, roi_heads)[^2]。 #### 使用 `demo.py` 在大多数开源框架中,都会有一个名为 `tools/demo.py` 或者类似的脚本用于快速演示模型的功能。这个脚本能帮助用户轻松地看到模型预测的效果而无需深入了解内部细节。要使用它来进行结果可视化: 1. 修改 `demo.py` 中的相关参数以适应个人需求; 2. 提供一张或多张待测图片作为输入; 3. 执行如下命令启动程序: ```bash python tools/demo.py --config-file PATH_TO_CONFIG_FILE \ --input INPUT_IMAGE_PATH \ --output OUTPUT_DIR \ [--confidence-threshold CONFIDENCE_THRESHOLD] ``` 这里的关键选项解释如下: - `--config-file`: 配置文件路径,包含了关于网络结构、超参设定等方面的信息。 - `--input`: 输入图像的位置。 - `--output`: 输出目录,保存带有标注后的图像。 - `[--confidence-threshold]`: (可选) 设置分类得分阈值,默认情况下可能为 0.7 左右。 当上述命令被执行之后,将会读取给定的图片并通过调用预训练好的 Faster R-CNN 模型对其进行推理分析,最后将识别到的对象连同其位置信息一起画回到原始图片上形成最终视觉化成果[^5]。 #### 自定义绘图逻辑 如果希望进一步定制可视化的样式,则可以在 `demo.py` 内部找到负责渲染的部分进行修改。一般而言,这部分代码会涉及到 OpenCV 库中的图形绘制功能,比如线条颜色的选择、字体大小等都可以根据实际应用场景灵活调整。 以下是简化版自定义绘图逻辑的例子: ```python import cv2 from PIL import ImageDraw, ImageFont def draw_bounding_boxes(image_path, predictions, output_dir): image = cv2.imread(image_path) # 创建PIL对象以便更方便地处理文字显示 pil_image = Image.fromarray(cv2.cvtColor(image,cv2.COLOR_BGR2RGB)) drawer = ImageDraw.Draw(pil_image) font = ImageFont.load_default() for box in predictions['boxes']: x_min, y_min, x_max, y_max = map(int, box.tolist()) label = f"{predictions['labels'][i]} {scores[i]:.2f}" color = tuple(map(int, np.random.randint(0, 256, size=3))) # 绘制矩形边框 drawer.rectangle([x_min, y_min, x_max, y_max], outline=color, width=3) # 添加标签和分数 text_width, _ = drawer.textsize(label, font=font) drawer.rectangle( [(x_min, y_min), (x_min + text_width + 8, y_min + 16)], fill=color ) drawer.text((x_min + 4, y_min), label, fill='white', font=font) result_img = cv2.cvtColor(np.array(pil_image),cv2.COLOR_RGB2BGR) save_name = os.path.join(output_dir, 'result_' + os.path.basename(image_path)) cv2.imwrite(save_name, result_img) ``` 这段代码展示了如何遍历每一个预测出来的边界框,并为其分配随机的颜色,同时把类别名称与置信度附加于顶部附近区域。注意这里的 `ImageFont.load_default()` 只是一个简单的例子,在生产环境中建议替换为自己喜欢的字体文件。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值