【问题标题】:How to concatenate two tensors with intervals in tensorflow?如何在张量流中连接两个具有间隔的张量?
【发布时间】:2020-09-26 06:13:36
【问题描述】:

我想在 tensorflow2 中以棋盘方式连接两个张量,如下所示:

示例 1:

a = [[1,1],[1,1]]
b = [[0,0],[0,0]]

concated_a_and_b = [[1,0,1,0],[0,1,0,1]]

示例 2:

a = [[1,1,1],[1,1,1],[1,1,1]]
b = [[0,0,0],[0,0,0],[0,0,0]]

concated_a_and_b = [[1,0,1,0,1,0],[0,1,0,1,0,1],[1,0,1,0,1,0]]

在 tensorflow2 中有没有像这样连接它们的好方法?

一些背景知识: 我首先将带有棋盘掩码的张量 c 分成两半 a 和 b。经过一些转换后,我必须将它们连接回原始形状和顺序。

我所说的棋盘式是什么意思:

【问题讨论】:

    标签: tensorflow tensorflow2.0 tensorflow2.x


    【解决方案1】:

    第 1 步:生成具有交替值的矩阵

    您可以通过首先连接成 [1, 0] 对,然后应用最终整形来做到这一点。

    第 2 步:反转一些行

    我将矩阵分成两部分,反转第二部分,然后通过交替选择第一部分和第二部分来重建完整矩阵

    代码示例

    import math
    import numpy as np
    import tensorflow as tf
    
    a = tf.ones(shape=(3, 4))
    b = tf.zeros(shape=(3, 4))
    
    x = tf.expand_dims(a, axis=-1)
    y = tf.expand_dims(b, axis=-1)
    
    paired_ones_zeros = tf.concat([x, y], axis=-1)
    
    alternated_values = tf.reshape(paired_ones_zeros, [-1, a.shape[1] + b.shape[1]])
    
    num_samples = alternated_values.shape[0]
    middle = math.ceil(num_samples / 2)
    is_num_samples_odd = middle * 2 != num_samples
    
    # Gather first part of the matrix, don't do anything to it
    first_elements = tf.gather_nd(alternated_values, [[index] for index in range(middle)])
    # Gather second part of the matrix and reverse its elements
    second_elements = tf.reverse(tf.gather_nd(alternated_values, [[index] for index in range(middle, num_samples)]), axis=[1])
    
    # Pick alternatively between first and second part of the matrix
    indices = np.concatenate([[[index], [index + middle]] for index in range(middle)], axis=0)
    if is_num_samples_odd:
        indices = indices[:-1]
    
    output = tf.gather_nd(
        tf.concat([first_elements, second_elements], axis=0),
        indices
    )
    print(output)
    

    【讨论】:

    • 它有点接近,但仍然不是棋盘式。您帖子中的输出是 [[1. 0. 1. 0. 1. 0. 1. 0.],[1. 0. 1. 0. 1. 0. 1. 0.],[1. 0. 1. 0. 1. 0. 1. 0.]] 这与我的预期不同:[[1. 0. 1. 0. 1. 0. 1. 0.],[0. 1. 0. 1. 0. 1. 0. 1.],[1. 0. 1. 0. 1. 0. 1. 0.]](注意第 2 行不同)。
    【解决方案2】:

    我知道这不是一个体面的方式,因为它会影响时间和空间的复杂性。但它解决了上述问题

       def concat(tf1, tf2):
          result = []
          for (index, (tf_item1, tf_item2)) in enumerate(zip(tf1, tf2)):
            item = []
            for (subitem1, subitem2) in zip(tf_item1, tf_item2):
                if index % 2 == 0:
                    item.append(subitem1)
                    item.append(subitem2)
                else:
                    item.append(subitem2)
                    item.append(subitem1)
            concated_a_and_b.append(item)
          return concated_a_and_b
    

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 2021-11-20
      • 2020-06-27
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      相关资源
      最近更新 更多