【发布时间】:2020-01-13 10:24:38
【问题描述】:
我要定义的是以下想法:
考虑这些张量在哪里
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
根据post,这是因为tf.constant 不能将张量作为输入,他们建议改用tf.Variable。但我认为这不适合我,因为我以后必须使用X 并且不想初始化它等等。我也读过这个other post,但找不到我的问题的任何答案.
有什么方法可以做我想做的事吗?我的代码对我的目的有意义吗?提前谢谢你。
更新:用 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 tensorflow