predicted_labels = np.argmax(predictions, axis=1) predicted_levels = [] predicted_onehot = np.zeros(predictions.shape) predicted_onehot[np.arange(len(predicted_labels)), predicted_labels] = 1这部分会导致准确率降低吗
时间: 2024-03-04 21:52:57 浏览: 113
这部分代码不会导致准确率降低,实际上它是将模型的预测结果从概率形式转换为了One-Hot编码的形式,以方便计算预测的准确率。
具体来说,np.argmax(predictions, axis=1)这句代码用于找到每个样本中预测概率最高的标签,这些标签将作为我们的预测结果。接下来,我们通过创建一个全零矩阵 predicted_onehot,并将每个样本中预测结果所对应的位置的值设置为1,从而将预测结果转换为One-Hot编码的形式。
predicted_levels = []这句代码则用于存储预测结果所对应的类别标签,它是将预测结果从One-Hot编码的形式转换为了单个标签形式。这在后续计算准确率时会用到。
因此,这部分代码不会导致准确率降低,反而可以方便我们对模型的预测结果进行处理和分析。
相关问题
YOLOv5代码画P_curve的代码
### YOLOv5中P曲线绘制
在YOLOv5源码里,评估模型性能的部分包含了计算精度(Precision, P)、召回率(Recall, R),以及平均精度均值(mAP)[^1]。对于绘制P曲线的需求而言,主要关注的是如何获取不同置信度下的精度变化情况。
#### 获取预测框与真实框匹配关系
为了构建用于绘图的数据集,在`val.py`文件中有如下逻辑处理:
```python
def process_batch(detections, labels):
"""
Return correct predictions matrix. Both sets of boxes are in (x1, y1, x2, y2) format.
Arguments:
detections (Array[N, 6]), x1, y1, x2, y2, conf, class
labels (Array[M, 5]), class, x1, y1, x2, y2
Returns:
correct (Array[N, 10]), for 10 IoU levels
"""
correct = torch.zeros(detections.shape[0], iou_thres, dtype=torch.bool).to(device)
detected = []
for *det_box, conf, cls in detections:
# 遍历每一个检测到的目标框...
ious = box_iou(det_box.unsqueeze(0), label_boxes) # 计算IoU
best_i = ious.max(1)[1]
if ious.max() >= iouv.min():
match_idx = best_i.item()
if match_idx not in detected and labels[match_idx][-1] == cls:
correct[d_idx][ious[best_i] >= iouv] = True
detected.append(match_idx)
return correct
```
此函数负责比较每一对预测边界框和实际标签之间的交并比(IOU),以此来判断哪些预测是正确的,并记录下来以便后续统计使用。
#### 绘制P-R曲线的基础数据准备
接着,在同一文件内存在一段代码用来累积所有测试图片上的TP/FP信息,从而形成最终可用于画图的数据结构:
```python
stats = [] # 存储每个图像的结果
for batch_i, (img_paths, targets, paths, shapes) in enumerate(tqdm(dataloader)):
...
tcls = targets[:, 0].tolist()
stats.append((correct.cpu(), (*[(np.concatenate(x, 0) if isinstance(x, list) else x) for x in [pred[:, :4]]],
pred[:, -1].cpu().numpy(),
np.array([p.stem for p in Path(path).parent.iterdir()]),
targets[:, 1:].cpu().numpy()), img_paths))
```
这里收集到了每次验证过程中产生的正确标记向量以及其他辅助信息,这些都将作为输入传递给下一步骤——即生成PR曲线上所需的点坐标集合。
#### 实现P曲线的具体方法
最后一步是在`utils/metrics.py`中定义了一个名为`ap_per_class`的方法,该方法能够接收上述累积起来的信息,并据此计算出各类别的AP值及其对应的Precision-Confidence曲线:
```python
def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()):
""" Compute the average precision, given the recall and precision curves.
Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
# Arguments
tp: True positives (nparray, nx1 or nx10).
conf: Objectness value from 0-1 (nparray).
pred_cls: Predicted object classes (nparray).
target_cls: True object classes (nparray).
# Returns
The average precision as computed in py-faster-rcnn.
"""
# Sort by objectness
i = np.argsort(-conf)
tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
# Find unique classes
unique_classes, nt = np.unique(target_cls, return_counts=True)
nc = int(pred_cls.max()) + 1 # number of classes, bypass TP masks to get number of classes
px, py = np.linspace(0, 1, 1000), [] # for plotting
ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 100)), np.zeros((nc, 100))
shape = (nc,) + tp.shape # number class, number iou thresholds
tp = tp.reshape(shape)
weights = (tp.cumsum(2) / (np.maximum(tp.sum(axis=2).reshape(shape[:2]+(1,)).repeat(tp.shape[-1], axis=-1), 1e-9)))
for ci, c in enumerate(unique_classes):
i = pred_cls == c
n_l = nt[ci] # number of labels
n_p = i.sum() # number of predictions
if n_p == 0 or n_l == 0:
continue
fpc = (1 - tp[ci]) * weights[ci] # false positive count
mpre = np.hstack([[0.], p[ci], [0.]])
mrec = np.hstack([[0.], r[ci], [1.]])
for j in range(len(px)-1, 0, -1): # go reverse through confidence scores
mpre[j-1] = max(mpre[j-1],mpre[j])
i = np.where(mrec[:-1] != mrec[1:])[0] # points where x-axis changes
ap[c] = sum((mrec[i+1]-mrec[i])*mpre[i+1]) # area under curve using trapezoidal rule
# Plotting part starts here
if plot and len(save_dir)>0:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 8))
ax.plot(r[ci], p[ci], marker='', lw=2, alpha=.7, color="blue",label=f'Class {c} ({names[c]} AP={ap[c]*100:.1f})')
ax.set_xlabel('Recall', fontsize=14)
ax.set_ylabel('Precision', fontsize=14)
ax.grid(True)
ax.legend(fontsize=12)
fig.savefig(Path(save_dir)/f'{Path(img_path).stem}_pr_curve.png') # Save image with PR-curve per class
plt.close(fig)
```
这段代码不仅实现了对各个类别下精确度-查全率曲线的计算,还提供了可视化的功能选项。当参数`plot=True`时,则会在指定目录保存对应类别的PR曲线图表。
阅读全文
相关推荐












