我想使用 TensorFlow Python API 计算多项式,如下所示:
多项式:f(x) = a0 + a1*x + a2*x^2 + a3*x^3 + a4*x^4。
代码是:
import tensorflow as tf
x = tf.placeholder(dtype=tf.float32, shape=())
cfc = tf.placeholder(dtype=tf.float32, shape=5)
polynomial = tf.constant([1, x, tf.pow(x, 2), tf.pow(x, 3), tf.pow(x, 4)])
f = tf.tensordot(cfc, polynomial, 1)
with tf.Session() as sess:
result = sess.run(f, feed_dict={x: 1.0,
cfc: [0.0, 1.0, -1.0, 1.0, -1.0]})
print(result)
一段非常简单的代码,但我无法正确理解。
这是错误跟踪:
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/trytf/sandbox.py", line 7, in <module>
polynomial = tf.constant([1, x, tf.pow(x, 2), tf.pow(x, 3), tf.pow(x, 4)])
File "C:\Python36\lib\site-packages\tensorflow\python\framework\constant_op.py", line 208, in constant
value, dtype=dtype, shape=shape, verify_shape=verify_shape))
File "C:\Python36\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 442, in make_tensor_proto
_AssertCompatible(values, dtype)
File "C:\Python36\lib\site-packages\tensorflow\python\framework\tensor_util.py", line 350, in _AssertCompatible
raise TypeError("List of Tensors when single Tensor expected")
TypeError: List of Tensors when single Tensor expected
我不明白为什么它说有一个张量列表。请指教。谢谢。
最佳答案
您应该将 tf.constant 替换为 tf.stack,因为您无法将张量列表作为 tf.constant 的参数传递
多项式 = tf.stack([1, x, tf.pow(x, 2), tf.pow(x, 3), tf.pow(x, 4)])
关于python - 错误: "List of Tensors when single Tensor expected" in computing a polynomial,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54084247/