python - 错误: "List of Tensors when single Tensor expected" in computing a polynomial

标签 python tensorflow

我想使用 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/

相关文章:

python - 计算列中的唯一值 - pandas Python

python - 如何从 check-yaml git hook 中排除 !Ref 标签?

Python - 一种学习和检测文本模式的方法?

tensorflow - 从 tf.Tensor 中包含的路径加载文件

python - 没有名为 'uff' 的模块

GPU 上的 Tensorflow 比 CPU 上的慢

python - BeautifulSoup 不会从网页中提取所有表单

python - 如何从现有数据集中生成一组新值?

python - 对比损失函数适用于孪生网络和优化器有问题

swift - Swift Tensorflow 中的#tfop 是什么,它在哪里定义?