Метод Numpy expand_dims() расширяет форму массива.
Содержание
Что такое функция np.expand_dims() в Python?
np.expand_dims() в Python — это функция математической библиотеки, которая расширяет массив, вставляя новую ось в указанную позицию. Эта функция требует два параметра.
Синтаксис
|
1 |
np.expand_dims(arr, axis) |
Параметры
arr: является входным массивом (обязательный параметр).
axis: позиция, где должна быть вставлена новая ось.
Примеры с методом numpy expand_dims()
См. следующий код.
|
1 2 3 4 5 6 7 8 |
# app.py import numpy as np x = np.array([11, 21]) print('Array x:', x) print('x shape: ', x.shape) |
Выход
|
1 2 3 |
python3 app.py Array x: [11 21] x shape: (2,) |
Теперь давайте расширим размер по оси X. Напишите следующий код.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
# app.py import numpy as np x = np.array([11, 21]) print('Array x:', x) print('x shape: ', x.shape) y = np.expand_dims(x, axis=0) print(y) print('y shape: ', y.shape) |
Выход
|
1 2 3 4 5 |
python3 app.py Array x: [11 21] x shape: (2,) [[11 21]] y shape: (1, 2) |
Y — это результат добавления нового измерения к x.
Из вывода видно, что мы добавили новое измерение по оси = 0.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# app.py import numpy as np x = np.array(([11, 21], [19, 18])) print('Array x:', x) print('\n') # insert axis at position 0 y = np.expand_dims(x, axis=0) print('Array y:') print(y) print('\n') print('The shape of X and Y array:') print(x.shape, y.shape) print('\n') # insert axis at position 1 y = np.expand_dims(x, axis=1) print('Array Y after inserting axis at position 1:') print(y) print('\n') print('x.ndim and y.ndim:') print(x.ndim, y.ndim) print('\n') print('x.shape and y.shape:') print(x.shape, y.shape) |
Выход
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
python3 app.py Array x: [[11 21] [19 18]] Array y: [[[11 21] [19 18]]] The shape of X and Y array:(2, 2)(1, 2, 2) Array Y after inserting axis at position 1: [[[11 21]] [[19 18]]] x.ndim and y.ndim: 2 3 x.shape and y.shape:(2, 2)(2, 1, 2) |
В этом примере мы видим это с помощью метода Numpy.expanded_dims(), и мы можем получить расширенный массив с помощью этого метода.
