基本Tensorflow:使用现有变量定义Tensor变量

时间:2018-01-19 21:06:03

标签: tensorflow

我有一些非常简单的张量流代码来旋转矢量:


import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, shape=(2, 1))
angle = tf.placeholder(tf.float32)

s_a = tf.sin(angle)
c_a = tf.cos(angle)
R = tf.Variable([[c_a, s_a], [-s_a, c_a]], tf.float32, expected_shape=(2,2))
#R = tf.Variable([[1.0, 0.0], [0.0, 1.0]], tf.float32)
rotated_v = tf.matmul(R,x)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)

    res =  sess.run([init,rotated_v], feed_dict={x:np.array([[1.0],[1.0]]), angle:1.0})
    print(res)

当我手动编码单位矩阵时,代码工作正常。但是,在目前的形式中,我收到了这个错误:

ValueError: initial_value must have a shape specified: Tensor("Variable/initial_value:0", dtype=float32)

我尝试过多种方式指定形状,但我无法完成这项工作。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

我找到了实现这个目标的方法(可能不是最好的方法,但它确实有效)。


import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, shape=(2, 1))
angle = tf.placeholder(tf.float32)

s_a = tf.sin(angle)
c_a = tf.cos(angle)
R = tf.Variable([[1.0, 0.0], [0.0, 1.0]], tf.float32)
assignR = tf.assign(R, [[c_a, s_a], [-s_a, c_a]])

rotated_v = tf.matmul(R,x)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    newR = sess.run(assignR, feed_dict={angle:1.0})
    print(newR)
    print()

    res =  sess.run([rotated_v], feed_dict={x:np.array([[1.0],[1.0]])})
    print(res)

答案 1 :(得分:0)

此方法不起作用,因为s_ac_a操作输出,这些值由angle唯一确定。您无法分配或更新这些节点,因此训练它们没有任何意义。

这条线,另一方面......

R = tf.Variable([[1.0, 0.0], [0.0, 1.0]], tf.float32)

...是初始值等于单位矩阵的自变量的定义。这完全有效。由于此变量是独立的,因此您可以为其指定一个新值,该值由s_ac_a组成。请注意,您无法使用s_ac_a对其进行初始化,因为初始化程序在将值输入会话之前运行(因此angle未知)。