只把一个张量加到另一个十的一部分

2024-04-16 07:40:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我要加两个张量,一个在深度方向上是另一个的倍数。这里有一个例子

t1 = tf.constant(3, shape=[2, 2, 2], dtype=tf.float32)
t2 = tf.constant(1, shape=[2, 2, 1], dtype=tf.float32)

我想用tf.add这样的方法把第二个张量加到第一个张量上,但只加到形状第三个分量的第一层。有数字的

t1 = [[[3, 3], [3, 3]],
      [[3, 3], [3, 3]]]
t2 = [[[1, 1], [1, 1]]]

output = [[[4, 4], [4, 4]],
          [[3, 3], [3, 3]]]

有没有一个内置的函数可以做到这一点?你知道吗


Tags: 方法addtf数字方向例子分量形状
1条回答
网友
1楼 · 发布于 2024-04-16 07:40:15

t1的第一列t2相加,然后将其与t1的其余列合并:

t1 = tf.constant(3, shape=[2, 2, 2], dtype=tf.float32)
t2 = tf.constant(1, shape=[2, 2, 1], dtype=tf.float32)
tf.InteractiveSession()

tf.concat((t1[...,0:1] + t2, t1[...,1:]), axis=2).eval()

#array([[[4., 3.],
#        [4., 3.]],

#       [[4., 3.],
#        [4., 3.]]], dtype=float32)

请注意,第二个示例t2具有不同的形状,即(1,2,2)而不是(2,2,1),在这种情况下,按第一个轴进行切片和合并:

tf.concat((t1[0:1] + t2, t1[1:]), axis=0).eval()

#array([[[4., 4.],
#        [4., 4.]],

#       [[3., 3.],
#        [3., 3.]]], dtype=float32)

相关问题 更多 >