【问题标题】:Is there a quicker way to do this in Numpy?在 Numpy 中有没有更快的方法来做到这一点?
【发布时间】:2019-11-08 03:30:08
【问题描述】:

我想在 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.array([[[1, 2, 3]*h]*w]) 的代码少了很多,而且我怀疑速度更快,因为 python 列表只是填充了对同一对象的引用。
  • @JoshuaF 感谢您的评论!我不确定我的代码是否有效。所以我在寻求提高效率的帮助。您的解决方案非常出色。

标签: python numpy numpy-ndarray array-broadcasting


【解决方案1】:

为了提高效率(内存、性能),只需 broadcastnp.broadcast_to 即可查看输出 -

np.broadcast_to(mean_value,(h,w,)+mean_value.shape)

作为一个视图,它没有内存开销,因此在运行时几乎是免费的。

我们来验证一下性能部分——

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

还有记忆部分(作为一个视图)-

In [49]: np.shares_memory(mean_value,np.broadcast_to(mean_value,(h,w,)+mean_value.shape))
Out[49]: True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多