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

求助:解决AttributeError: 'function' object has no attribute 'compile'问题

AttributeError: 'function' object has no attribute 'compile' in Keras

嘿,这个问题我之前踩过一模一样的坑,一眼就能看出问题所在——你把模型构建函数和模型实例用了同一个名字model,导致调用compile的时候操作的是函数本身,而不是真正的Keras模型对象。

问题根源

你定义的def model(input_shape):是一个Python函数,当你直接写model.compile()时,Python会认为你要调用这个函数的compile方法,但函数本身根本没有这个属性,自然就抛出了AttributeError。

修复方案

有两种简单的解决办法,选哪个都可以:

方案1:重命名模型构建函数

把函数名改成和实例名不冲突的,比如build_model,这样就不会混淆了:

def build_model(input_shape):
    model = keras.Sequential()
    model.add(keras.layers.LSTM(64, input_shape=(1,9), return_sequences=True))
    model.add(keras.layers.LSTM(64))
    model.add(keras.layers.Dense(64, activation='relu'))
    model.add(keras.layers.Dropout(0.3))
    model.add(keras.layers.Dense(10, activation='softmax'))
    return model

# 生成模型实例并编译
my_model = build_model((1, 9))
my_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
my_model.summary()

方案2:先调用函数生成模型实例

如果不想改函数名,那就先调用函数得到真正的Keras模型对象,再对实例进行操作:

def model(input_shape):
    model = keras.Sequential()
    model.add(keras.layers.LSTM(64, input_shape=(1,9), return_sequences=True))
    model.add(keras.layers.LSTM(64))
    model.add(keras.layers.Dense(64, activation='relu'))
    model.add(keras.layers.Dropout(0.3))
    model.add(keras.layers.Dense(10, activation='softmax'))
    return model

# 先调用函数拿到模型实例
trained_model = model((1, 9))
trained_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
trained_model.summary()

额外小提示

顺便提一句,你的输出层用了10个神经元+softmax(适合多分类),但损失函数用的是binary_crossentropy(适合二分类),这可能不匹配哦:

  • 如果是二分类任务:输出层改成1个神经元+sigmoid激活,损失保持binary_crossentropy
  • 如果是10分类任务:损失换成categorical_crossentropy(标签是one-hot编码)或者sparse_categorical_crossentropy(标签是整数编码)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:07:42