最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

np.where在多維數(shù)組的應(yīng)用方式

 更新時(shí)間:2024年02月02日 16:29:15   作者:Alex-Leung  
這篇文章主要介紹了np.where在多維數(shù)組的應(yīng)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

np.where在多維數(shù)組的應(yīng)用

函數(shù)用途

返回查找的參數(shù),在數(shù)組中的索引。

Code

舉例:

  • 一般卷積神經(jīng)網(wǎng)絡(luò)的輸入或者輸出為一個(gè)四維的數(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é)果為一個(gè)list,里面包含4個(gè)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

正確讀值,從列來(lái)看,四個(gè)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()用法解析

語(yǔ)法說(shuō)明

np.where(condition,x,y)

  • 當(dāng)where內(nèi)有三個(gè)參數(shù)時(shí),第一個(gè)參數(shù)表示條件,當(dāng)條件成立時(shí)where方法返回x,當(dāng)條件不成立時(shí)where返回y

np.where(condition)

  • 當(dāng)where內(nèi)只有一個(gè)參數(shù)時(shí),那個(gè)參數(shù)表示條件,當(dāng)條件成立時(shí),where返回的是每個(gè)符合condition條件元素的坐標(biāo),返回的是以元組的形式,坐標(biāo)以tuple的形式給出,通常原數(shù)組有多少維,輸出的tuple中就包含幾個(gè)數(shù)組,分別對(duì)應(yīng)符合條件元素的各維坐標(biāo)。

多條件condition

  • -&表示與,|表示或。
  • 如a = np.where((a>0)&(a<5), x, y),當(dāng)a>0與a<5滿足時(shí),返回x的值,當(dāng)a>0與a<5不滿足時(shí),返回y的值。
  • 注意:x, y必須和a保持相同維度,數(shù)組的數(shù)值才能一一對(duì)應(yīng)。

示例

(1)一個(gè)參數(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]

說(shuō)明:

  • b是符合小于50條件的元素位置,b的數(shù)據(jù)類型是tuple
  • c是符合大于等于50條件的元素位置,c的數(shù)據(jù)類型是numpy.ndarray

(2)三個(gè)參數(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]

說(shuō)明:

  • np.where(a > 5, 1, -1) ,滿足條件是1,不滿足是-1
  • np.where((a>3) & (a<8),a,b),滿足條件是a ,不滿足是b ,a和b的維度相同

注意:

& | 與和或,每個(gè)條件一定要用括號(hào),否則報(bào)錯(cuò)

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

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

甘孜县| 桂林市| 德昌县| 龙口市| 侯马市| 屯昌县| 凤庆县| 鹰潭市| 黎川县| 察哈| 台安县| 柘荣县| 洪雅县| 安吉县| 嵊州市| 穆棱市| 迁安市| 莎车县| 永仁县| 广水市| 临沭县| 阜宁县| 阳原县| 赤水市| 巩义市| 平度市| 彩票| 曲松县| 师宗县| 聂荣县| 娄底市| 徐汇区| 米脂县| 崇义县| 台南市| 泗水县| 北辰区| 于都县| 荣昌县| 彭泽县| 安陆市|