【问题标题】:How to split the data into training and testing data如何将数据拆分为训练和测试数据
【发布时间】:2020-08-02 23:01:27
【问题描述】:

嗨,现在我得到了数据加载代码,但我不确定如何将其拆分为训练和测试数据。谁能给我建议怎么做这是我的数据加载代码。

def __init__(self, root, specific_folder, img_extension, preprocessing_method=None, crop_size=(96, 112),train = True):
    """
    Dataloader of the LFW dataset.

    root: path to the dataset to be used.
    specific_folder: specific folder inside the same dataset.
    img_extension: extension of the dataset images.
    preprocessing_method: string with the name of the preprocessing method.
    crop_size: retrieval network specific crop size.
    """

    self.preprocessing_method = preprocessing_method
    self.crop_size = crop_size
    self.imgl_list = []
    self.classes = []
    self.people = []
    self.model_align = None
    self.arr = []

    # read the file with the names and the number of images of each people in the dataset
    with open(os.path.join(root, 'people.txt')) as f:
        people = f.read().splitlines()[1:]

    # get only the people that have more than 20 images
    for p in people:
        p = p.split('\t')
        if len(p) > 1:
            if int(p[1]) >= 20:
                for num_img in range(1, int(p[1]) + 1):
                    self.imgl_list.append(os.path.join(root, specific_folder, p[0], p[0] + '_' +
                                                       '{:04}'.format(num_img) + '.' + img_extension))
                    self.classes.append(p[0])
                    self.people.append(p[0])

    le = preprocessing.LabelEncoder()
    self.classes = le.fit_transform(self.classes)

    print(len(self.imgl_list), len(self.classes), len(self.people))

def __getitem__(self, index):
    imgl = imageio.imread(self.imgl_list[index])
    cl = self.classes[index]

    # if image is grayscale, transform into rgb by repeating the image 3 times
    if len(imgl.shape) == 2:
        imgl = np.stack([imgl] * 3, 2)

    imgl, bb = preprocess(imgl, self.preprocessing_method, crop_size=self.crop_size,
                          is_processing_dataset=True, return_only_largest_bb=True, execute_default=True)

    # append image with its reverse
    imglist = [imgl, imgl[:, ::-1, :]]

    # normalization
    for i in range(len(imglist)):
        imglist[i] = (imglist[i] - 127.5) / 128.0
        imglist[i] = imglist[i].transpose(2, 0, 1)
    imgs = [torch.from_numpy(i).float() for i in imglist]

    return imgs, cl, imgl, bb, self.imgl_list[index], self.people[index]

def __len__(self):
    return len(self.imgl_list)

我需要将其中的数据分成 20% 和 80% 的数据,这样我就可以测试我的模块了,现在已经快一周了,但仍然完全不知道该怎么做,如果有人能提供帮助,将不胜感激:

【问题讨论】:

  • 乍一看,我找不到保存您数据的变量,但您似乎正在使用 sklearn 的 fit_transform。你试过model_selection.train_test_split吗?拆分火车数据不仅仅是获取其中的一部分。您需要查看随机化、相互依赖和许多因素。尝试在stats.stackexchange.com中搜索
  • 您好,我尝试过,当我运行它时,程序会继续运行,永远不会停止,我不确定这是否会发生?

标签: python split datalist


【解决方案1】:

一般使用 PyTorch:

import torch
import numpy as np
from torchvision import datasets
from torchvision import transforms
from torch.utils.data.sampler import SubsetRandomSampler

dataset = yourdatahere
batch_size = 16 #change to whatever you'd like it to be
test_split = .2
shuffle_dataset = True
random_seed= 42

# Creating data indices for training and validation splits:
dataset_size = len(dataset)
indices = list(range(dataset_size))
split = int(np.floor(test_split * dataset_size))
if shuffle_dataset :
    np.random.seed(random_seed)
    np.random.shuffle(indices)
train_indices, test_indices = indices[split:], indices[:split]

# Creating PT data samplers and loaders:
train_sampler = SubsetRandomSampler(train_indices)
test_sampler = SubsetRandomSampler(test_indices)

train_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, 
                                           sampler=train_sampler)
test_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
                                                sampler=test_sampler)

# Usage Example:
num_epochs = 10
for epoch in range(num_epochs):
    # Train:   
    for batch_index, (faces, labels) in enumerate(train_loader):
        # ...

请注意,您还应该将训练数据拆分为训练 + 验证数据。您可以使用上述相同的逻辑来执行此操作。

【讨论】:

  • 还有一个问题,结果是数组形式还是不同的版本
  • 只是想知道是否可以让您检查我的培训模块并检查这看起来是否正常或我需要更改一些内容
  • 如果我不知道我的批量大小有没有办法检查它?对于很多问题,我对编码很抱歉
  • 批量大小是您选择的参数——通常,批量大小为 32 是一个很好的起点。另外,不用担心!
  • 所以现在我拥有的文件并不简单。我得到了每个人的文件夹,例如我得到了文件夹名称 bob,其中有 bob photo 和另一个文件夹名称 kevin,其中包含 kevin photo 你知道如何打开所有图像吗?
猜你喜欢
  • 2020-06-08
  • 1970-01-01
  • 2019-05-01
  • 2019-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多