ImportError: cannot import name ‘get_num_classes’ from ‘torchmetrics.utilities.data’

解决办法:

问题原因:torchmetrics版本与项目不匹配,笔者出错的环境使用的是 torchmetrics 0.8,库升级后部分代码进行了重构,导致某些函数“过时”,例如此例的“get_num_classes”。

解决方法:降级torchmetrics,此处我选择安装 torchmetrics 0.5

how to downgrade torchmetrics?:

conda uninstall torchmetrics
conda install torchmetrics=0.5

此处的0.5只是一个例子,如果后续出现0.5对其他库不兼容的话,也可以尝试慢慢调高版本,或者使用新的使用方法对get_num_classes相关的代码进行重写。

关于torchmetrics的更多内容:

简介:

torchmetrics是一个用于评估PyTorch模型的库。它提供了一组常用的度量,如准确性,精确度,召回率等。这些度量可以用来评估分类和回归模型的性能。

torchmetrics github:Lightning-AI/metrics: Machine learning metrics for distributed, scalable PyTorch applications. (github.com)

一、torchmetrics的基本使用方法如下:

  1. 安装torchmetrics库:在终端中运行”pip install torchmetrics”。
  2. 导入所需的度量:在代码中从torchmetrics库中导入所需的度量,如Accuracy,Precision,Recall等。
  3. 使用度量评估模型:在训练模型并对其进行评估之后,使用所选择的度量评估模型。例如,使用Accuracy()评估分类模型的准确性。
  4. 获取结果:调用该度量的“compute”方法以获取结果。例如,调用acc(y_pred, y_true)来获取准确性的结果。
  5. 多个度量:可以在同一时间使用多个度量评估模型,并使用不同的度量获取结果。

这是一个简单的示例代码:

from torchmetrics import Accuracy

acc = Accuracy()

y_pred = torch.tensor([1, 2, 3, 4, 5])
y_true = torch.tensor([1, 2, 3, 4, 5])

acc_result = acc(y_pred, y_true)
print(acc_result)

结果为1.0,表示预测值和真实值完全相同。

二、get_num_classes的使用方法

get_num_classes是torchmetrics库中的一个函数,它可以帮助你获取给定数据集中类的数量。

使用方法如下:

  1. 从torchmetrics库中导入函数:使用from torchmetrics import get_num_classes
  2. 定义你的数据集,可以是numpy数组或torch.Tensor
  3. 调用函数并传入数据集,如 get_num_classes(y)
  4. 它会返回一个整数,表示类别数量.

下面是一个简单的示例代码:

from torchmetrics import get_num_classes

y_true = torch.tensor([1, 2, 3, 4, 5])
n_classes = get_num_classes(y_true)
print(n_classes)

结果为5,表示有5个类别

注意:如果你的数据集是使用one-hot编码的,那么不能使用get_num_classes函数。

三、attributeerror: module torchmetrics has no attribute f1

提到的错误表明torchmetrics库中没有名为’f1’的属性。F1分数是一种用于评估二元分类模型性能的常用度量,它衡量了精确率和召回率之间的平衡。如果希望在torchmetrics库中使用F1分数,则需要自己实现该度量。

可以使用torchmetrics库中的Precision,Recall度量来计算F1分数,公式为: F1 = 2 * (precision * recall) / (precision + recall)

如果不想实现F1分数,您可以使用其他库如 sklearn , scikit-learn 中的f1_score来计算F1分数

from sklearn.metrics import f1_score

y_pred = [0, 1, 0, 0, 1]
y_true = [0, 1, 0, 1, 1]

f1 = f1_score(y_true, y_pred)
print(f1)

23 Replies to “ImportError: cannot import name ‘get_num_classes’ from ‘torchmetrics.utilities.data’”

  1. Thanks for your handy post. In recent times, I have come to be able to understand that the actual symptoms of mesothelioma are caused by the build up connected fluid regarding the lining on the lung and the upper body cavity. The disease may start from the chest vicinity and multiply to other limbs. Other symptoms of pleural mesothelioma include fat loss, severe inhaling and exhaling trouble, nausea, difficulty eating, and puffiness of the neck and face areas. It really should be noted that some people with the disease usually do not experience just about any serious indicators at all.

  2. I was just searching for this info for some time. After six hours of continuous Googleing, at last I got it in your web site. I wonder what’s the lack of Google strategy that do not rank this kind of informative sites in top of the list. Normally the top web sites are full of garbage.

  3. Thx for your post. I would like to comment that the price of car insurance will vary from one plan to another, for the reason that there are so many different facets which give rise to the overall cost. For instance, the brand name of the car or truck will have an enormous bearing on the purchase price. A reliable old family car or truck will have an inexpensive premium than the usual flashy sports vehicle.

  4. Thanks for your content. One other thing is when you are selling your property all on your own, one of the challenges you need to be alert to upfront is how to deal with home inspection reports. As a FSBO supplier, the key towards successfully moving your property plus saving money on real estate agent income is understanding. The more you know, the easier your property sales effort will be. One area when this is particularly essential is information about home inspections.

  5. What i do not understood is actually how you’re not actually much more well-liked than you might be right now. You are so intelligent. You realize thus considerably relating to this subject, made me personally consider it from so many varied angles. Its like women and men aren’t fascinated unless it?s one thing to do with Lady gaga! Your own stuffs great. Always maintain it up!

  6. I?m impressed, I need to say. Really rarely do I encounter a blog that?s both educative and entertaining, and let me tell you, you may have hit the nail on the head. Your idea is outstanding; the difficulty is one thing that not enough people are talking intelligently about. I am very glad that I stumbled across this in my search for something relating to this.

  7. One thing I’d prefer to comment on is that weightloss routine fast may be accomplished by the perfect diet and exercise. A person’s size not only affects the look, but also the complete quality of life. Self-esteem, depression, health risks, plus physical ability are disturbed in extra weight. It is possible to make everything right and at the same time having a gain. In such a circumstance, a condition may be the primary cause. While too much food rather than enough workout are usually to blame, common medical ailments and popular prescriptions could greatly add to size. I am grateful for your post in this article.

  8. I do agree with all of the ideas you have presented in your post. They are really convincing and will certainly work. Still, the posts are very short for novices. Could you please extend them a little from next time? Thanks for the post.

发表回复