numpy中axis數軸理解

numpy中數組有數軸axis的說法,在numpy中提供的一些方法中經常需要這個參數。
其實numpy中的axis和維度是一一對應關係。
比如:
arr1 = np.arange(24).reshape((2, 3, 4))
#其中axis=0對應第一個維度2,axis=1對應第二個維度3,axis=2對應第三個維度4
#然後再哪個數軸上進行運算時,就相當於在對應維度的變化方向上做運算。

三維數組維度爲(塊, 行, 列)
二維數組維度爲(行, 列)

例子1:

	arr1 = np.arange(24).reshape((2, 3, 4))
	##當axis=0時
	print("arr1:\n", arr1)
	t1 = arr1.max(axis=0)
	print("arr1.max(axis=0):\n", t1)

輸出:
	arr:
	 [[[ 0  1  2  3]
	  [ 4  5  6  7]
	  [ 8  9 10 11]]

	 [[12 13 14 15]
	  [16 17 18 19]
	  [20 21 22 23]]]
	  
	  arr.max(axis=0):
	 [[12 13 14 15]
	 [16 17 18 19]
	 [20 21 22 23]]

分析:在axis=0(塊)的變化方向上運算,得到去掉第一維度的數組爲(3, 4)。然後第一塊(3, 4)和第二塊(3, 4)對應位置比較,最終得到數組t1,維度爲(3, 4)

例子2:

	##當axis=1時
	print("arr1:\n", arr1)
	t2 = arr1.max(axis=1)
	print("arr1.max(axis=1):\n", t2)

輸出:
	arr:
	 [[[ 0  1  2  3]
	  [ 4  5  6  7]
	  [ 8  9 10 11]]

	 [[12 13 14 15]
	  [16 17 18 19]
	  [20 21 22 23]]]
	  
	  arr.max(axis=1):
	 [[ 8  9 10 11]
	 [20 21 22 23]]

分析:在axis=1(行)的變化方向上運算,得到去掉第二維度的數組爲(2, 4)。然後每塊在第二維度的變化方向上計算最大值,得到最終數組t2,維度爲(2, 4)

例子3:

	##當axis=2時
	print("arr1:\n", arr1)
	t3 = arr.max(axis=2)
	print("arr.max(axis=2):\n", t3)
	
輸出:
	arr:
	 [[[ 0  1  2  3]
	  [ 4  5  6  7]
	  [ 8  9 10 11]]

	 [[12 13 14 15]
	  [16 17 18 19]
	  [20 21 22 23]]]
	  
	  arr.max(axis=2):
	 [[ 3  7 11]
	 [15 19 23]]

分析:在axis=3(列)的變化方向上運算,得到去掉第三維度的數組爲(2, 3)。然後兩快都在第三維度的變化方向上計算最大值,得到最終的數組t3,維度爲(2, 3)

參考:大佬的博客
https://blog.csdn.net/qq_29573053/article/details/76998695

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章