簡體   English   中英

僅將張量添加到另一個張量的一部分

[英]Add a tensor only to a part of another tensor

我必須添加兩個張量,一個張量在深度方向上是另一個張量的形狀。 這是一個例子

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]]]

有內置的功能可以做到這一點嗎?

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) ,在這種情況下,第一個軸為slice和concat:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM