numpy.newaxis如何工作以及何时使用它?

Yue*_*ang 155 python numpy multidimensional-array numpy-broadcasting numpy-ndarray

当我尝试

numpy.newaxis
Run Code Online (Sandbox Code Playgroud)

结果给出了一个2维的绘图框架,x轴从0到1.但是,当我尝试使用numpy.newaxis切片矢量时,

vector[0:4,]
[ 0.04965172  0.04979645  0.04994022  0.05008303]
vector[:, np.newaxis][0:4,]
[[ 0.04965172]
[ 0.04979645]
[ 0.04994022]
[ 0.05008303]]
Run Code Online (Sandbox Code Playgroud)

除了它将行向量更改为列向量之外,它是否相同?

一般来说,numpy.newaxis我们应该使用什么,在什么情况下使用它?

kma*_*o23 270

简单地说,newaxis是用来提高尺寸由现有的阵列的一个更尺寸,当使用时一次.从而,

  • 1D阵列将成为2D阵列

  • 2D阵列将成为3D阵列

  • 3D阵列将成为4D阵列

  • 4D阵列将成为5D阵列

等等..

这是一个视觉图示,描绘了将1D阵列推广到2D阵列.

newaxis canva可视化


场景-1:np.newaxis当您想要将1D数组显式转换为行向量列向量时,可能会派上用场,如上图所示.

例:

# 1D array
In [7]: arr = np.arange(4)
In [8]: arr.shape
Out[8]: (4,)

# make it as row vector by inserting an axis along first dimension
In [9]: row_vec = arr[np.newaxis, :]     # arr[None, :]
In [10]: row_vec.shape
Out[10]: (1, 4)

# make it as column vector by inserting an axis along second dimension
In [11]: col_vec = arr[:, np.newaxis]     # arr[:, None]
In [12]: col_vec.shape
Out[12]: (4, 1)
Run Code Online (Sandbox Code Playgroud)

场景-2:当我们想要使用numpy广播作为某些操作的一部分时,例如在添加一些数组时.

例:

假设您要添加以下两个数组:

 x1 = np.array([1, 2, 3, 4, 5])
 x2 = np.array([5, 4, 3])
Run Code Online (Sandbox Code Playgroud)

如果您尝试添加这些,NumPy将提出以下内容ValueError:

ValueError: operands could not be broadcast together with shapes (5,) (3,)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以使用np.newaxis增加其中一个数组的维度,以便NumPy可以广播.

In [2]: x1_new = x1[:, np.newaxis]    # x1[:, None]
# now, the shape of x1_new is (5, 1)
# array([[1],
#        [2],
#        [3],
#        [4],
#        [5]])
Run Code Online (Sandbox Code Playgroud)

现在,添加:

In [3]: x1_new + x2
Out[3]:
array([[ 6,  5,  4],
       [ 7,  6,  5],
       [ 8,  7,  6],
       [ 9,  8,  7],
       [10,  9,  8]])
Run Code Online (Sandbox Code Playgroud)

或者,您也可以向数组添加新轴x2:

In [6]: x2_new = x2[:, np.newaxis]    # x2[:, None]
In [7]: x2_new     # shape is (3, 1)
Out[7]: 
array([[5],
       [4],
       [3]])
Run Code Online (Sandbox Code Playgroud)

现在,添加:

In [8]: x1 + x2_new
Out[8]: 
array([[ 6,  7,  8,  9, 10],
       [ 5,  6,  7,  8,  9],
       [ 4,  5,  6,  7,  8]])
Run Code Online (Sandbox Code Playgroud)

注意:观察到我们在两种情况下得到相同的结果(但一个是另一个的转置).


场景-3:这与场景-1类似.但是,你可以使用np.newaxis不止一次地促进阵列更高的层面.高阶阵列(即张量)有时需要这样的操作.

例:

In [124]: arr = np.arange(5*5).reshape(5,5)

In [125]: arr.shape
Out[125]: (5, 5)

# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]    # arr[None, ..., None, None]

In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)
Run Code Online (Sandbox Code Playgroud)

有关np.newaxis vs np.reshape的更多背景信息

newaxis 也称为伪索引,允许将轴临时添加到多个阵列中.

np.newaxis使用切片操作符重新创建数组,同时np.reshape将数组重新整形为所需的布局(假设尺寸匹配;这是必须reshape).

In [13]: A = np.ones((3,4,5,6))
In [14]: B = np.ones((4,6))
In [15]: (A + B[:, np.newaxis, :]).shape     # B[:, None, :]
Out[15]: (3, 4, 5, 6)
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我们在第一和第二轴之间插入一个临时轴B(使用广播).这里填充缺失的轴np.newaxis用于使广播操作起作用.


一般提示:您也可以None代替np.newaxis; 这些实际上是相同的对象.

In [13]: np.newaxis is None
Out[13]: True
Run Code Online (Sandbox Code Playgroud)

PS还看到这个伟大的答案:newaxis vs reshape添加尺寸

  • “等等,都是‘无’?-一直都是。” (8认同)
  • x1_new + x2是什么类型的操作?对我来说很奇怪,因为我认为只有两个矩阵具有相同的维数(或者其中一个实际上只是一个标量),才能添加两个矩阵。 (3认同)
  • 这是一个很棒的解释 (3认同)
  • @kmario23 确实出处隐藏在文章的最后一句,难怪我没有看到它。即使有这样的归因,我也认为它接近抄袭。在我的书中,只有同一作者在不同平台上发帖时,逐字复制才是可接受的。我对Medium 的期望更好。 (3认同)
  • @Stephen正如我在答案中还指出的,这是因为NumPy Broadcasting。 (2认同)
  • @valdrinit 很高兴这对你有帮助:) (2认同)
  • @kmario23 == Ian Dzindo 或 Ian Dzindo01 在 2018 年的 Medium 帖子中抄袭了这个答案:https://medium.com/@ian.dzindo01/what-is-numpy-newaxis-and-when-to-use-it -8cb61c7ed6ae。 (2认同)

MSe*_*ert 23

什么是np.newaxis

np.newaxis仅仅是Python的常量的别名None,这意味着无论你使用np.newaxis,你也可以使用None:

>>> np.newaxis is None
True
Run Code Online (Sandbox Code Playgroud)

如果你阅读使用代替的代码,它只是更具描述np.newaxisNone.

怎么用np.newaxis

np.newaxis,通常使用与切片.它表示您要为数组添加其他维度.的位置np.newaxis代表,我想补充的尺寸.

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape
(10,)
Run Code Online (Sandbox Code Playgroud)

在第一个示例中,我使用第一个维度中的所有元素并添加第二个维度:

>>> a[:, np.newaxis]
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
>>> a[:, np.newaxis].shape
(10, 1)
Run Code Online (Sandbox Code Playgroud)

第二个示例将维度添加为第一维,然后使用原始数组的第一维中的所有元素作为结果数组的第二维中的元素:

>>> a[np.newaxis, :]  # The output has 2 [] pairs!
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> a[np.newaxis, :].shape
(1, 10)
Run Code Online (Sandbox Code Playgroud)

同样,您可以使用多个np.newaxis来添加多个维度:

>>> a[np.newaxis, :, np.newaxis]  # note the 3 [] pairs in the output
array([[[0],
        [1],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7],
        [8],
        [9]]])
>>> a[np.newaxis, :, np.newaxis].shape
(1, 10, 1)
Run Code Online (Sandbox Code Playgroud)

有替代品np.newaxis吗?

NumPy中还有另一个非常相似的功能:np.expand_dims它也可用于插入一个维度:

>>> np.expand_dims(a, 1)  # like a[:, np.newaxis]
>>> np.expand_dims(a, 0)  # like a[np.newaxis, :]
Run Code Online (Sandbox Code Playgroud)

但鉴于它只是插入1s,shape你也可以reshape在数组中添加这些尺寸:

>>> a.reshape(a.shape + (1,))  # like a[:, np.newaxis]
>>> a.reshape((1,) + a.shape)  # like a[np.newaxis, :]
Run Code Online (Sandbox Code Playgroud)

大多数时候np.newaxis是添加尺寸的最简单方法,但知道替代方案是很好的.

什么时候用np.newaxis

在几种情况下,添加有用的维度:

  • 如果数据应具有指定数量的维度.例如,如果要matplotlib.pyplot.imshow用于显示一维数组.

  • 如果你想让NumPy广播数组.通过添加维度,您可以获得一个数组的所有元素之间的差异:a - a[:, np.newaxis].这是因为NumPy操作以最后一个维度1开始广播.

  • 添加必要的维度以便NumPy 可以广播数组.这是有效的,因为每个长度为1的维度只是广播到另一个数组的相应1维度的长度.


1如果您想了解有关广播规则的更多信息,NumPy有关该主题的文档非常好.它还包括一个示例np.newaxis:

>>> a = np.array([0.0, 10.0, 20.0, 30.0])
>>> b = np.array([1.0, 2.0, 3.0])
>>> a[:, np.newaxis] + b
array([[  1.,   2.,   3.],
       [ 11.,  12.,  13.],
       [ 21.,  22.,  23.],
       [ 31.,  32.,  33.]])
Run Code Online (Sandbox Code Playgroud)


Kev*_*vin 9

您从一维数字列表开始.使用之后numpy.newaxis,将其转换为二维矩阵,每行包含四行,每行一列.

然后,您可以使用该矩阵进行矩阵乘法,或将其用于构建更大的4 xn矩阵.


小智 6

newaxis选择元组中的对象用于将结果选择的维度扩展一个单位长度维度。

这不仅仅是行矩阵到列矩阵的转换。

考虑下面的例子:

In [1]:x1 = np.arange(1,10).reshape(3,3)
       print(x1)
Out[1]: array([[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]])
Run Code Online (Sandbox Code Playgroud)

现在让我们为我们的数据添加新的维度,

In [2]:x1_new = x1[:,np.newaxis]
       print(x1_new)
Out[2]:array([[[1, 2, 3]],

              [[4, 5, 6]],

              [[7, 8, 9]]])
Run Code Online (Sandbox Code Playgroud)

您可以看到newaxis这里添加了额外的维度,x1 的维度为 (3,3),而 X1_new 的维度为 (3,1,3)。

我们的新维度如何使我们能够进行不同的操作:

In [3]:x2 = np.arange(11,20).reshape(3,3)
       print(x2)
Out[3]:array([[11, 12, 13],
              [14, 15, 16],
              [17, 18, 19]]) 
Run Code Online (Sandbox Code Playgroud)

将 x1_new 和 x2 相加,我们得到:

In [4]:x1_new+x2
Out[4]:array([[[12, 14, 16],
               [15, 17, 19],
               [18, 20, 22]],

              [[15, 17, 19],
               [18, 20, 22],
               [21, 23, 25]],

              [[18, 20, 22],
               [21, 23, 25],
               [24, 26, 28]]])
Run Code Online (Sandbox Code Playgroud)

因此,newaxis不仅仅是行到列矩阵的转换。它增加了矩阵的维数,从而使我们能够对其进行更多操作。

  • 它不仅仅是矩阵,它还适用于 NumPy 术语中的任何“ndarray”。 (2认同)