python - 仅将一个张量添加到另一个张量的一部分

标签 python tensorflow

我必须添加两个张量,一个在深度方向上的形状是另一个张量的倍数。这是一个例子

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),在这种情况下,按第一个轴进行切片和连接:

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

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

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

关于python - 仅将一个张量添加到另一个张量的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52838888/

相关文章:

python - 具有不同长度数组的 Pandas

python - Tensorflow域适应如何同时使用两个Bazel命令?

python - 将输入管道传递给 TensorFlow Estimator

image-processing - 使用 tensorflow 在图像中查找点模式

python - Tensorflow:调整图像占位符大小

Tensorflow - 如何实现超参数随机搜索?

python - 计算字符串中字符出现次数的最佳方法

python - 从基于 Django 类的 View 的 form_valid 方法调用特殊(非 HTTP)URL

python - keras 中的自定义 keras.applications 模型

python - 来自源 'https://storage.googleapis.com' 的字体已被跨源资源共享策略阻止加载