-
-
Notifications
You must be signed in to change notification settings - Fork 15.9k
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
How to make a confusion matrix in YOLOv5 step by step? #10365
Comments
👋 Hello @husnan622, 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 support@ultralytics.com. RequirementsPython>=3.7.0 with all requirements.txt installed including PyTorch>=1.7. To get started: git clone https://github.com/ultralytics/yolov5 # clone
cd yolov5
pip install -r requirements.txt # install EnvironmentsYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):
StatusIf this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training, validation, inference, export and benchmarks on MacOS, Windows, and Ubuntu every 24 hours and on every commit. |
@husnan622 val.py makes confusion matrices automatically. See val.py for usage examples. |
@glenn-jocher I've tried what you suggested regarding val.py but I haven't been able to bring up the confusion matrix image, I don't know what's missing from the command I made and val.py is still scanning the valid dataset even though I have modified val.py to be task=test |
@husnan622 check your runs/val/exp2 directory, confusion matrix is in there. |
@husnan622 if your data.yaml has a test: key then yes you can run python val.py --task test to use your test split. |
Thanks @glenn-jocher Are the weights that I use correct? and usually the code in the confusion matrix is contained actual data path & prediction data path for example y_true and y_pred, where can i find it |
@husnan622 you can use any weights you want as long as they are trained on your --data data.yaml You can access the confusion matrix code in utils/metrics.py: Lines 126 to 220 in 7845cea
|
Thank you so much for your help @glenn-jocher |
@glenn-jocher Previously I was able to generate a confusion matrix using val.py, the results are like the following image: But I want a confusion matrix that only displays True Positive (TP), True Negative (TN), False Positive (FP) and False Negative (FN), for example in the following image: How to generate a confusion matrix that only displays True Positive (TP), True Negative (TN), False Positive (FP) and False Negative (FN)? |
@husnan622 set normalize=False in ConfusionMatrix() |
👋 Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs. Access additional YOLOv5 🚀 resources:
Access additional Ultralytics ⚡ resources:
Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed! Thank you for your contributions to YOLOv5 🚀 and Vision AI ⭐! |
@glenn-jocher I got the confusion matrix as shown, For this matrix the TP is nil(no value), FP is 1 and TN is 0.94 what these indicates exactly and may I know how to improve the values like TP has to get some value, FP has to decrease?? I really appreciate your help. Thanks in advance.. |
@glenn-jocher : For YOLOv5, how do I increase the font size of numbers in the confusion matrix? |
@syamghali to increase the font size of the numbers in the confusion matrix in YOLOv5, you can modify the |
pls. What is the background mean in the confusion matrix image? and how can I remove it? |
@muhanadabdul the background area in the confusion matrix image represents values that are not part of the confusion matrix itself. This area is typically used to display legends or colorbars. To remove the background area, you can modify the |
@muhanadabdul hello, the values you have highlighted in the image represent the number of samples that were not considered in the validation phase. These samples may have been excluded from the validation set for a variety of reasons, such as missing annotations or insufficient image quality. The values can be useful to understand the size of the validation set relative to the full dataset and to identify any potential imbalances or biases in the dataset. However, they are generally not included in the confusion matrix or other validation metrics, as they do not represent true positive or negative results. Please let me know if you have any further questions or concerns. |
@muhanadabdul hello! The value of 0.08 represents the number of samples that were not included in the validation set for the "mobile_use" class. The value of 0.06 represents the percentage of samples for this class that were not included in the validation set. This percentage is calculated as the number of excluded samples (0.08) divided by the total number of samples (1.34) for this class. Regarding whether it's possible to find which images were excluded from the validation set, this depends on how the data was split and stored. If you have access to the code or procedure that was used to split the data, you may be able to identify the excluded images. If the image filenames or IDs are included in the dataset, you may also be able to cross-reference them with the validation set to identify the excluded images. Finally, regarding the question of hiding the V and H columns and their values from the confusion matrix, you can modify the |
Fantastic, many thanks for your dear. |
@muhanadabdul hello! You're very welcome. If you have any further questions or concerns, please don't hesitate to ask. We're here to help! |
Dear Glenn I implemented the detection but at the time of execution the
accuracy was not good so I used with hyperparameters and used for detection
and I also used few(10%) negative images in the training but the confusion
matrix is as shown, What exactly it describes glenn and How to decrease the
1 over there and How should I increase the accuracy. PLease reply asap as
I'm doing the project .
[image: image.png]
…On Wed, 31 May 2023, 08:29 Glenn Jocher, ***@***.***> wrote:
@muhanadabdul <https://github.com/muhanadabdul> hello! You're very
welcome. If you have any further questions or concerns, please don't
hesitate to ask. We're here to help!
—
Reply to this email directly, view it on GitHub
<#10365 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/A53QIF6R5QOXGOLDPVUYAZ3XI2XYLANCNFSM6AAAAAASRDZ2NM>
.
You are receiving this because you commented.Message ID:
***@***.***>
|
@charanlsa dear user, Thank you for reaching out. The confusion matrix you have shared represents the performance of your YOLOv5 model on the validation set. The rows correspond to the ground truth classes, and the columns correspond to the predicted classes. Each element in the matrix represents the number of validation samples that were assigned to a specific ground truth class and predicted class. The diagonal elements represent the number of correct predictions for each class, and the off-diagonal elements represent the number of incorrect predictions. If you are noticing a low accuracy, one possible approach to increasing it is to adjust the hyperparameters of your YOLOv5 model. Some hyperparameters you might consider tuning include the learning rate, batch size, and number of training iterations. Additionally, you may want to consider increasing the size or diversity of your training set to boost overall performance. Regarding the specific class where you are noticing a high number of false positives (i.e., ground truth class 1 and predicted class 0), you may want to consider adjusting the class weights or focal loss coefficients to emphasize this class during training. You may also want to examine the annotations for this class carefully to ensure that they are accurate and complete. I hope this information is helpful. Please let me know if you have any further questions or concerns, and I'll be happy to assist you. Good luck with your project! Best regards, |
Dear, I did not find the plot_confusion_matrix() function in the utils/plots.py ? |
Hi, sorry for the late reply. so when i edit my metrics.py, do I have to
run val.py again?
Pada tanggal Rab, 20 Sep 2023 pukul 07.20 dadin852 ***@***.***>
menulis:
… Hello, are you suggesting that you'd like to remove the background FP/FN
labels?
My approach involves saving the matrix data in metrics.py and then editing
it to create the confusion_matrix.png.
In metrics.py :
def plot(self, save_dir='', names=()):
try:
import seaborn as sn
array = self.matrix / ((self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) if False else 1 ) # normalize
# Save the matrix data
open(f'{my_save_dir}/matrix.txt', 'a+').write(np.array2string(array, separator=','))
array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
...
—
Reply to this email directly, view it on GitHub
<#10365 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AO376HQNGIBNVDVMXGEHRPTX3IZF5ANCNFSM6AAAAAASRDZ2NM>
.
You are receiving this because you commented.Message ID:
***@***.***>
|
@ryecries no worries about the delay! After editing the Once you have made the desired changes in the Let me know if you have any further questions or need any assistance! Cheers! |
hello. I have a question: I trained the YOLOv5 and I got the confusion matrix result (confusion matrix picture). but I want to re-create the confusion matrix picture because I want to change the font size or text in the confusion matrix picture. I always run training again to get the new confusion matrix result. are there any ways to create a new confusion matrix without training? can I use the weight result to re-create the confusion matrix picture? Thank you! |
@RyanTNN hi there! It is not necessary to run the training again to create a new confusion matrix with different font size or text. You can create a new confusion matrix using the existing model weights. The confusion matrix is generated based on the predictions and ground truth labels during the evaluation process. If you want to change the font size or text in the confusion matrix picture, you can modify the code responsible for plotting the matrix. In the Once you have made the desired modifications, you can run the evaluation again using the trained model weights by running the I hope this helps! Let me know if you have any further questions or need any clarifications. |
okay. I got it. Thank you for your time. |
@RyanTNN You're welcome! I'm glad I could help. If you have any more questions or need further assistance, feel free to ask. Happy coding! |
what is the file used for plotting confusion matrix for yolov7 |
@glenn-jocher . could you please help me get confusion matrix and accuracy score for yolov7 on custom dataset |
@Joshnavarma It looks like the image link you provided is broken. To better assist you, could you please provide more details or a valid link for the confusion matrix image? Thank you! |
@Joshnavarma Thank you for sharing the confusion matrix image. It seems that the provided link is not accessible. If you could upload the image to a public image hosting service (such as Imgur or PostImage) and share the new link, I would be happy to take a look. Regarding your question about the mAP score discrepancies, achieving 85.2% mAP on a custom dataset with 6k images after 50 epochs is certainly a notable result. However, it is essential to investigate potential factors that may have contributed to this high mAP score, such as the data distribution, augmentation techniques, and the balance of classes in your dataset. Additionally, changes in hyperparameters like batch size and the number of epochs can also impact the training process. For the varying mAP scores obtained with different training configurations, it's important to perform a thorough investigation of any alterations made during the training process, such as changes in the dataset, data preprocessing, augmentation, and the impact of different hyperparameters. As you're working on your final year project, understanding and justifying the impact of these factors on your results will be valuable. I recommend thoroughly reviewing your training process and experimenting with different configurations to understand the effects on performance. If you need further assistance troubleshooting the confusion matrix issue or analyzing the differences in mAP scores, please feel free to provide additional details. I'm here to help! |
https://postimg.cc/XX7t1B0G |
@Joshnavarma thank you for sharing the image. However, the provided link still seems to be inaccessible. Could you double-check the link or provide an alternative method to access the confusion matrix image? It's important for me to review the confusion matrix to better assist you. Thank you! |
Hi @glenn-jocher, how can I only show the A, B and D classes for confusion matrix? |
Hello @wjlim-14, it seems there's still an issue with the image link you've provided. However, to address your question about showing only specific classes (A, B, and D) in the confusion matrix: Currently, the YOLOv5 Here's a general approach you could take:
This would require custom coding on your part. You can refer to the If you're not comfortable with modifying the code, another workaround is to temporarily remove the data for the classes you don't want to include from your dataset and then run Remember to backup your data and code before making any changes, and ensure you revert any temporary dataset changes after you're done. If you manage to get the correct image link or upload the image to a different hosting service, I'll be happy to take a look at the confusion matrix issue you're facing. |
@jahid-coder hello! Given that the image link you've shared for the confusion matrix isn't accessible, I'm unable to view the specifics of your confusion matrix directly. However, I’ll explain generally what a confusion matrix represents. A confusion matrix is a table often used to describe the performance of a classification model on a set of test data for which the true values are known. Each row of the matrix represents the instances in a predicted class, while each column represents the instances in an actual class (or vice versa). The diagonal elements represent correct predictions, whereas off-diagonal elements are misclassifications. If you're able to provide a working image link or more specific details about your confusion matrix, I'd be more than happy to give a more tailored explanation! 😊 |
@glenn-jocher thanks for your general explanation, I want to know specifically about this share confusion matrix. Actually i want to know explanation of this confusion matrix. What happened here and how to summarize about my model from this confusion matrix graph. |
Hello @jahid-coder! Unfortunately, the image link you've provided for the confusion matrix doesn't seem to be accessible, so I'm unable to view and discuss the specifics of your model’s performance. However, in general, you can interpret a confusion matrix by observing:
To summarize your model from the confusion matrix:
Once the image becomes accessible, I’d be happy to provide a more specific analysis. Make sure the image is properly uploaded or consider hosting it on a reliable image hosting platform for sharing. 🖼️😊 |
Hello @Killuagg, Thank you for reaching out and sharing your confusion matrix image! 😊 To address your question about why your confusion matrix only shows a value of 0.9 and not other values:
To better assist you, could you please provide a bit more context or a minimum reproducible code example? This will help us understand the issue more clearly and provide a more accurate solution. You can refer to our Minimum Reproducible Example guide for more details on how to share this. Additionally, please ensure that you are using the latest versions of Looking forward to your response so we can assist you further! 🚀 |
I can i make the value show to all class in the confusion matrix. I think it is impossible to relate the problem with class imbalance and thresholding. Even the class is imbalance and thresholding, it at least will show the value of each box. All of my train does not have value of confusion matrix in each box |
Hello @Killuagg, Thank you for your detailed follow-up! 😊 To ensure we can assist you effectively, could you please provide a minimum reproducible code example? This will help us understand the specific issue you're encountering with the confusion matrix. You can refer to our Minimum Reproducible Example guide for more details on how to share this. Having this information is crucial for us to reproduce the bug and investigate a solution. In the meantime, please ensure that you are using the latest versions of If you have already verified that you are using the latest versions and the issue persists, here are a few additional steps you can try:
Here is a small snippet to help you visualize the confusion matrix with all values: import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
# Assuming y_true and y_pred are your ground truth and predictions
cm = confusion_matrix(y_true, y_pred)
sns.heatmap(cm, annot=True, fmt='g')
plt.xlabel('Predicted')
plt.ylabel('True')
plt.show() This code uses If you continue to experience issues, please share the code and any relevant details so we can assist you further. Thank you for your patience and cooperation! |
Visualization Settings: Sometimes, the visualization settings might be affecting the display of values. Ensure that the settings are configured to display all values, even if they are zero. Based on that,where can i fixed that and where it is? |
Hello @Killuagg, Thank you for your patience and for providing more context! 😊 To address your question about visualization settings, you can adjust the settings in the code responsible for generating and displaying the confusion matrix. Here’s a step-by-step guide to help you ensure that all values, including zeros, are displayed in the confusion matrix:
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
# Assuming y_true and y_pred are your ground truth and predictions
cm = confusion_matrix(y_true, y_pred)
# Create a heatmap with annotations
sns.heatmap(cm, annot=True, fmt='g', cmap='Blues', cbar=False)
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.show() In this code:
If you still encounter issues, please provide a minimum reproducible code example as outlined in our Minimum Reproducible Example guide. This will help us reproduce the issue on our end and investigate a solution more effectively. Additionally, please verify that you are using the latest versions of Thank you for your cooperation, and feel free to reach out if you have any more questions or need further assistance! 🚀 |
code: YOLOv5 🚀 by Ultralytics, AGPL-3.0 license"""Model validation metrics.""" import math import matplotlib.pyplot as plt from utils import TryExcept, threaded def fitness(x): def smooth(y, f=0.05): def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir=".", names=(), eps=1e-16, prefix=""):
def compute_ap(recall, precision):
class ConfusionMatrix:
def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
def box_iou(box1, box2, eps=1e-7):
def bbox_ioa(box1, box2, eps=1e-7):
def wh_iou(wh1, wh2, eps=1e-7): Plots ----------------------------------------------------------------------------------------------------------------@threaded
@threaded
|
is there a problem with the confusion matrix?.why i cannot generate each value for each box? |
Hello @Killuagg, Thank you for sharing your code and the confusion matrix image! 😊 It looks like you're on the right track, but there might be a small issue with how the confusion matrix values are being displayed. Let's ensure that all values, including zeros, are properly annotated. Here’s a refined version of your class ConfusionMatrix:
# Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
def __init__(self, nc, conf=0.25, iou_thres=0.45):
"""Initializes ConfusionMatrix with given number of classes, confidence, and IoU threshold."""
self.matrix = np.zeros((nc + 1, nc + 1))
self.nc = nc # number of classes
self.conf = conf
self.iou_thres = iou_thres
def process_batch(self, detections, labels):
# (existing code)
pass
def tp_fp(self):
# (existing code)
pass
@TryExcept("WARNING ⚠️ ConfusionMatrix plot failure")
def plot(self, normalize=True, save_dir="", names=()):
"""Plots confusion matrix using seaborn, optional normalization; can save plot to specified directory."""
import seaborn as sn
array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1) # normalize columns
fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)
nc, nn = self.nc, len(names) # number of classes, names
sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size
labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels
ticklabels = (names + ["background"]) if labels else "auto"
with warnings.catch_warnings():
warnings.simplefilter("ignore") # suppress empty matrix RuntimeWarning: All-NaN slice encountered
sn.heatmap(
array,
ax=ax,
annot=True, # Ensure all values are annotated
annot_kws={"size": 8},
cmap="Blues",
fmt=".2f",
square=True,
vmin=0.0,
xticklabels=ticklabels,
yticklabels=ticklabels,
).set_facecolor((1, 1, 1))
ax.set_xlabel("True")
ax.set_ylabel("Predicted")
ax.set_title("Confusion Matrix")
fig.savefig(Path(save_dir) / "confusion_matrix.png", dpi=250)
plt.show(fig)
def print(self):
# (existing code)
pass This modification ensures that all values, including zeros, are annotated in the confusion matrix. The key change is setting If the issue persists, please ensure:
If you continue to experience issues, please provide a minimum reproducible code example as outlined in our Minimum Reproducible Example guide. This will help us reproduce the issue on our end and investigate a solution more effectively. Thank you for your cooperation, and feel free to reach out if you have any more questions or need further assistance! 🚀 |
Search before asking
Question
I've done model training using YOLOv5 and got pretty good performance. Therefore I want to make a confusion matrix for my needs. But I don't know how to make it and I've tried several tutorials and I still fail. Please help to explain step by step how to make a confusion matrix on YOLOv5 🙏🏻
Additional
No response
The text was updated successfully, but these errors were encountered: