【问题标题】:How to count letters from print result?如何计算打印结果中的字母?
【发布时间】:2018-10-25 23:11:54
【问题描述】:

我正在尝试计算代码以从单热 MNIST 字母数据中找到准确度得分。我想计算 MNIST 数据中每个标签的准确率,因为我对准确率、召回率和 f1 分数使用相同的值。 y_true 是数据框 [88800, 26]。首先,我定义了真阳性、真阴性和其他。我的代码是:

for i in y_true:
x=y_true[i]
y=y_pred[i]
    for j in range(len(x)):
       if (x.values[j] == 1) and (y.values[j] == 1):
           print("True Positive", y_pred.columns[i-1])
       elif (x.values[j] == 0) and (y.values[j] == 0):
           print("True Negative", y_pred.columns[i-1])
       elif (x.values[j] == 0) and (y.values[j] == 1):
           print("False Positive", y_pred.columns[i-1])
       else:
           print("False Negative", y_pred.columns[i-1])

输出是:

True Positive 1
True Positive 1
True Negative 1
...
True Negative 26

直到每个标签为 1 和 26 的行。但是,我意识到,我无法从打印结果中计算每个标签有多少真阳性、真阴性、假阳性和假阴性。我不知道如何计算它。是否可以从打印结果中计算?

【问题讨论】:

  • 创建计数变量并在内部增加 if stmt
  • 在循环之前,创建四个变量名为true_positivetrue_negative等,并将它们全部初始化为零。在每个 print 语句之后,增加相应的变量。
  • 你为什么不只是例如将标签添加到要打印的 if 语句内的列表中(例如,print("True Positive") 下方的 output_list.append("TP"))。然后您就可以轻松统计实例了。
  • 我仍然无法获得每个标签和变量的计数。这不是计数实例。

标签: python count


【解决方案1】:

你可以在你的代码中使用Counter

from collections import Counter

   c = Counter()


   for j in range(len(x)):
       if (x.values[j] == 1) and (y.values[j] == 1):
           print("True Positive", y_pred.columns[i-1])
           c.update([f'"True Positive" {y_pred.columns[i-1]}'])
       elif (x.values[j] == 0) and (y.values[j] == 0):
           print("True Negative", y_pred.columns[i-1])
           c.update([f'"True Negative" {y_pred.columns[i-1]}'])
       elif (x.values[j] == 0) and (y.values[j] == 1):
           print("False Positive", y_pred.columns[i-1])
           c.update([f'"False Positive" {y_pred.columns[i-1]}'])
       else:
           print("False Negative", y_pred.columns[i-1])
           c.update([f'"False Negative" {y_pred.columns[i-1]}'])

在此之后,c 将是您想要的输出。

要打印输出,请使用:

for k,v in dict(c).items():
    print(k,':',v)

【讨论】:

  • c.update([f'"True Positive" {y_pred.columns[i-1]}']) 是否必须对所有 True Positive?
  • 不,它返回True Negative 1。与索引。然后计数器将自动计算所有相同的输出。@muthikin
  • 但是您应该使用python>=3.6 进行这种格式设置。如果您使用其他版本,请告诉我,我会更新我的答案。
  • 我想要的输出是:True Positive 1: ? True Negative 1: ? False Positive 1: ? False Negative 1: ? True Positive 2: ? True Negative 2: ? 但是,当我在循环外运行 print (c) 时,它只显示最后一个索引。当我在循环内打印 (c) 时,它显示的行数与 @mehrdad 的行数一样多
  • @muthikin 我更新了我的答案,以便您可以打印所需的输出。
猜你喜欢
  • 2014-06-03
  • 2019-01-02
  • 2015-05-05
  • 1970-01-01
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
相关资源
最近更新 更多