Tensorflow:如何平铺以一定顺序复制的张量?

Nat*_*ion 5 python tensorflow

例如,我有一个张量A = tf.Variable([a, b, c, d, e]),通过 tf.tile(),它可以给张量[a, b, c, d, e, a, b, c, d, e]

但是我想A改成类似:的形式[a, a, b, b, c, c, d, d, e],其中元素在原始位置重复。

(通过不同的操作)实现此目标的最有效方法(更少的操作)是什么?

sdc*_*cbr 5

您可以通过添加尺寸,沿该尺寸平铺并删除它来实现:

import tensorflow as tf

A = tf.constant([1, 2, 3, 4, 5])

B = tf.expand_dims(A, axis=-1)
C = tf.tile(B, multiples=[1,2])
D = tf.reshape(C, shape=[-1])

with tf.Session() as sess:
    print('A:\n{}'.format(A.eval()))
    print('B:\n{}'.format(B.eval()))
    print('C:\n{}'.format(C.eval()))
    print('D:\n{}'.format(D.eval()))
Run Code Online (Sandbox Code Playgroud)

A:
[1 2 3 4 5]
B: # Add inner dimension
[[1]
 [2]
 [3]
 [4]
 [5]]
C: # Tile along inner dimension
[[1 1]
 [2 2]
 [3 3]
 [4 4]
 [5 5]]
D: # Remove innermost dimension
[1 1 2 2 3 3 4 4 5 5]
Run Code Online (Sandbox Code Playgroud)

编辑:如注释中所指出,使用tf.stack允许随时指定其他尺寸:

F = tf.stack([A, A], axis=1)
F = tf.reshape(F, shape=[-1])

with tf.Session() as sess:
    print(F.eval())

[1 1 2 2 3 3 4 4 5 5]
Run Code Online (Sandbox Code Playgroud)