np.where在多維數(shù)組的應(yīng)用方式
np.where在多維數(shù)組的應(yīng)用
函數(shù)用途
返回查找的參數(shù),在數(shù)組中的索引。
Code
舉例:
- 一般卷積神經(jīng)網(wǎng)絡(luò)的輸入或者輸出為一個四維的數(shù)組/Tensor。
- 一般為[batch_size, channel, height, width]
下面代碼目標(biāo)是輸出所有值為0的數(shù)字的索引。
output = [[ [[1, 0, 2], [2, 1, 0], [1, 0, 0]] ]] arr = np.array(output) print(arr.shape) res = np.where(arr==0) print(res)
Output
# print(arr.shape) (1, 1, 3, 3) # print(res) (array([0, 0, 0, 0], dtype=int64), array([0, 0, 0, 0], dtype=int64), array([0, 1, 2, 2], dtype=int64), array([1, 2, 1, 2], dtype=int64))
np.where的輸出結(jié)果為一個list,里面包含4個ndarray,分別代表四維。
[0, 0, 0, 0] # axis=0 [0, 0, 0, 0] # axis=1 [0, 1, 2, 2] # axis=2 [1, 2, 1, 2] # axis=3
正確讀值,從列來看,四個0值的索引分別是
print(arr[0][0][0][1]) # output:0 print(arr[0][0][1][2]) # output:0 print(arr[0][0][2][1]) # output:0 print(arr[0][0][2][2]) # output:0
np.where()用法解析
語法說明
np.where(condition,x,y)
- 當(dāng)where內(nèi)有三個參數(shù)時,第一個參數(shù)表示條件,當(dāng)條件成立時where方法返回x,當(dāng)條件不成立時where返回y
np.where(condition)
- 當(dāng)where內(nèi)只有一個參數(shù)時,那個參數(shù)表示條件,當(dāng)條件成立時,where返回的是每個符合condition條件元素的坐標(biāo),返回的是以元組的形式,坐標(biāo)以tuple的形式給出,通常原數(shù)組有多少維,輸出的tuple中就包含幾個數(shù)組,分別對應(yīng)符合條件元素的各維坐標(biāo)。
多條件condition
- -&表示與,|表示或。
- 如a = np.where((a>0)&(a<5), x, y),當(dāng)a>0與a<5滿足時,返回x的值,當(dāng)a>0與a<5不滿足時,返回y的值。
- 注意:x, y必須和a保持相同維度,數(shù)組的數(shù)值才能一一對應(yīng)。
示例
(1)一個參數(shù)
import numpy as np a = np.arange(0, 100, 10) b = np.where(a < 50) c = np.where(a >= 50)[0] print(a) print(b) print(c)
結(jié)果如下:
[ 0 10 20 30 40 50 60 70 80 90]
(array([0, 1, 2, 3, 4]),)
[5 6 7 8 9]
說明:
- b是符合小于50條件的元素位置,b的數(shù)據(jù)類型是tuple
- c是符合大于等于50條件的元素位置,c的數(shù)據(jù)類型是numpy.ndarray
(2)三個參數(shù)
a = np.arange(10) b = np.arange(0,100,10) print(np.where(a > 5, 1, -1)) print(b) print(np.where((a>3) & (a<8),a,b)) c=np.where((a<3) | (a>8),a,b) print(c)
結(jié)果如下:
[-1 -1 -1 -1 -1 -1 1 1 1 1]
[ 0 10 20 30 40 50 60 70 80 90]
[ 0 10 20 30 4 5 6 7 80 90]
[ 0 1 2 30 40 50 60 70 80 9]
說明:
- np.where(a > 5, 1, -1) ,滿足條件是1,不滿足是-1
- np.where((a>3) & (a<8),a,b),滿足條件是a ,不滿足是b ,a和b的維度相同
注意:
& | 與和或,每個條件一定要用括號,否則報錯
c=np.where((a<3 | a>8),a,b)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python列表推導(dǎo)式實現(xiàn)找出列表中長度大于5的名字
這篇文章主要介紹了python列表推導(dǎo)式實現(xiàn)找出列表中長度大于5的名字,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02Python如何獲取Win7,Win10系統(tǒng)縮放大小
這篇文章主要介紹了Python如何獲取Win7,Win10系統(tǒng)縮放大小,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-01-01Python的Matplotlib庫應(yīng)用實例超詳細教程
這篇文章主要介紹了Python的Matplotlib庫應(yīng)用的相關(guān)資料,Matplotlib是一個強大的Python數(shù)據(jù)可視化庫,支持繪制2D和3D圖像,它提供了簡單易用的API,廣泛應(yīng)用于數(shù)據(jù)分析和科學(xué)研究,需要的朋友可以參考下2025-01-01python數(shù)據(jù)可視化Seaborn畫熱力圖
這篇文章主要介紹了數(shù)據(jù)可視化Seaborn畫熱力圖,熱力圖的想法其實很簡單,用顏色替換數(shù)字,下面我們來看看文章對操作過程的具體介紹吧,需要的小伙伴可以參考一下具體內(nèi)容,希望對你有所幫助2022-01-01