【发布时间】: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