【问题标题】:TF accuracy score and confusion matrix disagree. Is TensorFlow shuffling data on each access of BatchDataset?TF 准确度得分和混淆矩阵不一致。 TensorFlow 是否会在 BatchDataset 的每次访问时对数据进行洗牌?
【发布时间】:2021-06-14 17:58:40
【问题描述】:

model.evaluate() 报告的准确率与根据 Sklearn 或 TF 混淆矩阵计算的准确率大不相同。

from sklearn.metrics import confusion_matrix
...

training_data, validation_data, testing_data = load_img_datasets()
# These ^ are tensorflow.python.data.ops.dataset_ops.BatchDataset

strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
    model = create_model(INPUT_SHAPE, NUM_CATEGORIES)
    optimizer = tf.keras.optimizers.Adam()
    metrics = ['accuracy']
    model.compile(loss='categorical_crossentropy',
                  optimizer=optimizer,
                  metrics=metrics)

history = model.fit(training_data, epochs=epochs,
                    validation_data=validation_data)

testing_data.shuffle(len(testing_data), reshuffle_each_iteration=False)
# I think this ^ is preventing additional shuffles on access

loss, accuracy = model.evaluate(testing_data)
print(f"Accuracy: {(accuracy * 100):.2f}%")
# Prints 
# Accuracy: 78.7%

y_hat = model.predict(testing_data)
y_test = np.concatenate([y for x, y in testing_data], axis=0)
c_matrix = confusion_matrix(np.argmax(y_test, axis=-1),
                            np.argmax(y_hat, axis=-1))
print(c_matrix)
# Prints result that does not agree:
# Confusion matrix:
#[[ 72 111  54  15  69]
# [ 82 100  44  16  78]
# [ 64 114  52  21  69]
# [ 71 106  54  21  68]
# [ 79 101  51  25  64]]
# Accuracy calculated from CM = 19.3%

起初,我认为 TensorFlow 在每次访问时都在洗牌 testing_data,所以我添加了 testing_data.shuffle(len(testing_data), reshuffle_each_iteration=False),但结果仍然不一致。

也试过TF混淆矩阵:

y_hat = model.predict(testing_data)
y_test = np.concatenate([y for x, y in testing_data], axis=0)
true_class = tf.argmax(y_test, 1)
predicted_class = tf.argmax(y_hat, 1)
cm = tf.math.confusion_matrix(true_class, predicted_class, NUM_CATEGORIES)
print(cm)

...结果相似。

显然预测的标签必须与正确的标签进行比较。我做错了什么?

【问题讨论】:

    标签: tensorflow scikit-learn tensorflow2.0 tensorflow-datasets


    【解决方案1】:

    我找不到源代码,但似乎 Tensorflow 仍在对引擎盖下的测试进行改组。您可以尝试迭代数据集以获得预测和真实类:

    predicted_classes = np.array([])
    true_classes =  np.array([])
    
    for x, y in testing_data:
      predicted_classes = np.concatenate([predicted_classes,
                           np.argmax(model(x), axis = -1)])
      true_classes = np.concatenate([true_classes, np.argmax(y.numpy(), axis=-1)])
    

    model(x) 用于更快的执行。 From the source:

    计算是分批完成的。该方法专为 表现在 大规模投入。对于适合一批的少量输入, 建议直接使用__call__ 以加快执行速度,例如, model(x)

    如果不行,你可以试试model.predict(x)。

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 2013-12-02
      • 2020-02-25
      • 2012-11-12
      • 2018-09-26
      • 2019-01-11
      • 2016-08-25
      • 2021-10-30
      • 2018-06-06
      相关资源
      最近更新 更多