0

我想在 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。经过一些改造后,我必须将它们连接回原始形状和秩序。

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

4

2 回答 2

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)
于 2020-06-07T08:29:24.350 回答
0

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

   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
于 2020-06-07T09:41:54.727 回答