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

如何解决Google Colab中导入KerasRegressor的报错问题?

解决Colab中KerasRegressor导入及scikeras使用问题

问题根源

TensorFlow 2.10及以上版本已经移除了tensorflow.keras.wrappers模块,所以直接导入会触发ModuleNotFoundError,官方推荐用scikeras作为替代工具。

正确解决步骤

  • 安装scikeras
    在Colab的代码单元格中执行安装命令:

    !pip install scikeras[tensorflow]
    

    加上[tensorflow]后缀会自动匹配兼容的TensorFlow版本,避免版本冲突。

  • 替换导入语句
    把原来的导入代码替换成:

    from scikeras.wrappers import KerasRegressor
    
  • 示例使用代码
    这里给一个简单的示例,展示如何用scikeras的KerasRegressor包装Keras模型:

    import tensorflow as tf
    from scikeras.wrappers import KerasRegressor
    from sklearn.model_selection import cross_val_score
    from sklearn.datasets import make_regression
    
    # 生成回归数据集
    X, y = make_regression(n_samples=1000, n_features=10, random_state=42)
    
    # 定义Keras回归模型
    def build_model():
        model = tf.keras.Sequential([
            tf.keras.layers.Dense(64, activation='relu', input_shape=(10,)),
            tf.keras.layers.Dense(64, activation='relu'),
            tf.keras.layers.Dense(1)
        ])
        model.compile(optimizer='adam', loss='mse')
        return model
    
    # 用KerasRegressor包装模型
    regressor = KerasRegressor(model=build_model, epochs=10, batch_size=32, verbose=0)
    
    # 交叉验证测试
    scores = cross_val_score(regressor, X, y, cv=5)
    print(f"交叉验证得分: {scores.mean():.4f} ± {scores.std():.4f}")
    

常见问题排查

如果使用scikeras仍报错,检查以下几点:

  • 安装完包后重启Colab运行时,避免缓存问题
  • 更新TensorFlow到稳定版:执行!pip install --upgrade tensorflow
  • 更新scikit-learn到兼容版本(需0.22+):执行!pip install --upgrade scikit-learn

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:43:15