我想定义的是以下想法:
考虑是否有这些张量
a = tf.constant([1., 1.5, 1.2]) # tensor with shape [3,]
b = tf.constant([1., 2., 3.]) # ""
c = tf.constant([3., 0., 6.]) # ""
t = tf.constant([0.5, 0.6, 0.7, 2., 4., 5., 6.]) # tensor with shape [7,]
现在让我们考虑我想计算一个新的张量,使用以前张量的每个元素,例如:
def new_tensor(a, b, c, t):
X = tf.constant([[tf.sin(a*t[1]), b*t[3], c+t[4]],
[tf.cos(b*t[5]), tf.atan2(t[5], c), a+t[2]+b],
[a+t[4], a+b, c*t[0]]])
return X
X
应该是形状[3, 3, 3]
的张量。也就是说,我想定义一个函数,它将四个张量作为输入:其中三个具有相同的形状,第四个具有不同的形状。我希望函数为前三个输入(a, b, c
(的每个值计算一个张量(X
(。
使用此代码,TensorFlow 会给出此错误:
TypeError: List of Tensors when single Tensor expected
根据这篇文章,这是因为tf.constant
不能将张量作为输入,他们建议改用tf.Variable
。但我认为这不适合我,因为我以后必须使用X
并且不想初始化它等。我也读过另一篇文章,但找不到我的问题的任何答案。
有什么方法可以做我想做的事吗?我的代码对我的目的有意义吗?提前谢谢你。
更新:带有jdehesa答案
取@jdehesa答案并使生成的张量更简单:
def new_tensor(a, b, c, t):
# Could also use tf.convert_to_tensor
X = tf.stack([[a+t[1], b*t[1], c+t[1]],
[b*t[0], t[5]+ c, a+t[2]+b],
[a+t[4], a+b, c*t[0]]])
return X
对于张量:
a = tf.constant([1., 1., 1.]) # tensor with shape [3,]
b = tf.constant([2., 2., 2.]) # ""
c = tf.constant([3., 3., 3.]) # ""
t = tf.constant([1., 1., 1., 1., 1., 1., 1.]) # tensor with shape [7,]
我得到的是以下张量:
# When evaluating x = new_tensor(a,b,c,t)
[[[2. 2. 2.]
[2. 2. 2.]
[4. 4. 4.]]
[[2. 2. 2.]
[4. 4. 4.]
[4. 4. 4.]]
[[2. 2. 2.]
[3. 3. 3.]
[3. 3. 3.]]]
但我所期望的是以下内容:
[[[2. 2. 4.]
[2. 4. 4.]
[2. 3. 3.]]
[[2. 2. 4.]
[2. 4. 4.]
[2. 3. 3.]]
[[2. 2. 4.]
[2. 4. 4.]
[2. 3. 3.]]]
正如我希望它评估输入张量的每个元素一样。
没错,你只能将 Python 或 NumPy 值传递给tf.constant
,但你可以用tf.stack
构建你的张量,或者,如果你愿意,通常用tf.convert_to_tensor
:
import tensorflow as tf
def new_tensor(a, b, c, t):
# Could also use tf.convert_to_tensor
X = tf.stack([[tf.sin(a*t[1]), b*t[3], c+t[4]],
[tf.cos(b*t[5]), tf.atan2(t[5], c), a+t[2]+b],
[ a+t[4], a+b, c*t[0]]])
return X
with tf.Graph().as_default(), tf.Session() as sess:
a = tf.constant([1., 1.5, 1.2]) # tensor with shape [3,]
b = tf.constant([1., 2., 3.]) # ""
c = tf.constant([3., 0., 6.]) # ""
t = tf.constant([0.5, 0.6, 0.7, 2., 4., 5., 6.]) # tensor with shape [7,]
x = new_tensor(a, b, c, t)
print(sess.run(x))
# [[[ 0.5646425 0.7833269 0.65938467]
# [ 2. 4. 6. ]
# [ 7. 4. 10. ]]
#
# [[ 0.2836622 -0.8390715 -0.7596879 ]
# [ 1.0303768 1.5707964 0.69473827]
# [ 2.7 4.2 4.9 ]]
#
# [[ 5. 5.5 5.2 ]
# [ 2. 3.5 4.2 ]
# [ 1.5 0. 3. ]]]
编辑:对于第二个示例,要获得所需的结果,您需要使用tf.transpose
来更改张量维度的顺序:
import tensorflow as tf
def new_tensor(a, b, c, t):
# Could also use tf.convert_to_tensor
X = tf.stack([[a+t[1], b*t[1], c+t[1]],
[b*t[0], t[5]+ c, a+t[2]+b],
[a+t[4], a+b, c*t[0]]])
X = tf.transpose(X, (2, 0, 1))
return X
with tf.Graph().as_default(), tf.Session() as sess:
a = tf.constant([1., 1., 1.]) # tensor with shape [3,]
b = tf.constant([2., 2., 2.]) # ""
c = tf.constant([3., 3., 3.]) # ""
t = tf.constant([1., 1., 1., 1., 1., 1., 1.]) # tensor with shape [7,]
x = new_tensor(a, b, c, t)
print(sess.run(x))
# [[[2. 2. 4.]
# [2. 4. 4.]
# [2. 3. 3.]]
#
# [[2. 2. 4.]
# [2. 4. 4.]
# [2. 3. 3.]]
#
# [[2. 2. 4.]
# [2. 4. 4.]
# [2. 3. 3.]]]