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

如何解决Spyder中运行Keras代码时的'module' object is not callable错误

解决Keras中TypeError: 'module' object is not callable错误

问题场景

在Spyder环境中编写Keras的MLP模型代码时,运行到模型定义步骤出现错误。

代码片段

import numpy as np
import keras
from keras import models

### Generate random training and testing sets

x_train = np.random.random((1000,20))
y_train = np.random.randint(low = 2 , size = (x_train.shape[0] , 1))

x_test = np.random.random((100,20))
y_test = np.random.randint(low = 2 , size = (100 , 1))

### Defining layers of the MLP model

m = keras.models.sequential()

错误信息

m = keras.models.sequential()
Traceback (most recent call last):

  File "C:\Users\hossein\AppData\Local\Temp\ipykernel_464\416401841.py", line 1, in <module>
    m = keras.models.sequential()

TypeError: 'module' object is not callable

错误原因与解决办法

这个错误的核心是大小写使用错误:Keras中的Sequential模型类是大写开头的Sequential,你写的小写sequential是一个模块而非可调用的类,因此触发了"module object is not callable"错误。

你可以选择以下几种正确写法:

  • 写法1:直接调用keras.models下的Sequential类
m = keras.models.Sequential()
  • 写法2:利用已导入的models模块简化调用
    因为已经执行了from keras import models,可以直接写:
m = models.Sequential()
  • 写法3:单独导入Sequential类
    直接导入目标类让代码更简洁:
from keras.models import Sequential
m = Sequential()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:39:45