簡體   English   中英

append 使用與另一個 ndarray 索引匹配的索引到列表的第 i 個值

[英]append ith value to a list using index that matches another ndarray index

我正在嘗試對 cifar100 數據集進行子采樣,以對每個超類的一個子類進行訓練和測試。 我進行了設置,以便如果 y_full 中的值(每個圖像的子類 label)與我想要的子類列表匹配,則該元素的索引用於從 X_full(圖像)中獲取具有相同索引的值.

到目前為止,這是我的代碼:

from sklearn.model_selection import train_test_split
cifar100 = keras.datasets.cifar100
(X_full, y_full), (X_test_full, y_test_full) = cifar100.load_data(label_mode="fine")

classes = [0,1,2,3,4,5,6,8,9,12,15,22,23,26,27,34,36,41,47,54]

X_tr_full = []
y_tr_full = []
X_test = []
y_test = []

for i in y_full:
  if i in classes:
    X_tr_full.append(X_full[np.where(y_full==i)])
    y_tr_full.append(i)

for i in y_test_full:
  if i in classes:
    X_test.append(X_test_full[np.where(y_test_full==i)])
    y_test.append(i)

我的代碼的問題在於np.where(y_full==i) 這會發回 y_full 中所有索引的元組,其值與我的列表中的 class 匹配,然后將來自 X_full 的所有圖像與這些索引添加到一個條目中。 Instead I want to iterate through the entirety of y_full, if the class label matches my class list, I want the index of that element to be used to append the value from X_full with that same index for every value in y_full. 抱歉,如果我不夠清楚,很難解釋我要做什么,但希望有人能提供幫助!

我想我明白了。 一旦我弄清楚如何將每個索引彼此分開調用,這非常簡單:

for n in range(y_full.size):
  if y_full[n] in classes:
    X_tr_full.append(X_full[n])
for i in y_full:
  if i in classes:
    y_tr_full.append(i)

for n in range(y_test_full.size):
  if y_test_full[n] in classes:
    X_test.append(X_test_full[n])
for i in y_test_full:
  if i in classes:
    y_test.append(i)

為了說明我的評論,我將使用一個簡單的模數測試示例

In [224]: arr = np.arange(10); alist = []
In [225]: for i in [2,3]:
     ...:     alist.append(arr[arr%i>0])
     ...:     
In [226]: alist
Out[226]: [array([1, 3, 5, 7, 9]), array([1, 2, 4, 5, 7, 8])]

我得到一個 arrays 的列表,它可以加入一個數組:

In [227]: np.hstack(alist)
Out[227]: array([1, 3, 5, 7, 9, 1, 2, 4, 5, 7, 8])

或者使用extend

In [228]: arr = np.arange(10); alist = []    
In [229]: for i in [2,3]:
     ...:     alist.extend(arr[arr%i>0])
     ...:         
In [230]: alist
Out[230]: [1, 3, 5, 7, 9, 1, 2, 4, 5, 7, 8]    
In [231]: np.array(alist)
Out[231]: array([1, 3, 5, 7, 9, 1, 2, 4, 5, 7, 8])

extend替換您的迭代append

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM