keras model.fit 精度与 model.evaluate 不同

问题描述 投票:0回答:1

出于某种目的,我想探索单个神经元的拟合极限。对于二元分类,我相信神经元可以完美地适应上升沿或下降沿。因此,我想通过代码来验证这种情况。但在实际测试过程中,我遇到了以下问题。

我不确定为什么模型的训练准确率是1.0,但是使用model.evaluate在训练集上测试时并没有反映出相同的准确率。

这是代码:

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import keras
import random
from keras import layers
from keras.callbacks import EarlyStopping
from keras.optimizers import Adam


def random_seed(seed_num=1):
    np.random.seed(seed_num)
    tf.random.set_seed(seed_num)
    random.seed(seed_num)


class CustomEarlyStopping(keras.callbacks.Callback):
    def __init__(self, threshold):
        super().__init__()
        self.threshold = threshold

    def on_epoch_end(self, epoch, logs=None):
        accuracy = logs["accuracy"]
        loss = logs['loss']
        if accuracy >= self.threshold:
            self.model.stop_training = True

# data init
x = np.arange(-20, 30, 0.1)
y = np.zeros_like(x)
df = pd.DataFrame({'x': x, 'y': y})
df.y = df.x.map(lambda x: 0 if x<10 else 1)
X_train = df.drop(columns='y')
y_train = df.y

# model
random_seed()
model = keras.Sequential([
    layers.Input(shape=X_train.shape[-1]),
    layers.Normalization(),
    layers.Dense(1, activation='relu'),
    layers.Dense(1, activation='sigmoid'),
])
model.compile(
    optimizer=Adam(learning_rate=0.1),
    loss='binary_crossentropy',
    metrics=['accuracy'],
)
history = model.fit(
    X_train, y_train, 
    batch_size=128,
    epochs=100,
    callbacks=[
        CustomEarlyStopping(1.0)
    ]
)
history_df = pd.DataFrame(history.history)

last_accuracy = history_df.accuracy.tolist()[-1]
predict_accuracy = model.evaluate(X_train, y_train)[-1]

print('last_accuracy', last_accuracy)           # 1.0
print('predict_accuracy', predict_accuracy)     # 0.9940000176429749

我尝试不使用提前停止,直接检查不同时期的结果,但很多时候,两者之间的值是不同的。我不明白这种情况。

python tensorflow keras model
1个回答
0
投票
if accuracy >= self.threshold:
    self.model.stop_training = True

这意味着您的训练可能会在最后一个时期之前结束,而

last_accuracy
是提前结束之前在最后一个时期获得的准确率。然而,当您在训练后调用 model.evaluate 时,它会在整个训练集上评估模型,而不会提前终止,并且 Predict_accuracy 表示整个训练集上的准确性。

© www.soinside.com 2019 - 2024. All rights reserved.