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

TensorFlow 2.10.0代码报错求助:温度转换神经网络无法运行

解决摄氏度转华氏度神经网络代码运行报错问题

问题原因

代码报错核心是Dense层参数使用错误:添加Dense层时,误将参数名input_shape写成了input,而TensorFlow的Dense层并不存在名为input的参数,这直接导致模型初始化失败。

修正后的完整代码

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras.layers import Dense

# 摄氏度与对应华氏度数据集
c = np.array([-40, -10, 0, 8, 15, 22, 38])
f = np.array([-40, 14, 32, 46, 59, 72, 100])

# 构建神经网络模型
model = keras.Sequential()                      
model.add(Dense(units=1, input_shape=(1,), activation='linear'))  # 修正参数名为input_shape

# 编译模型
model.compile(loss='mean_squared_error', optimizer=keras.optimizers.Adam(0.1))

# 训练模型
history = model.fit(c, f, epochs=500)

# 绘制训练损失曲线
plt.plot(history.history['loss'])
plt.grid(True)
plt.show()

额外优化说明

  • 将导入路径从from tensorflow.python.keras.layers import Dense改为from tensorflow.keras.layers import Dense,tensorflow.python属于TensorFlow内部私有模块,使用公开的tensorflow.keras接口更稳定可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:39:55