pytorch 样本随机采样

前言:

        在训练的时候,都需要对样本进行随机采样。

# -*- coding: utf-8 -*-
"""
Created on Mon Nov 14 09:49:07 2022

@author: chengxf2
"""
from  torch.utils.data import Dataset, DataLoader
import torch

#需要继承data.Dataset
class MyDataset(Dataset):
    
    
    def __init__(self, data, target):
        
        self.x = data
        self.y = target
        self.len = self.x.shape[0] #样本个数
        
    
    def __getitem__(self, index):
        
         x = self.x[index]
         y = self.y[index]
         return x,y
    
    
    def __len__(self):
        
        return self.len

    
def  sample(data, label):
    
    
    mydata = MyDataset(data,label)
    train_loader = DataLoader(dataset = mydata, batch_size =6, shuffle = True,drop_last =True)

    max_iter =6
    for epoch in range(max_iter):
        for step, (batch_x, batch_y) in enumerate(train_loader):  
            print('Epoch: ', epoch, '| Step:', step, '\n batch x:\n ', batch_x.numpy(), '\n| batch y:', batch_y.numpy())
            

if __name__ == "__main__":
    
    xList =[[1,0],[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[1,8],[1,9]]
    yList = [0,1,2,3,4,5,6,7,8,9]
    x = torch.tensor(xList,dtype= torch.float)
    y = torch.tensor(yList,dtype= torch.float)
    
    sample(x,y)

  

你可能感兴趣的:(人工智能,pytorch,深度学习,python)