numpy.newaxis 如何工作以及何时使用它? [英] How does numpy.newaxis work and when to use it?

查看:32
本文介绍了numpy.newaxis 如何工作以及何时使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试

numpy.newaxis

结果给了我一个 x 轴从 0 到 1 的二维图框.但是,当我尝试使用 numpy.newaxis 对向量进行切片时,

vector[0:4,][ 0.04965172 0.04979645 0.04994022 0.05008303]向量[:, np.newaxis][0:4,][[0.04965172][0.04979645][0.04994022][0.05008303]]

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

一般来说


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

示例:

# 一维数组在 [7] 中:arr = np.arange(4)在 [8]: arr.shape输出[8]:(4,)# 通过沿第一维插入轴使其成为行向量在 [9]: row_vec = arr[np.newaxis, :] # arr[None, :]在 [10]:row_vec.shape输出 [10]: (1, 4)# 通过沿第二维插入轴使其成为列向量在 [11]: col_vec = arr[:, np.newaxis] # arr[:, None]在 [12]: col_vec.shape输出 [12]: (4, 1)


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

示例:

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

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

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

ValueError: 操作数无法与形状 (5,) (3,) 一起广播

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

在 [2]: x1_new = x1[:, np.newaxis] # x1[:, None]# 现在,x1_new 的形状是 (5, 1)# 数组([[1],# [2],# [3],# [4],# [5]])

现在,添加:

在[3]中:x1_new + x2出[3]:数组([[ 6, 5, 4],[ 7, 6, 5],[ 8, 7, 6],[ 9, 8, 7],[10, 9, 8]])


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

在 [6]: x2_new = x2[:, np.newaxis] # x2[:, None]在 [7]: x2_new # 形状是 (3, 1)出[7]:数组([[5],[4],[3]])

现在,添加:

在[8]中:x1 + x2_new出[8]:数组([[ 6, 7, 8, 9, 10],[ 5, 6, 7, 8, 9],[ 4, 5, 6, 7, 8]])

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


场景 3:这类似于场景 1.但是,您可以使用 np.newaxis 多次提升数组到更高的维度.对于高阶数组(即张量),有时需要这样的操作.

示例:

在[124]中:arr = np.arange(5*5).reshape(5,5)在 [125]: arr.shape输出[125]:(5, 5)# 将二维数组提升为 5D 数组在 [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis] # arr[None, ..., None, None]在 [127]: arr_5D.shape输出[127]: (1, 5, 5, 1, 1)

作为替代,您可以使用 numpy.expand_dims 有一个直观的 axis kwarg.

# 在结果数组的第 1、4 和最后一维添加新轴在 [131] 中:newaxes = (0, 3, -1)在 [132]: arr_5D = np.expand_dims(arr,axis=newaxes)在 [133]: arr_5D.shape输出[133]: (1, 5, 5, 1, 1)


更多关于 np.newaxisnp.reshape

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

np.newaxis使用切片运算符重新创建数组,而 numpy.reshape 将数组重塑为所需的布局(假设尺寸匹配;这是 必须 对于 reshape 发生).

示例

在[13]中:A = np.ones((3,4,5,6))在 [14] 中:B = np.ones((4,6))在 [15]: (A + B[:, np.newaxis, :]).shape # B[:, None, :]输出[15]:(3、4、5、6)

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


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

在 [13] 中:np.newaxis 是 None输出[13]:真

附言另请参阅这个很棒的答案:newaxis 与 reshape 以添加尺寸

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.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?

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

解决方案

Simply put, numpy.newaxis is used to increase the dimension of the existing array by one more dimension, when used once. Thus,

  • 1D array will become 2D array

  • 2D array will become 3D array

  • 3D array will become 4D array

  • 4D array will become 5D array

and so on..

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


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.

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 broadcasting as part of some operation, for instance while doing addition of some arrays.

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 :

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

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

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:

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.newaxis more than once to promote the array to higher dimensions. Such an operation is sometimes needed for higher order arrays (i.e. 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)

As an alternative, you can use numpy.expand_dims that has an intuitive axis kwarg.

# adding new axes at 1st, 4th, and last dimension of the resulting array
In [131]: newaxes = (0, 3, -1)
In [132]: arr_5D = np.expand_dims(arr, axis=newaxes)
In [133]: arr_5D.shape
Out[133]: (1, 5, 5, 1, 1)


More background on np.newaxis vs np.reshape

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

np.newaxis uses the slicing operator to recreate the array while numpy.reshape reshapes the array to the desired layout (assuming that the dimensions match; And this is must for a reshape to happen).

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.newaxis to make the broadcasting operation work.


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

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

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

这篇关于numpy.newaxis 如何工作以及何时使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆