温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Pytorch如何使用shuffle打乱数据的操作

发布时间:2021-05-21 09:53:29 来源:亿速云 阅读:698 作者:小新 栏目:开发技术

这篇文章主要介绍Pytorch如何使用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]

pytorch的优点

1.PyTorch是相当简洁且高效快速的框架;2.设计追求最少的封装;3.设计符合人类思维,它让用户尽可能地专注于实现自己的想法;4.与google的Tensorflow类似,FAIR的支持足以确保PyTorch获得持续的开发更新;5.PyTorch作者亲自维护的论坛 供用户交流和求教问题6.入门简单

以上是“Pytorch如何使用shuffle打乱数据的操作”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI