我有张量tmp1。我想创建tmp2,它​​是tmp1的第一个轴的N个副本tmp1(tmp1的第一个轴的维数为1)。
我做了一个for循环。但是我讨厌他们,因为他们减慢了训练速度。有没有更好的方法来创建tmp2?

tmp2 = tf.concat((tmp1, tmp1), axis=1)
for i in range(2*batch_size-2):
    tmp2 = tf.concat((tmp2, tmp1), axis=1)


我在上面所做的是:首先用两个tmp1副本初始化tmp2,然后继续以类似的方式沿该轴添加更多副本。

最佳答案

我认为您想要numpy repeat()。使用axis参数指定要重复的轴:

In [1]: x = np.random.randint(1, 10, (5,5))
In [2]: x
Out[2]:
array([[7, 3, 6, 8, 8],
       [6, 5, 3, 3, 9],
       [1, 7, 1, 5, 7],
       [4, 6, 6, 8, 3],
       [3, 7, 8, 6, 7]])
In [4]: x.repeat(2, axis=1)
Out[4]:
array([[7, 7, 3, 3, 6, 6, 8, 8, 8, 8],
       [6, 6, 5, 5, 3, 3, 3, 3, 9, 9],
       [1, 1, 7, 7, 1, 1, 5, 5, 7, 7],
       [4, 4, 6, 6, 6, 6, 8, 8, 3, 3],
       [3, 3, 7, 7, 8, 8, 6, 6, 7, 7]])


或者可能是numpy.tile()

In [15]: np.tile(x, 2)
Out[15]:
array([[7, 3, 6, 8, 8, 7, 3, 6, 8, 8],
   [6, 5, 3, 3, 9, 6, 5, 3, 3, 9],
   [1, 7, 1, 5, 7, 1, 7, 1, 5, 7],
   [4, 6, 6, 8, 3, 4, 6, 6, 8, 3],
   [3, 7, 8, 6, 7, 3, 7, 8, 6, 7]])

关于python - 在TF/Numpy中进行这种级联的一种优雅方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56551598/

10-10 05:03