gpt4 book ai didi

python - numpy atleast_3d() 的行为

转载 作者:行者123 更新时间:2023-11-28 17:17:11 24 4
gpt4 key购买 nike

有人可以向我解释 np.atleast_3d() 的行为吗?

从使用 np.atleast_2d() 我认为这类似于添加 np.newaxis 同时将传递给它的任何内容放在最后一个维度:

np.atleast_2d(3.0)
>>> array([[ 3.]])

np.atleast_2d([1.0, 2.0, 3.0])
>>> array([[1.0, 2.0, 3.0]])

但是 np.atleast_3d() 的行为似乎很不一样

np.atleast_3d([[2.9, 3.0]])
>>> array([[[ 2.9],
[ 3. ]]])

文档说明

For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1),
and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).

我本来希望 (M, N) 变成 (1, M, N) 而 (N,) 变成 (1, 1, N, 1)

这种行为不是误导吗?

最佳答案

以下是 atleast_2d 的摘录:

    if len(ary.shape) == 0:
result = ary.reshape(1, 1)
elif len(ary.shape) == 1:
result = ary[newaxis,:]
else:
result = ary

所以如果数组是 1d,它使用 newaxis 技巧。

对于 3d:

    if len(ary.shape) == 0:
result = ary.reshape(1, 1, 1)
elif len(ary.shape) == 1:
result = ary[newaxis,:, newaxis]
elif len(ary.shape) == 2:
result = ary[:,:, newaxis]
else:
result = ary

它也使用了 newaxis 技巧,但对于 1 维和二维数组采用不同的方式。它按照文档所说的进行操作。

还有其他改变形状的方法。例如,column_stack 使用

array(arr, copy=False, subok=True, ndmin=2).T

expand_dims 使用

a.reshape(shape[:axis] + (1,) + shape[axis:])

关于python - numpy atleast_3d() 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43612024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com