一、Dataset、DataLoader介绍及使用
代码所用数据集:https://pan.baidu.com/s/16ac0Z97Za-nmwDD90EaUGw 提取码:160h
from torch.utils.data import Dataset, DataLoaderpath = r"C:\Users\Administrator\PycharmProjects\pythonProject\data\SMSSpamCollection"# 构建数据集类
class MyDataset(Dataset):def __init__(self):self.lines = open(path, encoding='utf-8').readlines()def __getitem__(self, index):cur_line = self.lines[index].strip()label = cur_line[:4].strip()return cur_line, labeldef __len__(self):return len(self.lines)my_dataset = MyDataset()
# 使用数据加载器类:用来
# 批处理数据、打乱数据、使用多线程并行加载数据
data_load = DataLoader(dataset=my_dataset, batch_size=3, shuffle=True, drop_last=True)if __name__ == '__main__':for index, i in enumerate(data_load):print(index, i)breakprint(len(my_dataset)) # 5574print(len(data_load)) # 1858# data_load除不断时,向上取整# 如果data_load的长度不是batch_size,那么drop_last=True时,可以将最后一个batch删除
二、pytorch自带数据集介绍
pytorch中自带数据集由两个API提供分别是:torchvision、torchtext
- torchvision.datasets
- torchtext.datasets
from torch.utils.data import DataLoader
from torchvision.datasets import MNISTmnist = MNIST(root='./data', train=True, download=True)
DataLoader(dataset=mnist, batch_size=256, shuffle=True)
print(mnist[0])