【问题标题】:confusion_matrix error 'list' object has no attribute 'argmax'混淆矩阵错误“列表”对象没有属性“argmax”
【发布时间】:2021-06-24 03:35:46
【问题描述】:

我正在为 DCNN 模型编写分类报告,但我遇到了一个错误。我的代码是

from sklearn.metrics import confusion_matrix

test = ImageDataGenerator()
test_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
test_data = test_generator.flow_from_directory(directory="/content/dataset/test",target_size=IMAGE_SHAPE , color_mode="rgb" , class_mode='categorical' , batch_size=1 , shuffle = False )
test_data.reset()

predicted_class_indices=np.argmax(pred,axis=1)
cm = confusion_matrix(test_labels, predictions.argmax(axis=1))

错误:

AttributeError: 'list' object has no attribute 'argmax'

【问题讨论】:

  • 虽然这里的诊断很容易,但以后请发布完整的错误跟踪。另请注意,错误之后出现的任何代码都与问题无关(从未执行),不应将其包含在此处,因为它只会造成不必要的混乱(已编辑)。
  • predpredictions 是从哪里来的?

标签: python tensorflow machine-learning keras classification


【解决方案1】:

您的predictions 显然是一个Python 列表,而列表没有argmax 属性;你需要使用 Numpy 函数argmax():

predictions = [[0.1, 0.9], [0.8, 0.2]] # dummy data
y_pred_binary = predictions.argmax(axis=1)
# AttributeError: 'list' object has no attribute 'argmax'

# Use Numpy:
import numpy as np
y_pred_binary = np.argmax(predictions, axis=1)
y_pred_binary
# array([1, 0])

【讨论】:

  • 谢谢。但是, y_pred_binary = np.argmax(predictions, axis=1) 我面临另一个错误,即 AxisError: axis 1 is out of bounds for array of dimension 1 @desertnaut
  • @TurjoyAhmed 仅当您的 predictionssingle 元组组成时才会发生这种情况,即 predictions=[p0, p1](实际上没有轴 1);但在这种情况下,混淆矩阵是没有意义的。请更新您的帖子以准确显示predictions 变量是什么。上一行中的preds 是什么?那里的命令应该返回您实际查找的内容(假设 preds 确实是您的预测),并且不是您似乎认为的索引。
  • @TurjoyAhmed 如果它解决了您的问题,请接受答案。
猜你喜欢
  • 2021-12-04
  • 2019-10-15
  • 2015-09-18
  • 1970-01-01
  • 2020-03-09
  • 2018-10-02
  • 2021-05-25
  • 2022-01-20
  • 1970-01-01
相关资源
最近更新 更多