Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Classes with no instances causes legend misalignment #5158

Closed
NauchtanRobotics opened this issue Oct 13, 2021 · 4 comments · Fixed by #5174
Closed

Classes with no instances causes legend misalignment #5158

NauchtanRobotics opened this issue Oct 13, 2021 · 4 comments · Fixed by #5174
Labels
bug Something isn't working

Comments

@NauchtanRobotics
Copy link
Contributor

NauchtanRobotics commented Oct 13, 2021

🐛 Bug

I prepared some annotations which were then filtered to removed annotations for the first three classes. This cause problems with plot legends.

When there are not instances of bounding boxes for certain classes in the dataset.yaml file, the legends for various plots can be misaligned. See labels.jpg correctly shows no count for instances of class "D00", "D10" and "D20" whilst "D40" and "EB" do have bars. However, PR_curve.png mistakenly marks "D00" and "D01" in the legend as having data (but not "D40" and "EB" classes).

To Reproduce (REQUIRED)

Prepare annotation labels that do not have any instances of the first three classes listed in the dataset yaml file, then run:

python train.py --img 640 --batch 54 --device 0,1 --cfg models/yolov5x_road.yaml --data filtered_dataset.yaml --weights weights/IMSC/last_95.pt --hyp ./data/hyp.scratch.yaml --name TEST --epochs 1

where filtered_dataset.yaml is:

train: datasets/bbox_collation_6_D40_EB_only/train/images/
val: datasets/bbox_collation_6_split_D40_EB_only/val/images/
nc: 5
names: ['D00','D10','D20','D40', 'EB']

Expected behavior

PR Curve should have lines for classes "D40" and "EB" marked in the legend but nothing for the first three classes "D00", "D10" and "D20".

Context

I realise that it would be unusual to plan to have no bounding box instances for the first 3 class names, but things can evolve this way over time. In my case, I didn't want to use all of the classes provided by an open source data set. I noticed that having classes with low instance counts could harm the detection performance of my priority classes (even when I remove class weighting). So I filter these out when training a model for production, but I retain data for those first three classes for a time in the future when I have accumulated higher instance counts. Hopefully after increasing the instance counts of those classes, the performance of priority classes will not be reduced.
labels
PR_curve
.

@NauchtanRobotics NauchtanRobotics added the bug Something isn't working label Oct 13, 2021
@github-actions
Copy link
Contributor

github-actions bot commented Oct 13, 2021

👋 Hello @NauchtanRobotics, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide screenshots and minimum viable code to reproduce your issue, otherwise we can not help you.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online W&B logging if available.

For business inquiries or professional support requests please visit https://ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com.

Requirements

Python>=3.6.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

$ git clone https://github.com/ultralytics/yolov5
$ cd yolov5
$ pip install -r requirements.txt

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

CI CPU testing

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training (train.py), validation (val.py), inference (detect.py) and export (export.py) on MacOS, Windows, and Ubuntu every 24 hours and on every commit.

@glenn-jocher
Copy link
Member

glenn-jocher commented Oct 13, 2021

@NauchtanRobotics hi, thank you for your feature suggestion on how to improve YOLOv5 🚀!

The fastest and easiest way to incorporate your ideas into the official codebase is to submit a Pull Request (PR) implementing your idea, and if applicable providing before and after profiling/inference/training results to help us understand the improvement your feature provides. This allows us to directly see the changes in the code and to understand how they affect workflows and performance.

Please see our ✅ Contributing Guide to get started.

The curve plotting functions are in metrics.py here:

yolov5/utils/metrics.py

Lines 294 to 333 in b754525

def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
# Precision-recall curve
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
py = np.stack(py, axis=1)
if 0 < len(names) < 21: # display per-class legend if < 21 classes
for i, y in enumerate(py.T):
ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
else:
ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
ax.set_xlabel('Recall')
ax.set_ylabel('Precision')
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
fig.savefig(Path(save_dir), dpi=250)
plt.close()
def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
# Metric-confidence curve
fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
if 0 < len(names) < 21: # display per-class legend if < 21 classes
for i, y in enumerate(py):
ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
else:
ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
y = py.mean(0)
ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
fig.savefig(Path(save_dir), dpi=250)
plt.close()

@NauchtanRobotics
Copy link
Contributor Author

PR submitted #5174

@NauchtanRobotics
Copy link
Contributor Author

p.s. This problem was effecting more than just the PR_curve.png. Was effecting all plots called in ap_per_class() here:

    if plot:
        plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
        plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
        plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
        plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')

@glenn-jocher glenn-jocher linked a pull request Oct 14, 2021 that will close this issue
NauchtanRobotics added a commit to NauchtanRobotics/yolov5 that referenced this issue Oct 14, 2021
NauchtanRobotics added a commit to NauchtanRobotics/yolov5 that referenced this issue Oct 14, 2021
glenn-jocher added a commit that referenced this issue Oct 14, 2021
* legend-labels Adjust legend labels for classes without instances.

* #5158 Re-indexed series names: only classes containing data.

* #5158 Re-indexed series names: only classes containing data.

* Cleanup

Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
BjarneKuehl pushed a commit to fhkiel-mlaip/yolov5 that referenced this issue Aug 26, 2022
* legend-labels Adjust legend labels for classes without instances.

* ultralytics#5158 Re-indexed series names: only classes containing data.

* ultralytics#5158 Re-indexed series names: only classes containing data.

* Cleanup

Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants