這個東西算是我被這個shuffle坑了的一個總結吧!
首先我得告訴你一件事,那就是pytorch中的tensor,如果直接使用random.shuffle打亂數據,或者使用下面的方式,自己定義直接寫。
1
2
3
4
5
6
7
8
9
|
def Shuffle( self , x, y,random = None , int = int ): if random is None : random = self .random for i in range ( len (x)): j = int (random() * (i + 1 )) if j< = len (x) - 1 : x[i],x[j] = x[j],x[i] y[i],y[j] = y[j],y[i] retrun x,y |
那你就會收獲一堆的混亂數據,因為使用這種交換的方式對tensor類型的數據進行操作,會導致里面的數據出現重復復制的問題。
比如我y中的數據為【0,1,0,1,0,1】
在經過幾次shuffle,其中的數據就變成了【1,1,1,1,1,1】。
數據頓時出現混亂。
正確的方式是先轉成numpy,再進行交換數據
比如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
def Shuffle( self , x, y,random = None , int = int ): """x, random=random.random -> shuffle list x in place; return None. Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the standard random.random. """ if random is None : random = self .random #random=random.random #轉成numpy if torch.is_tensor(x) = = True : if self .use_cuda = = True : x = x.cpu().numpy() else : x = x.numpy() if torch.is_tensor(y) = = True : if self .use_cuda = = True : y = y.cpu().numpy() else : y = y.numpy() #開始隨機置換 for i in range ( len (x)): j = int (random() * (i + 1 )) if j< = len (x) - 1 : #交換 x[i],x[j] = x[j],x[i] y[i],y[j] = y[j],y[i] #轉回tensor if self .use_cuda = = True : x = torch.from_numpy(x).cuda() y = torch.from_numpy(y).cuda() else : x = torch.from_numpy(x) y = torch.from_numpy(y) return x,y |
補充:python對訓練數據集shuffle(打亂)的一些方式
1.通過數組來shuffle
1
2
3
4
5
6
7
8
9
|
image_list = [] # list of images label_list = [] # list of labels temp = np.array([image_list, label_list]) temp = temp.transpose() np.random.shuffle(temp) images = temp[:, 0 ] # array of images (N,) labels = temp[:, 1 ] |
2.通過索引 Index 來 shuffle
1
2
3
4
5
6
7
8
9
10
11
12
|
image_list = [] # list of images label_list = [] # list of labels ##如果image_list存的是讀取的特征數據,而不是圖片路徑,不要注釋后面兩句(list無法索引內部list) #[list indices must be integers or slices, not list] #image_list = np.array(image_list) #label_list = np.array(label_list) index = [i for i in range ( len (image_list))] np.random.shuffle(index) images = image_list[index] labels = label_list[index] |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_41487299/article/details/107424432