【发布时间】:2021-08-11 10:55:58
【问题描述】:
参考本教程https://www.tensorflow.org/tutorials/images/transfer_learning,我创建并训练了一个 resnet 模型
preprocess_input = tf.keras.applications.resnet50.preprocess_input
IMG_SHAPE = IMG_SIZE + (3,)
base_model = tf.keras.applications.resnet50.ResNet50(
include_top=False, weights='imagenet',input_shape=IMG_SHAPE, classes=2)
prediction_layer = tf.keras.layers.Dense(1)
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
inputs = tf.keras.Input(shape=IMG_SHAPE)
x = data_augmentation(inputs)
x = preprocess_input(x)
x = base_model(x)
x = global_average_layer(x)
x = tf.keras.layers.Dropout(0.2)(x)
outputs = prediction_layer(x)
model = tf.keras.Model(inputs, outputs)
那么当我推断模型是否执行数据增强时?我希望模型在训练期间而不是在推理期间进行数据增强
当我将图像推断为批次并一次推断一个图像时,我也会得到不同的结果。当我推断一批图像时,我总是得到准确度 1(这是一个过度拟合的模型),当我逐个推断图像时,我得到 2-4 个错误(这个数字不是恒定的,每次我得到不同的准确度时)
这是我的推理代码
image_batch, label_batch = test_dataset.as_numpy_iterator().next()
class_list =['close','open']
model = tf.keras.models.load_model("shutter_model")
predictions = model.predict_on_batch(image_batch).flatten()
# Apply a sigmoid since our model returns logits
predictions = tf.nn.sigmoid(predictions)
predictions = tf.where(predictions < 0.5, 0, 1)
error = 0
for i in range(len(predictions)):
if predictions[i]!= label_batch[i]:
error+=1
print("number of errors when batch of images fed into the model: ",error)
print('=='*10)
error = 0
for i in range(len(image_batch)):
img = tf.expand_dims(image_batch[i], axis=0)
predictions = model(img)
predictions = tf.nn.sigmoid(predictions)
class_n = 1 if predictions[0][0] >0.5 else 0
if label_batch[i]!= class_n:
error+=1
print("number of errors when images fed into the model one by one: ",error)
输出
number of errors when batch of images fed into the model: 0
====================
number of errors when images fed into the model one by one: 3
我的目的是使用 Resnet5o 架构训练(从头开始或从预训练的权重)2 类模型
【问题讨论】:
-
在上述设置中,在训练时会应用增强,在推理时不会使用。
-
当我使用测试数据集(加载一批图像)评估模型时,我得到的准确度为 1,但是当我逐个推断图像时,我得到的准确度只有 0.97,这正常吗? @M.Innat
-
获得 1 似乎不正常。请添加更多信息,可能使用可重现的代码。我建议在 mnist/cifar 数据集上运行您的模型,并在其测试集上尝试评估和推理(如您所说)并更新您问题中的结果。
-
这是一个高度过拟合的模型,我只是在试验。我想问的是 global_average_layer 会影响推理吗,当输入分批而不是分批提供时,它是否会给出不同的输出值@M.Innat