python - 在 TF/Numpy 中进行这种串联的优雅方法是什么?

标签 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,然后以类似的方式沿该轴继续添加更多副本。

最佳答案

我认为你想要 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/

相关文章:

python - 在 Pandas 中获取平均年份(多年平均天数)

python - 如何在不同轴上绘制 numpy 数组的数字?

python - 使用tensorflow时没有名为 'Pil'的模块

python-3.x - 由于负索引查找,Keras 嵌入层中的 InvalidArgumentError

python - python 中的扩展切片?

python - 我可以在 PySimpleGUI slider 上设置低于 0.1 的分辨率吗?

python - 让文本显示在子图图像前面

Python,删除列表中所有出现的字符串

python - 在numpy中用3d数组索引2d数组

tensorflow - tf.nn.bias_add(value, bias) 的输出是否与 value 的形状不同