numpy.newaxis如何工作以及何时使用它? [英] How does numpy.newaxis work and when to use it?
问题描述
当我尝试
numpy.newaxis
结果为我提供了一个x轴从0到1的二维绘图框.但是,当我尝试使用numpy.newaxis
切片矢量时,
the result gives me a 2-d plot frame with x-axis from 0 to 1. However, when I try using numpy.newaxis
to slice a vector,
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?
通常, numpy.newaxis
,在什么情况下应该使用它?
Generally, what is the use of numpy.newaxis
, and in which circumstances should we use it?
推荐答案
Simply put, the newaxis
is used to increase the dimension of the existing array by one more dimension, when used once. Thus,
-
1D 阵列将变为 2D 阵列
2D 阵列将变为 3D 阵列
3D 阵列将变为 4D 阵列
4D 阵列将变为 5D 阵列
以此类推.
这是一个视觉插图,描绘了从1D数组到2D数组的促销.
Here is a visual illustration which depicts promotion of 1D array to 2D arrays.
场景1 : np.newaxis
在您要显式将一维数组转换为行向量或列向量时可能会派上用场>,如上图所示.
Scenario-1: np.newaxis
might come in handy when you want to explicitly convert a 1D array to either a row vector or a column vector, as depicted in the above picture.
示例:
# 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 broadcasting as part of some operation, for instance while doing addition of some arrays.
示例:
假设您要添加以下两个数组:
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])
如果您尝试像这样添加它们,NumPy将引发以下ValueError
:
If you try to add these just like that, NumPy will raise the following ValueError
:
ValueError: operands could not be broadcast together with shapes (5,) (3,)
在这种情况下,您可以使用 np.newaxis
来增加其中一个数组的尺寸,以便NumPy可以广播.
In this situation, you can use np.newaxis
to increase the dimension of one of the arrays so that NumPy can broadcast.
In [2]: x1_new = x1[:, np.newaxis] # x1[:, None]
# now, the shape of x1_new is (5, 1)
# array([[1],
# [2],
# [3],
# [4],
# [5]])
现在,添加:
In [3]: x1_new + x2
Out[3]:
array([[ 6, 5, 4],
[ 7, 6, 5],
[ 8, 7, 6],
[ 9, 8, 7],
[10, 9, 8]])
或者,您也可以将新轴添加到数组x2
:
In [6]: x2_new = x2[:, np.newaxis] # x2[:, None]
In [7]: x2_new # shape is (3, 1)
Out[7]:
array([[5],
[4],
[3]])
现在,添加:
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).
方案3 :这与方案1类似.但是,您可以使用 np.newaxis
多次以提升数组为更高的维度.对于高阶数组(即张量),有时需要执行此操作.
Scenario-3: This is similar to scenario-1. But, you can use np.newaxis
more than once to promote the array to higher dimensions. Such an operation is sometimes needed for higher order arrays (i.e. Tensors).
示例:
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)
有关的更多背景np.newaxis 与 np.reshape
More background on np.newaxis vs np.reshape
newaxis
也称为伪索引,它允许将轴临时添加到多数组中.
newaxis
is also called as a pseudo-index that allows the temporary addition of an axis into a multiarray.
np.newaxis
使用切片运算符重新创建数组,而 np.reshape
将数组调整为所需的布局(假设尺寸匹配;这对于
np.newaxis
uses the slicing operator to recreate the array while np.reshape
reshapes the array to the desired layout (assuming that the dimensions match; And this is must for a reshape
to happen).
示例
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)
在上面的示例中,我们在B
的第一轴和第二轴之间插入了一个临时轴(以使用广播).使用 np.newaxis
进行广播 a>操作工作.
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.newaxis
to make the broadcasting operation work.
一般提示 :您也可以使用None
代替相同的对象
In [13]: np.newaxis is None
Out[13]: True
P.S.另请参见以下很好的答案: newaxis vs reshape以添加尺寸
P.S. Also see this great answer: newaxis vs reshape to add dimensions
这篇关于numpy.newaxis如何工作以及何时使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!