TensorFlow报错TypeError: __init__()意外参数'shape'求助
解决TensorFlow新手两数相加代码的TypeError问题
嘿,我一眼就看到问题啦——你把代码运行后的打印输出结果当成可执行代码写进去了!那三行tf.Tensor("Const:0", dtype='f',shape=[1])是print(a)/print(b)/print(total)的输出内容,不是要运行的代码,直接执行它们就会触发TypeError,因为tf.Tensor的构造函数根本不接受shape这个关键字参数。
修正后的正确代码
先把那三行多余的输出语句删掉,然后注意:你的代码是TensorFlow 1.x风格的,需要通过Session来执行计算图才能得到实际的数值结果,完整代码如下:
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf # 定义计算图中的常量和相加操作 a = tf.constant(3.0, dtype=tf.float32) b = tf.constant(4.0) total = a + b # 打印Tensor节点的元信息(这部分是正常的,会输出节点名称、数据类型等) print(a) print(b) print(total) # 创建会话并运行计算,获取实际数值 with tf.Session() as sess: a_val, b_val, total_val = sess.run([a, b, total]) print("\n实际计算结果:") print(a_val) print(b_val) print(total_val)
错误原因详解
你添加的那三行tf.Tensor(...)是完全错误的用法:
- 在TensorFlow中,
tf.Tensor对象是由诸如tf.constant、tf.add这类操作自动创建的,不需要你手动调用tf.Tensor构造函数生成。 - 手动调用
tf.Tensor("Const:0", dtype='f',shape=[1])时,构造函数不识别shape参数,所以抛出了TypeError: __init__() got an unexpected keyword argument 'shape'这个错误。
额外提示:TensorFlow 2.x的写法
如果你用的是TensorFlow 2.x,代码会更简单,因为默认启用了即时执行(Eager Execution),不需要会话就能直接得到结果:
import tensorflow as tf a = tf.constant(3.0, dtype=tf.float32) b = tf.constant(4.0) total = a + b # 直接打印就能输出数值,而不是Tensor节点信息 print(a) print(b) print(total)
内容的提问来源于stack exchange,提问作者user7091413
相关产品推荐
相关产品推荐

