人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動態(tài)

Pytorch使用shuffle打亂數(shù)據(jù)的操作

發(fā)布日期:2022-05-23 14:11 | 文章來源:CSDN

這個(gè)東西算是我被這個(gè)shuffle坑了的一個(gè)總結(jié)吧!

首先我得告訴你一件事,那就是pytorch中的tensor,如果直接使用random.shuffle打亂數(shù)據(jù),或者使用下面的方式,自己定義直接寫。

 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

那你就會收獲一堆的混亂數(shù)據(jù),因?yàn)槭褂眠@種交換的方式對tensor類型的數(shù)據(jù)進(jìn)行操作,會導(dǎo)致里面的數(shù)據(jù)出現(xiàn)重復(fù)復(fù)制的問題。

比如我y中的數(shù)據(jù)為【0,1,0,1,0,1】

在經(jīng)過幾次shuffle,其中的數(shù)據(jù)就變成了【1,1,1,1,1,1】。

數(shù)據(jù)頓時(shí)出現(xiàn)混亂。

正確的方式是先轉(zhuǎn)成numpy,再進(jìn)行交換數(shù)據(jù)

比如:

 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
  #轉(zhuǎn)成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()
  #開始隨機(jī)置換
  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]
  #轉(zhuǎn)回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

補(bǔ)充:python對訓(xùn)練數(shù)據(jù)集shuffle(打亂)的一些方式

1.通過數(shù)組來shuffle

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

image_list=[]  # list of images
label_list=[]  # list of labels
 
##如果image_list存的是讀取的特征數(shù)據(jù),而不是圖片路徑,不要注釋后面兩句(list無法索引內(nèi)部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]

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

海外服務(wù)器租用

版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時(shí)開通

自選配置、實(shí)時(shí)開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對1客戶咨詢顧問

在線
客服

在線客服:7*24小時(shí)在線

客服
熱線

400-630-3752
7*24小時(shí)客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部