通过重复其列来扩展Tensorflow中2D张量的宽度

时间:2017-01-18 10:54:53

标签: arrays tensorflow slice

我有一个2d张量,必须在宽度(列号)方向上扩展。在下面的示例中,我想通过重复其列来使B与A一样宽。

这可以通过以下方式在numpy中完成:

A = np.array([[1,2,3],[4,5,6],[6,7,8]])
B = np.array([[19,15],[18,14],[17,13]])

ncl = A.shape[1]

B = B[:,np.mod(np.arange(ncl),B.shape[1])]
print(B)

收率:

[[19 15 19]
 [18 14 18]
 [17 13 17]]

如何在Tensorflow中为两个常数张量A和B执行此操作?

1 个答案:

答案 0 :(得分:0)

A = tf.constant([[1,2,3,4,4,5,6,7],[4,5,6,6,4,5,6,7],[6,7,8,9,4,5,6,7]])
B = tf.constant([[19,15],
             [18,14],
             [17,13]])

diff = A.get_shape()[1] - B.get_shape()[1]

Bt = tf.transpose(B)
for idx in range(diff):
    col = tf.gather_nd(Bt, [[idx]])
    Bt = tf.concat(0, [Bt, col])

result = tf.transpose(Bt)

with tf.Session() as sess:
    res = sess.run(result)
    print(res)

不是最美丽的代码,但它有效。

输出:

[[19 15 19 15 19 15 19 15]
 [18 14 18 14 18 14 18 14]
 [17 13 17 13 17 13 17 13]]