我想在 numpy 中生成一个 3D 矩阵。代码是:
mean_value = np.array([1, 2, 3], dtype=np.float32)
h, w = 5, 5
b = np.ones((h, w, 1), dtype=np.float32) * np.reshape(mean_value, [1, 1, 3])
print(b.shape) # (5, 5, 3)
有没有更快的方法来生成b
?谢谢。
最佳答案
为了提高效率(内存、性能),只需使用 np.broadcast_to
进行广播
对于 View 输出 -
np.broadcast_to(mean_value,(h,w,)+mean_value.shape)
作为一个 View ,它没有内存开销,因此在运行时几乎是免费的。
让我们验证一下性能部分 -
In [45]: mean_value = np.array([1, 2, 3], dtype=np.float32)
...: h, w = 5, 5
In [46]: %timeit np.broadcast_to(mean_value,(h,w,)+mean_value.shape)
100000 loops, best of 3: 3.21 µs per loop
In [47]: mean_value = np.random.rand(10000)
...: h, w = 5000, 5000
In [48]: %timeit np.broadcast_to(mean_value,(h,w,)+mean_value.shape)
100000 loops, best of 3: 3.22 µs per loop
和内存部分(作为 View )-
In [49]: np.shares_memory(mean_value,np.broadcast_to(mean_value,(h,w,)+mean_value.shape))
Out[49]: True
关于python - 在 Numpy 中是否有更快的方法来做到这一点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58759956/