Python—numpy.flatnonzero()


numpy.flatnonzero():

  該函數輸入一個矩陣,返回扁平化后矩陣中非零元素的位置(index)

這是官方文檔給出的用法,非常正規,輸入一個矩陣,返回了其中非零元素的位置.

1 >>> x = np.arange(-2, 3)
2 >>> x
3 array([-2, -1,  0,  1,  2])
4 >>> np.flatnonzero(x)
5 array([0, 1, 3, 4])
import numpy as np
d = np.array([1,2,3,4,4,3,5,3,6])
haa = np.flatnonzero(d == 3)
print (haa)

[2 5 7]

 

對向量元素的判斷d==3返回了一個和向量等長的由0/1組成的矩陣,然后調用函數,返回的位置,就是對應要找的元素的位置。

# Visualize some examples from the dataset.
# We show a few examples of training images from each class.
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] #類別列表
num_classes = len(classes) #類別數目
samples_per_class = 7 # 每個類別采樣個數
for y, cls in enumerate(classes): # 對列表的元素位置和元素進行循環,y表示元素位置(0,num_class),cls元素本身'plane'等
    idxs = np.flatnonzero(y_train == y) #找出標簽中y類的位置
    idxs = np.random.choice(idxs, samples_per_class, replace=False) #從中選出我們所需的7個樣本
    for i, idx in enumerate(idxs): #對所選的樣本的位置和樣本所對應的圖片在訓練集中的位置進行循環
        plt_idx = i * num_classes + y + 1 # 在子圖中所占位置的計算
        plt.subplot(samples_per_class, num_classes, plt_idx) # 說明要畫的子圖的編號
        plt.imshow(X_train[idx].astype('uint8')) # 畫圖
        plt.axis('off')
        if i == 0:
            plt.title(cls) # 寫上標題,也就是類別名
plt.show() # 顯示

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM