我想使用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
我不明白为什么它说有张量列表。请指教。谢谢。
答案 0 :(得分:1)
您应该将tf.constant替换为tf.stack,因为您无法将张量列表作为tf.constant的参数传递
polynomial = tf.stack([1, x, tf.pow(x, 2), tf.pow(x, 3), tf.pow(x, 4)])
答案 1 :(得分:1)
这是因为您试图使用x创建一个常量,该常量是一个占位符,在运行时会接受值。因此,它会向您抛出该错误。
此处是代码的修改版本,在Google Colab上运行时可返回结果。
import tensorflow as tf
x = tf.placeholder(dtype=tf.float32, shape=())
cfc = tf.placeholder(dtype=tf.float32, shape=(5))
polynomial = tf.Variable([1.0, 0.0, 0.0, 0.0, 0.0])
polynomial_op = polynomial.assign([1.0, x, tf.pow(x, 2), tf.pow(x, 3), tf.pow(x, 4)])
f = tf.tensordot(cfc, polynomial, 1)
init_op = tf.variables_initializer([polynomial])
with tf.Session() as sess:
sess.run(init_op)
result = sess.run(polynomial_op, feed_dict={x: 2.0, cfc: [0.0, 1.0, -1.0, 1.0, -1.0]})
print(result)
sess.close()
结果:
[ 1. 2. 4. 8. 16.]
在这里,我将多项式定义为变量,并使用tf变量初始值设定项对其进行了初始化。请注意,由于正在执行此操作,因此我在开始时分配了一个默认值,然后通过定义一个赋值操作然后运行该值,将其重新分配给使用x计算的值。您可以选择以其他任何舒适的方式进行操作。
答案 2 :(得分:1)
import tensorflow as tf
x = tf.placeholder(dtype=tf.float32, shape=())
cfc = tf.placeholder(dtype=tf.float32, shape=5)
polynomial = [1, x, x**2, x**3, 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)