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

使用TensorFlow Keras构建CNN时遇NameError:input_shape未定义

问题解决:TensorFlow Keras构建模型时input_shape未定义及其他错误

核心错误原因

你遇到的NameError是因为语法错误:把input_shape当成函数调用了,正确写法是将它作为关键字参数,值用元组形式传递,即input_shape=(784,),而非input_shape(784,)。

除此之外,代码还有两个潜在问题需要修复:

  • 导入方式冲突:同时混用from tensorflow import keras和from keras.models import Sequential会导致模块导入混乱,建议统一使用TensorFlow内置的Keras API。
  • metrics参数类型错误:model.compile的metrics参数要求传入列表,你写的{'accuracy'}是集合类型,会导致后续运行报错,需改为['accuracy']。

修复后的完整代码

# 创建简单的全连接模型(注:你注释标注的是CNN,但当前代码为全连接网络)
from tensorflow import keras

# 统一使用TensorFlow内置的Keras组件
model = keras.Sequential([
    keras.layers.Dense(10, input_shape=(784,), activation='sigmoid')
])

model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']  # 修正为列表类型
)

# 假设X_train_flattened和y_train已提前正确定义
model.fit(X_train_flattened, y_train, epochs=5)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:10:38