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

TensorFlow模型在Jupyter Notebook报ValueError,Coursera环境可正常运行

解决TensorFlow本地运行ValueError的问题

问题原因

你的输入数据X是一维张量(形状为(8,)),而Keras的Dense层默认期望输入是二维张量(格式为(样本数量, 特征数量))。Coursera环境可能使用的是旧版本TensorFlow,会自动兼容一维输入;但本地较新版本的TensorFlow会严格校验输入维度,因此抛出ValueError。

解决步骤

1. 调整输入数据维度

给X增加一个特征维度,将形状从(8,)转为(8, 1),有两种简单实现方式:

方式一:用tf.expand_dims扩展维度

import tensorflow as tf
import numpy as np 
X = tf.constant(np.array([-7.0, -4.0, -1.0, 2.0, 5.0, 8.0, 11.0, 14.0]))
# 在axis=1位置增加维度,将一维转为二维
X = tf.expand_dims(X, axis=1)

y = tf.constant(np.array([3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0]))

model = tf.keras.Sequential([ tf.keras.layers.Dense(1) ])

model.compile(loss = tf.keras.losses.mae, optimizer = tf.keras.optimizers.SGD(), metrics = ['mae'])

model.fit(X, y, epochs=5)

方式二:创建数组时直接定义二维结构

import tensorflow as tf
import numpy as np 
# 直接以二维数组形式定义X,每个元素单独作为一个子列表
X = tf.constant(np.array([[-7.0], [-4.0], [-1.0], [2.0], [5.0], [8.0], [11.0], [14.0]]))

y = tf.constant(np.array([3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0]))

model = tf.keras.Sequential([ tf.keras.layers.Dense(1) ])

model.compile(loss = tf.keras.losses.mae, optimizer = tf.keras.optimizers.SGD(), metrics = ['mae'])

model.fit(X, y, epochs=5)

2. 版本对齐(可选)

如果想完全匹配Coursera环境的运行逻辑,可以查看并安装对应版本的TensorFlow:

  • 查看当前本地版本:
print(tf.__version__)
  • 安装指定版本(示例为2.8.0,需根据Coursera实际版本调整):
pip install tensorflow==2.8.0

不过更推荐用方法1调整维度,因为新版本的维度校验是更规范的机器学习数据输入要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 14:46:00