Python 在TF/Numpy中实现这种连接的优雅方式?
我有一个张量tmp1。我想创建tmp2,它是沿着tmp1的第一个轴的tmp1的N个副本(tmp1沿着其第一个轴的维度为1)。 我用了一个for循环。但我讨厌他们,因为他们减慢了训练。有没有更好的方法来创建tmp2Python 在TF/Numpy中实现这种连接的优雅方式?,python,numpy,tensorflow,keras,Python,Numpy,Tensorflow,Keras,我有一个张量tmp1。我想创建tmp2,它是沿着tmp1的第一个轴的tmp1的N个副本(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
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()
。使用轴
参数指定要沿哪个轴重复:
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()
:
完美的正是我想要的。原来tensorflow有自己的版本tf.tile。我知道我错过了一些东西。不幸的是,tf.tile不如repeat灵活,因为您无法指定连接轴。你必须做一个整形手术,明白了吗。谢谢
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]])