Pytorch使用shuffle打乱数据的操作
这个东西算是我被这个shuffle坑了的一个总结吧!
首先我得告诉你一件事,那就是pytorch中的tensor,如果直接使用random.shuffle打乱数据,或者使用下面的方式,自己定义直接写。
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,再进行交换数据
比如:
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
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存的是读取的特征数据,而不是图片路径,不要注释后面两句(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]
(资源库 www.zyku.net)
原文链接:https://blog.csdn.net/qq_41487299/article/details/107424432
您可能感兴趣的文章
- 02-08PyTorch梯度裁剪避免训练loss nan的操作
- 02-08我对PyTorch dataloader里的shuffle=True的理解
- 02-08浅谈pytorch中为什么要用 zero_grad() 将梯度清零
- 02-08pytorch DataLoader的num_workers参数与设置大小详解
- 02-08pytorch 带batch的tensor类型图像显示操作
- 02-08解决pytorch中的kl divergence计算问题
- 02-08pytorch 实现在测试的时候启用dropout
- 04-09使用pytorch实现线性回归
- 01-15小米12pro开启全局120HZ刷新率教程
- 02-07苹果12手机设置连拍功能教程
- 01-11花朵识别-花朵识别应用软件功能介绍
- 12-27HTML网页特殊符号代码大全
- 03-20oppofindx3pro连接打印机方法
- 07-07华为儿童手表加好友方法
- 04-24python的几种开发工具介绍
- 01-11一年级上册语文帮-一年级上册语文帮应
- 10-24微信读书阅读记录怎样删除
- 10-24ios15口罩解锁怎么开
- 12-09荣耀60模拟颜色空间在哪里关闭
- 12-23HTML <br> 标签
最近更新
阅读排行
猜你喜欢
- 02-28oppok9设置流量预警方法
- 09-27OPPOreno6怎么隐藏应用
- 01-14潜江停车-潜江停车应用软件功能介绍
- 03-19华为手环6取消久坐提醒设置方法
- 06-25天翼云
- 02-28WordPress后台发布文章,自定义栏目和字
- 11-17网易云音乐怎么修改个人状态
- 10-15华为nova7怎样开启应急预警通知
- 11-25红米手机如何取消纯净模式
- 02-06小米11赫兹刷新率调整方法