首页 > 解决方案 > 使用 TensorFlow 在我的 keras 代码中提前停止不起作用

问题描述

当我使用提前停止模型训练仅一个时期时,这不是应该做的。

这是没有提前停止的示例:

# split a univariate sequence into samples

def split_sequence(sequence, n_steps):
    X, y = list(), list()
    for i in range(len(sequence)):
        # find the end of this pattern
        end_ix = i + n_steps
        # check if we are beyond the sequence
        if end_ix > len(sequence)-1:
            break
        # gather input and output parts of the pattern
        seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]
        X.append(seq_x)
        y.append(seq_y)
    return np.array(X), np.array(y)

sequence = np.arange(10, 1000, 10)

n_steps = 3

X, y = split_sequence(sequence, n_steps)

n_features = 1
X = X.reshape((X.shape[0], X.shape[1], n_features))

model = Sequential()
model.add(LSTM(50, activation='relu', input_shape=(n_steps, n_features)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mean_absolute_percentage_error')


# early_stopping = EarlyStopping(monitor='val_loss', patience= 5)

hist = model.fit(X, y, validation_split=0.2,  batch_size = 16, epochs = 200)

从以下屏幕截图中可以看出,前 15 个以上的 epoch 的误差不断下降:

在此处输入图像描述

在此处输入图像描述

现在,如果我尝试提前停止它会在第一个时期停止:

hist = model.fit(X, y, validation_split=0.2,  callbacks = [EarlyStopping(patience=5)], batch_size = 16)

在此处输入图像描述

我做错了什么,我该如何纠正?

标签: pythonpython-3.xtensorflowkeras-2

解决方案


您忘记在此调用中指定 epoch 数,因此默认为 1:

hist = model.fit(X, y, validation_split=0.2,  callbacks = [EarlyStopping(patience=5)], batch_size = 16)

将其更改为:

hist = model.fit(X, y, validation_split=0.2,  callbacks=[EarlyStopping(patience=5)], batch_size=16, epochs=200)

干杯


推荐阅读