使用 Tensorflow 识别错误分类的图像

Identify misclassified images with Tensorflow

我一直在研究图像分类器,我想看看模型在验证中错误分类的图像。我的想法是比较真实值和预测值,并使用不匹配值的索引来获取图像。 但是,当我尝试比较准确性时,我得到的结果与使用评估方法时得到的结果不同。 这就是我所做的:

我使用这个函数导入数据:

def create_dataset(folder_path, name, split, seed, shuffle=True):
  return tf.keras.preprocessing.image_dataset_from_directory(
    folder_path, labels='inferred', label_mode='categorical', color_mode='rgb',
    batch_size=32, image_size=(320, 320), shuffle=shuffle, interpolation='bilinear',
    validation_split=split, subset=name, seed=seed)

train_set = create_dataset(dir_path, 'training', 0.1, 42)
valid_set = create_dataset(dir_path, 'validation', 0.1, 42)

# output:
# Found 16718 files belonging to 38 classes.
# Using 15047 files for training.
# Found 16718 files belonging to 38 classes.
# Using 1671 files for validation.

然后为了评估验证集的准确性,我使用了这一行:

model.evaluate(valid_set)

# output:
# 53/53 [==============================] - 22s 376ms/step - loss: 1.1322 - accuracy: 0.7349
# [1.1321837902069092, 0.7348892688751221]

这很好,因为这些值与我在最后一个训练阶段得到的值完全相同。

为了从验证集中提取真实标签,我使用了基于此 answer 的这行代码。请注意,我需要再次创建验证,因为每次我调用引用验证集的变量时,验证集都会被打乱。 我还以为是这个因素导致了精度不一致,但是显然并没有解决问题。

y_val_true = np.concatenate([y for x, y in create_dataset(dir_path, 'validation', 0.1, 42)], axis=0)
y_val_true = np.argmax(y_val_true, axis=1)

我预测:

y_val_pred = model.predict(create_dataset(dir_path, 'validation', 0.1, 42))
y_val_pred = np.argmax(y_val_pred, axis=1)

最后我再次计算准确率以验证一切正常:

m = tf.keras.metrics.Accuracy()
m.update_state(y_val_true, y_val_pred)
m.result().numpy()

# output:
# 0.082585275

如您所见,我在 运行 评估方法时得到的不是相同的值,而是现在我只得到 8%。

如果您能指出我的方法的缺陷,我将不胜感激。 自从我的第一个问题 post 以来,我为我犯的任何错误提前道歉。

如果您想逐批显示或分析,此方法可以帮助提供见解

m = tf.keras.metrics.Accuracy()

# Iterating over individual batches to keep track of the images
# being fed to the model.
for valid_images, valid_labels in valid_set.as_numpy_iterator():
    y_val_true = np.argmax(valid_labels, axis=1)

    # Model can take inputs other than dataset as well. Hence, after images
    # are collected you can give them as input.
    y_val_pred = model.predict(valid_images)
    y_val_pred = np.argmax(y_val_pred, axis=1)
   
    # Update the state of the accuracy metric after every batch
    m.update_state(y_val_true, y_val_pred)

m.result().numpy()

如果你想一起喂食

valid_ds = create_dataset(dir_path, 'validation', 0.1, 42, shuffle=False)
y_val_true = np.concatenate([y for x, y in valid_ds, axis=0)
y_val_true = np.argmax(y_val_true, axis=1)
y_val_pred = model.predict(valid_ds)
y_val_pred = np.argmax(y_val_pred, axis=1)

m = tf.keras.metrics.Accuracy()
m.update_state(y_val_true, y_val_pred)
m.result().numpy()

虽然我在你的代码中找不到错误。