【发布时间】: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