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

Keras Sequential模型调用compile()报错:缺少必填参数'self'

解决Keras中compile() missing 1 required positional argument: 'self'错误

错误原因

这个错误的核心问题是:你创建Sequential模型时没有调用类的构造函数(缺少一对括号()),导致model变量指向的是Sequential类本身,而不是类的实例对象。类的方法(比如compile)必须依赖实例作为第一个参数self,直接调用类的方法就会抛出这个参数缺失的错误。

修正方案

只需要在keras.Sequential后添加括号,正确实例化模型即可:

修正后的模型定义代码

model = keras.Sequential(
    [
        Dense(2, activation="relu", name="L1"),
        Dense(3, activation="relu", name="L2"),
        Dense(4, name="L3")
    ]
)

完整可运行代码示例

from tensorflow import keras
from tensorflow.keras.layers import Dense
from tensorflow.keras.metrics import MeanSquaredError

# 正确实例化Sequential模型
model = keras.Sequential(
    [
        Dense(2, activation="relu", name="L1"),
        Dense(3, activation="relu", name="L2"),
        Dense(4, name="L3")
    ]
)

# 正常编译模型
model.compile(optimizer="sgd", loss="mse", metrics=[MeanSquaredError()])

补充说明

  • 如果你是单独导入Sequential类(比如from tensorflow.keras.models import Sequential),同样要确保用Sequential()来创建实例,而不是直接赋值Sequential类本身。
  • 类与实例的区别是Python基础概念:类是模板,实例是根据模板创建的具体对象,只有实例才能调用类的实例方法(比如compile、fit等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:27:39