You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scikit-learn时间序列交叉验证中各折训练的epoch数疑问及配置咨询

关于Scikit-learn交叉验证中Keras MLP的epoch配置问题

嘿,我来帮你把这个问题掰明白~

首先你看到的114/114、225/225这类输出,不是epoch数,而是每折训练时的batch批次总数。因为时间序列拆分(TimeSeriesSplit)是按顺序递增划分训练集的,随着折数增加,训练集的样本量越来越大,对应的batch数自然也会变多,所以数字会不一样。

那你关心的epoch数问题:默认情况下,Keras的Scikit-learn包装器(KerasRegressor或者KerasClassifier)的epochs参数默认值是1,所以每折确实只训练1个epoch。不过这个参数完全是可以自定义配置的!

怎么配置epoch数?

在初始化Keras包装器的时候,直接把epochs参数传进去就行,比如:

from keras.wrappers.scikit_learn import KerasRegressor
from keras.models import Sequential
from keras.layers import Dense

def build_mlp_model():
    # 这里是你的MLP模型构建代码
    model = Sequential()
    model.add(Dense(64, activation='relu', input_shape=(X_train.shape[1],)))
    model.add(Dense(32, activation='relu'))
    model.add(Dense(1))
    model.compile(optimizer='adam', loss='mse')
    return model

# 初始化包装器时指定epochs和batch_size
model = KerasRegressor(build_fn=build_mlp_model, epochs=50, batch_size=32)

这样设置后,每一轮交叉验证的折都会训练50个epoch,而不是默认的1个。

额外优化:早停机制

如果担心训练过多epoch导致过拟合,还可以加上Keras的EarlyStopping回调函数,让模型在验证集性能不再提升时自动停止训练:

from keras.callbacks import EarlyStopping

early_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
model = KerasRegressor(build_fn=build_mlp_model, epochs=100, batch_size=32, callbacks=[early_stop])

这里设置了最多训练100个epoch,但如果连续5个epoch验证损失都没下降,就会提前停止,并且恢复到性能最好的那组权重。

这样调整后,你就能完全控制每折训练的epoch数啦~

内容的提问来源于stack exchange,提问作者Gabriel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:22:38