IT

numpy.newaxis는 어떻게 작동하며 언제 사용합니까?

lottoking 2020. 6. 15. 08:03
반응형

numpy.newaxis는 어떻게 작동하며 언제 사용합니까?


내가 시도 할 때

numpy.newaxis

결과는 0에서 1까지의 x 축을 가진 2 차원 플롯 프레임을 제공합니다. 그러나 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]]

행 벡터를 열 벡터로 변경한다는 점을 제외하고는 같은 것입니까?

일반적으로의 사용은 무엇이며 numpy.newaxis어떤 상황에서 사용해야합니까?


간단하게는 넣어 newaxis하는 데 사용되는 차원이 증가 하여 기존 배열을 하나 더 차원 사용할 경우, 한 번 . 그러므로,

  • 1D 배열은 2D 배열이됩니다

  • 2D 배열은 3D 배열이됩니다

  • 3D 배열은 4D 배열이됩니다

  • 4D 배열은 5D 배열이됩니다

등등..

다음은 1D 어레이에서 2D 어레이로의 승격나타내는 시각적 설명입니다 .

newaxis 칸바 시각화


시나리오 -1 : 위의 그림과 같이 1D 배열을 행 벡터 또는 열 벡터np.newaxis명시 적으로 변환 하려는 경우 유용 할 수 있습니다 .

예:

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

시나리오 -2 : 일부 어레이를 추가 하는 등 일부 작업의 일부로 numpy 브로드 캐스팅사용하려는 경우

예:

다음 두 배열을 추가한다고 가정 해 봅시다.

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

이와 같이 추가하면 NumPy가 다음을 발생시킵니다 ValueError.

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

이 상황에서 np.newaxisNumPy가 브로드 캐스트 할 수 있도록 배열 중 하나의 차원을 늘리는 데 사용할 수 있습니다 .

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

참고 : 두 경우 모두 동일한 결과를 얻습니다 (하나는 다른 것의 전치 임).


시나리오 3 : 시나리오 1과 유사합니다. 그러나 배열을 더 높은 차원 np.newaxis으로 승격시키기 위해 두 번 이상 사용할 수 있습니다 . 이러한 연산은 때때로 고차 배열 ( 즉, Tensor )에 필요합니다.

예:

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 vs np.reshape 에 대한 추가 배경

newaxis 다중 축에 축을 임시로 추가 할 수있는 유사 인덱스라고도합니다.

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

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


What is np.newaxis?

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

>>> np.newaxis is None
True

It's just more descriptive if you read code that uses np.newaxis instead of None.

How to use np.newaxis?

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

>>> 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.newaxis to add multiple dimensions:

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

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

>>> 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 shape you could also reshape the array to add these dimensions:

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

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

When to use 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.imshow to 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 can broadcast arrays. This works because each length-1 dimension is simply broadcast to the length of the corresponding1 dimension of the other array.


1 If you want to read more about the broadcasting rules the NumPy documentation on that subject is very good. It also includes an example with 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.]])

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.

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


newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension.

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 newaxis added the extra dimension here, x1 had dimension (3,3) and X1_new has dimension (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:

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

따라서 newaxis행을 열 행렬로 변환하는 것이 아닙니다. 행렬의 차원이 커지므로 더 많은 작업을 수행 할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/29241056/how-does-numpy-newaxis-work-and-when-to-use-it

반응형