とはnumpy.newaxis
いつ使用すればよいですか?
これを 1 次元配列で使用すると、次の結果x
が生成されます。
>>> x
array([0, 1, 2, 3])
>>> x[np.newaxis, :]
array([[0, 1, 2, 3]])
>>> x[:, np.newaxis]
array([[0],
[1],
[2],
[3]])
ベストアンサー1
簡単に言えば、numpy.newaxis
一度使用すると、既存の配列の次元を1つ増やすために使用されます。つまり、
1D配列は2D配列になる
2D配列は3D配列になる
3D配列は4D配列になる
4D配列は5D配列になる
等々..
これは、1D 配列を 2D 配列に昇格する様子を示す視覚的な図です。
シナリオ1 :np.newaxis
上の図に示すように、1 次元配列を行ベクトルまたは列ベクトルに明示的に変換する場合に便利です。
例:
# 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 ブロードキャストたとえば、配列の追加を実行するときなど、何らかの操作の一部として。
例:
次の 2 つの配列を追加するとします。
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.newaxis
配列の1つの次元を増やして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]])
次に以下を追加します:
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
配列を高次元に昇格するには、これを複数回実行します。このような操作は、高次元配列 (つまり、テンソル) で必要になることがあります。
例:
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)
代わりに、numpy.expand_dims
直感的なキーワード引数を持ちますaxis
。
# 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)
背景情報np.newaxis対np.reshape
newaxis
マルチ配列に軸を一時的に追加できるようにする疑似インデックスとも呼ばれます。
np.newaxis
スライス演算子を使用して配列を再作成し、numpy.reshape
配列を希望のレイアウトに再形成します(寸法が一致していると仮定します。これは、reshape
発生する)。
例
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
(ブロードキャストを使用するために)の1番目と2番目の軸の間に一時的な軸を挿入しました。不足している軸は、ここで次のように埋められます。np.newaxis
作るために放送操作作業。
一般的なヒントNone
:代わりにも使用できますnp.newaxis
; これらは実際には同じオブジェクト。
In [13]: np.newaxis is None
Out[13]: True
PS この素晴らしい回答もご覧ください:次元を追加するための newaxis と reshape