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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29241056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:15:50  来源:igfitidea点击:

How does numpy.newaxis work and when to use it?

pythonnumpymultidimensional-arrayarray-broadcastingnumpy-ndarray

提问by Yue Harriet Huang

When I try

当我尝试

numpy.newaxis

the result gives me a 2-d plot frame with x-axis from 0 to 1. However, when I try using numpy.newaxisto slice a vector,

结果给了我一个 x 轴从 0 到 1numpy.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]]

Is it the same thing except that it changes a row vector to a column vector?

除了将行向量更改为列向量之外,它是同一回事吗?

Generally, what is the use of numpy.newaxis, and in which circumstances should we use it?

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

回答by Kevin

You started with a one-dimensional list of numbers. Once you used numpy.newaxis, you turned it into a two-dimensional matrix, consisting of four rows of one column each.

您从一维数字列表开始。一旦你使用了numpy.newaxis,你就将它变成了一个二维矩阵,由四行组成,每行一列。

You could then use that matrix for matrix multiplication, or involve it in the construction of a larger 4 x n matrix.

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

回答by kmario23

Simply put, numpy.newaxisis used to increase the dimensionof the existing array by one more dimension, when used once. Thus,

简单的说,numpy.newaxis用于将现有数组的维数增加一维,当使用一次时。因此,

  • 1Darray will become 2Darray

  • 2Darray will become 3Darray

  • 3Darray will become 4Darray

  • 4Darray will become 5Darray

  • 一维数组会变成二维数组

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

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

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

and so on..

等等..

Here is a visual illustration which depicts promotionof 1D array to 2D arrays.

这是一个直观的插图,描述了从一维数组到二维数组的提升

newaxis canva visualization

newaxis 画布可视化



Scenario-1: np.newaxismight come in handy when you want to explicitlyconvert a 1D array to either a row vectoror a column vector, as depicted in the above picture.

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

Example:

例子:

# 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)


Scenario-2: When we want to make use of numpy broadcastingas part of some operation, for instance while doing additionof some arrays.

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

Example:

例子:

Let's say you want to add the following two arrays:

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

 x1 = np.array([1, 2, 3, 4, 5])
 x2 = np.array([5, 4, 3])

If you try to add these just like that, NumPy will raise the following ValueError:

如果您尝试像这样添加这些,NumPy 将引发以下问题ValueError

ValueError: operands could not be broadcast together with shapes (5,) (3,)

In this situation, you can use np.newaxisto increase the dimension of one of the arrays so that NumPy can broadcast.

在这种情况下,您可以使用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]])

Now, add:

现在,添加:

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


Alternatively, you can also add new axis to the array x2:

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

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

Now, add:

现在,添加:

In [8]: x1 + x2_new
Out[8]: 
array([[ 6,  7,  8,  9, 10],
       [ 5,  6,  7,  8,  9],
       [ 4,  5,  6,  7,  8]])

Note: Observe that we get the same result in both cases (but one being the transpose of the other).

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



Scenario-3: This is similar to scenario-1. But, you can use np.newaxismore than once to promotethe array to higher dimensions. Such an operation is sometimes needed for higher order arrays (i.e. Tensors).

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

Example:

例子:

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)


More background on np.newaxisvs np.reshape

有关np.newaxisnp.reshape 的更多背景

newaxisis also called as a pseudo-index that allows the temporary addition of an axis into a multiarray.

newaxis也称为伪索引,允许将轴临时添加到多数组中。

np.newaxisuses the slicing operator to recreate the array while np.reshapereshapes the array to the desired layout (assuming that the dimensions match; And this is mustfor a reshapeto happen).

np.newaxis使用切片运算符重新创建数组,同时将数组np.reshape重塑为所需的布局(假设维度匹配;这是a发生的必要条件reshape)。

Example

例子

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)

In the above example, we inserted a temporary axis between the first and second axes of B(to use broadcasting). A missing axis is filled-in here using np.newaxisto make the broadcastingoperation work.

在上面的例子中,我们在B(使用广播)的第一个和第二个轴之间插入了一个临时轴。此处填写缺失的轴np.newaxis用于使广播操作工作。



General Tip: You can also use Nonein place of np.newaxis; These are in fact the same objects.

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

In [13]: np.newaxis is None
Out[13]: True

P.S. Also see this great answer: newaxis vs reshape to add dimensions

PS另请参阅这个很好的答案:newaxis vs reshape to add维度

回答by harsh hundiwala

newaxisobject in the selection tuple serves to expand the dimensionsof the resulting selection by one unit-lengthdimension.

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

It is not just conversion of row matrix to column matrix.

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

Consider the example below:

考虑下面的例子:

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

Now lets add new dimension to our data,

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

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

              [[4, 5, 6]],

              [[7, 8, 9]]])

You can see that newaxisadded the extra dimension here, x1 had dimension (3,3) and X1_new has dimension (3,1,3).

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

How our new dimension enables us to different operations:

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

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

Adding x1_new and x2, we get:

将 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]]])

Thus, newaxisis not just conversion of row to column matrix. It increases the dimension of matrix, thus enabling us to do more operations on it.

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

回答by MSeifert

What is np.newaxis?

什么是np.newaxis

The np.newaxisis just an alias for the Python constant None, which means that wherever you use np.newaxisyou could also use None:

np.newaxis只是 Python 常量的别名None,这意味着无论您在何处使用np.newaxis,都可以使用None

>>> np.newaxis is None
True

It's just more descriptiveif you read code that uses np.newaxisinstead of None.

这只是更多的描述,如果你读代码使用np.newaxis,而不是None

How to use np.newaxis?

如何使用np.newaxis

The np.newaxisis generally used with slicing. It indicates that you want to add an additional dimension to the array. The position of the np.newaxisrepresents where I want to add dimensions.

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,)

In the first example I use all elements from the first dimension and add a second dimension:

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

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

The second example adds a dimension as first dimension and then uses all elements from the first dimension of the original array as elements in the second dimension of the result array:

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

>>> 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)

Similarly you can use multiple np.newaxisto add multiple dimensions:

同样,您可以使用 multiplenp.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)

Are there alternatives to np.newaxis?

有替代品np.newaxis吗?

There is another very similar functionality in NumPy: np.expand_dims, which can also be used to insert one dimension:

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

>>> np.expand_dims(a, 1)  # like a[:, np.newaxis]
>>> np.expand_dims(a, 0)  # like a[np.newaxis, :]

But given that it just inserts 1s in the shapeyou could also reshapethe array to add these dimensions:

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

>>> a.reshape(a.shape + (1,))  # like a[:, np.newaxis]
>>> a.reshape((1,) + a.shape)  # like a[np.newaxis, :]

Most of the times np.newaxisis the easiest way to add dimensions, but it's good to know the alternatives.

大多数情况下,这np.newaxis是添加维度的最简单方法,但最好了解替代方法。

When to use np.newaxis?

什么时候使用np.newaxis

In several contexts is adding dimensions useful:

在多种情况下,添加维度很有用:

  • If the data should have a specified number of dimensions. For example if you want to use matplotlib.pyplot.imshowto display a 1D array.

  • If you want NumPy to broadcast arrays. By adding a dimension you could for example get the difference between all elements of one array: a - a[:, np.newaxis]. This works because NumPy operations broadcast starting with the last dimension 1.

  • To add a necessary dimension so that NumPy canbroadcast arrays. This works because each length-1 dimension is simply broadcast to the length of the corresponding1dimension of the other array.

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

  • 如果您希望 NumPy 广播数组。通过增加一个维度例如,你可以得到一个数组的所有元素之间的区别:a - a[:, np.newaxis]。这是有效的,因为 NumPy 操作从最后一个维度1开始广播。

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



1If you want to read more about the broadcasting rules the NumPy documentation on that subjectis very good. It also includes an example with np.newaxis:

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.]])
>>> 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.]])