如何解决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
相关产品推荐
相关产品推荐

