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

Keras报错:'Sequential'对象不存在'fit'属性问题求助

Keras Sequential模型fit方法报错:AttributeError: 'Sequential' object has no attribute 'fit'

问题详情

我在开发AI课程项目时,突然遇到keras.models.Sequential.fit方法无法使用的问题。此前运行正常的代码现在执行失败,抛出相同错误;甚至从谷歌获取的随机Keras示例代码运行后也出现同样问题。

示例代码

import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
 
x = data = np.linspace(1,2,200)
y = x*4 + np.random.randn(*x.shape) * 0.3

model = Sequential()
model.add(Dense(1, input_dim=1, activation='linear'))

model.compile(optimizer='sgd', loss='mse', metrics=['mse'])

weights = model.layers[0].get_weights()
w_init = weights[0][0][0]
b_init = weights[1][0]
# print('Linear regression model is initialized with weights w: %.2f, b: %.2f' % (w_init, b_init)) 

model.fit(x,y, batch_size=1, epochs=30, shuffle=False)

weights = model.layers[0].get_weights()
w_final = weights[0][0][0]
b_final = weights[1][0]
# print('Linear regression model is trained to have weight w: %.2f, b: %.2f' % (w_final, b_final))

predict = model.predict(data)

错误输出

Traceback (most recent call last):
  File "MY_CWD/main.py", line 21, in <module>
    model.fit(x,y, batch_size=1, epochs=30, shuffle=False)
AttributeError: 'Sequential' object has no attribute 'fit'

环境信息

  • Python版本:3.10.6
  • Keras版本:2.12.0
  • TensorFlow版本:2.12.0
  • 操作系统:Ubuntu 22.04.2

解决方法

方法1:改用TensorFlow自带的Keras实现

将代码中的导入语句替换为tensorflow.keras相关模块,这是TensorFlow 2.x版本官方推荐的使用方式,能避免兼容性问题:

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
import numpy as np

方法2:卸载单独安装的Keras包

如果同时安装了单独的keras包和TensorFlow,可能会导致冲突。卸载单独的Keras,直接使用TensorFlow内置的Keras:

pip uninstall -y keras

方法3:重新安装匹配版本的依赖

如果以上方法无效,尝试重新安装对应版本的TensorFlow(会自动附带兼容的Keras):

pip uninstall -y tensorflow keras
pip install tensorflow==2.12.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 13:44:52