【问题标题】:Tensorflow training accuracy and loss different from evaluation of the same datasetTensorFlow 训练精度和损失不同于对同一数据集的评估
【发布时间】:2020-04-25 20:30:15
【问题描述】:

我尝试训练一个包含两个类的 Tensorflow 模型。 我的 Trainingsdata 是平衡的(两个类都有大约 11k 图像)。 我正在使用 Tranferlearning 并尝试使用以下代码继续使用 InceptionV3 模型:

BUFFER_SIZE = 1000
BATCH_SIZE = 32

def get_label(file_path, class_names):
  # convert the path to a list of path components
  parts = tf.strings.split(file_path, os.path.sep)
  # The second to last is the class-directory
  return parts[-2] == class_names

def parse_image(filename):
    parts = tf.strings.split(filename, "\\")
    label = get_label(filename, CLASS_NAMES)

    image = tf.io.read_file(filename)
    image = tf.image.decode_png(image, channels=3)
    image = tf.image.convert_image_dtype(image, tf.float32)
    image = tf.image.resize(image, [299,299])/255.0
    return image, label

datasetFilePath = "Path\To\BalancedData"
IMAGESIZE = 299
AUTOTUNE = tf.data.experimental.AUTOTUNE
datasetPath = pathlib.Path(datasetFilePath)
list_ds = tf.data.Dataset.list_files(str(datasetPath/"*/*"))

CLASS_NAMES = np.array([item.name for item in datasetPath.glob('*')])

# labeled_ds = list_ds.map(process_path)

images_ds = list_ds.map(parse_image, num_parallel_calls=AUTOTUNE)
images_ds = images_ds.shuffle(BATCH_SIZE)

dataset = images_ds.batch(BATCH_SIZE, drop_remainder=True)

for image_batch, label_batch in dataset.take(1):
    pass

def build_and_compile_model():
    base_model =tf.keras.applications.InceptionV3(include_top=False, weights = "imagenet", input_shape=(IMAGESIZE,IMAGESIZE,3))
    feature_batch = base_model(image_batch)
    print(feature_batch.shape)

    base_model.trainable = False
    x = base_model.output
    x = tf.keras.layers.GlobalAveragePooling2D(name="avg_pool")(x)
    x = tf.keras.layers.Dense(256, activation="relu")(x)
    predictions = tf.keras.layers.Dense(2, activation="softmax")(x)
    model = tf.keras.models.Model(inputs=base_model.input, outputs=predictions)

    base_learning_rate = 0.00001
    model.compile(optimizer=tf.keras.optimizers.Adam(lr=base_learning_rate),
                 loss="categorical_crossentropy",
                 metrics=["accuracy"])
    return model


multi_worker_model = build_and_compile_model()
tensorboard = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)
history = multi_worker_model.fit(dataset, epochs=2, callbacks=[tensorboard])

=>Epoch 1/2
=>711/711 [==============================] - 176s 247ms/step - loss: 0.3309 - accuracy: 0.8945
=>Epoch 2/2
=>711/711 [==============================] - 166s 233ms/step - loss: 0.1410 - accuracy: 0.9632

predictions = multi_worker_model.evaluate(dataset)
=>711/711 [==============================] - 150s 212ms/step - loss: 0.7538 - accuracy: 0.4999

所以总而言之,我的模型只是预测所有内容都属于 1 类,我不明白为什么会这样,主要是为什么它声称训练准确率为 96%

这可能是数据的问题,但话又说回来,我希望训练准确度也达到 50%,因为训练和评估都发生在同一个数据集上。

任何帮助将不胜感激,如果您需要更多信息,请告诉我!

【问题讨论】:

    标签: python tensorflow machine-learning keras deep-learning


    【解决方案1】:

    好的,经过几个小时的研究,我可能会遇到问题。 InceptionV3 使用

    def preprocess_input(x):
        x /= 255.
        x -= 0.5
        x *= 2.
        return x
    

    作为预处理函数。我只做 x/=255 部分是不够的。准确度的差异可能是因为.fit 函数自动进行预处理,而另一方面.evaluate 不能这样做。

    我不能 100% 确定这是正确答案,但这是我的最佳猜测。它也适用于将base_model.trainable = False 设置为base_model.trainable = True。我认为这允许模型使用我自己的预处理进行训练,因此评估也有效,因为它得到了我的预处理。

    我希望这可以帮助有类似问题的人。但我仍然很高兴看到那些可能对这个话题有更好见解的人提供的任何意见。

    【讨论】:

      猜你喜欢
      • 2022-06-30
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多