日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

PyTorch系列 (二): pytorch数据读取自制数据集并

發(fā)布時間:2025/3/11 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 PyTorch系列 (二): pytorch数据读取自制数据集并 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

PyTorch系列 (二): pytorch數(shù)據(jù)讀取

PyTorch 1: How to use data in pytorch

Posted by WangW on February 1, 2019

參考:

  • PyTorch documentation
  • PyTorch 碼源
  • 本文首先介紹了有關預處理包的源碼,接著介紹了在數(shù)據(jù)處理中的具體應用;

    1 PyTorch數(shù)據(jù)預處理以及源碼分析 (torch.utils.data)

    torch.utils.data腳本碼源

    1.1 Dataset

    Dataset

    1 class torch.utils.data.Dataset

    表示Dataset的抽象類。所有其他數(shù)據(jù)集都應該進行子類化。?所有子類應該override__len__和__getitem__,前者提供了數(shù)據(jù)集的大小,后者支持整數(shù)索引,范圍從0到len(self)。

    1 2 3 4 5 6 7 8 9 10 11 12 class Dataset(object):# 強制所有的子類override getitem和len兩個函數(shù),否則就拋出錯誤;# 輸入數(shù)據(jù)索引,輸出為索引指向的數(shù)據(jù)以及標簽;def __getitem__(self, index):raise NotImplementedError# 輸出數(shù)據(jù)的長度def __len__(self):raise NotImplementedErrordef __add__(self, other):return ConcatDataset([self, other])

    TensorDataset

    1 class torch.utils.data.TensorDataset(*tensors)

    Dataset的子類。包裝tensors數(shù)據(jù)集;輸入輸出都是元組; 通過沿著第一個維度索引一個張量來回復每個樣本。 個人感覺比較適用于數(shù)字類型的數(shù)據(jù)集,比如線性回歸等。

    1 2 3 4 5 6 7 8 9 10 class TensorDataset(Dataset):def __init__(self, *tensor):assert all(tensors[0].size(0) == tensor.size(0) for tensor in tensors)self.tensors = tensorsdef __getitem__(self, index):return tuple(tensor[index] for tensor in tensorsdef __len__(self):return self.tensors[0].size(0)

    ConcatDateset

    1 class torch.utils.data.ConcatDateset(datasets)

    連接多個數(shù)據(jù)集。 目的:組合不同的數(shù)據(jù)集,可能是大規(guī)模數(shù)據(jù)集,因為連續(xù)操作是隨意連接的。 datasets的參數(shù):要連接的數(shù)據(jù)集列表 datasets的樣式:iterable

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class ConcatDataset(Dataset):@staticmethoddef cumsum(sequence):# sequence是一個列表,e.g. [[1,2,3], [a,b], [4,h]]# return 一個數(shù)據(jù)大小列表,[3, 5, 7], 明顯看的出來包含數(shù)據(jù)多少,第一個代表第一個數(shù)據(jù)的大小,第二個代表第一個+第二數(shù)據(jù)的大小,最后代表所有的數(shù)據(jù)大學;...def __getitem__(self, idx):# 主要是這個函數(shù),通過bisect的類實現(xiàn)了任意索引數(shù)據(jù)的輸出;dataset_idx = bisect.bisect_right(self.cumulative_size, idx)if dataset_idx == 0:sample_idx == idxelse:sample_idx = idx - self.cumulative_sizes[dataset_idx -1]return self.datasets[dataset_idx][sample_idx]...

    Subset

    1 class torch.utils.data.Subset(dataset, indices)

    選取特殊索引下的數(shù)據(jù)子集; dataset:數(shù)據(jù)集; indices:想要選取的數(shù)據(jù)的索引;

    random_split

    1 class torch.utils.data.random_split(dataset, lengths):

    隨機不重復分割數(shù)據(jù)集; dataset:要被分割的數(shù)據(jù)集 lengths:長度列表,e.g. [7, 3],?保證7+3=len(dataset)

    1.2 DataLoader

    DataLoader

    1 class torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_workers=0, collate_fn=<function default_collate>, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None)

    數(shù)據(jù)加載器。 組合數(shù)據(jù)集和采樣器,并在數(shù)據(jù)集上提供單進程或多進程迭代器。 參數(shù):

    • dataset (Dataset) - 從中加載數(shù)據(jù)的數(shù)據(jù)集。
    • batch_size (int, optional) - 批訓練的數(shù)據(jù)個數(shù)。
    • shuffle (bool, optional) - 是否打亂數(shù)據(jù)集(一般打亂較好)。
    • sampler (Sampler, optional) - 定義從數(shù)據(jù)集中提取樣本的策略。如果指定,則忽略shuffle參數(shù)。
    • batch_sampler (Sample, optional) - 和sampler類似,返回批中的索引。
    • num_workers (int, optional) - 用于數(shù)據(jù)加載的子進程數(shù)。
    • collate_fn (callable, optional) - 合并樣本列表以形成小批量。
    • pin_memory (bool, optional) - 如果為True,數(shù)據(jù)加載器在返回去將張量復制到CUDA固定內(nèi)存中。
    • drop_last (bool, optional) - 如果數(shù)據(jù)集大小不能被batch_size整除, 設置為True可以刪除最后一個不完整的批處理。
    • timeout (numeric, optional) - 正數(shù),收集數(shù)據(jù)的超時值。
    • worker_init_fn (callabel, optional) - If not?None, this will be called on each worker subprocess with the worker id (an int in?[0, num_workers - 1]) as input, after seeding and before data loading. (default:?None)

    特別重要:DataLoader中是不斷調(diào)用DataLoaderIter

    DataLoaderIter

    1 class _DataLoaderIter(loader)

    從DataLoader’s數(shù)據(jù)中迭代一次。其上面DataLoader功能都在這里;?插個眼,有空在分析這個

    1.3 sampler

    Sampler

    1 class torch.utils.data.sampler.Sampler(data_source)

    所有采樣器的基礎類; 每個采樣器子類必須提供一個__iter__方法,提供一種迭代數(shù)據(jù)集元素的索引的方法,以及返回迭代器長度__len__方法。

    class Sampler(object):def __init__(self, data_source):passdef __iter__(self):raise NotImplementedErrordef __len__(self):raise NotImplementedError
    ??

    SequentialSampler

    1 class torch.utils.data.SequentialSampler(data_source)

    樣本元素順序排列,始終以相同的順序。?參數(shù):-data_source (Dataset) - 采樣的數(shù)據(jù)

    RandomSampler

    1 class torch.utils.data.RandomSampler(data_source, replacement=False, num_samples=None)

    樣本隨機排列,如果沒有Replacement,將會從打亂的數(shù)據(jù)采樣,否則,。。?參數(shù):

    • data_source (Dataset) - 采樣數(shù)據(jù)
    • num_samples (int) - 采樣數(shù)據(jù)大小,默認是全部。
    • replacement (bool) - 是否放回

    SubsetRandomSampler

    1 class torch.utils.data.SubsetRandomSampler(indices)

    從給出的索引中隨機采樣,without replacement。?參數(shù):

    • indices (sequence) - 索引序列。

    BatchSampler

    1 class torch.utils.data.BatchSampler(sampler, batch_size, drop_last)

    將采樣封裝到批處理索引。?參數(shù):

    • sampler (sampler) - 基本采樣
    • batch_size (int) - 批大小
    • drop_last (bool) - 是否刪掉最后的批次

    weightedRandomSampler

    1 class torch.utils.data.WeightedRandomSampler(weights, num_samples, replacement=True)

    樣本元素來自[0,…,len(weights)-1], 給定概率(權重)。?參數(shù):

    • weights (list) - 權重列表。不需要加起來為1
    • num_samplers (int) - 要采樣數(shù)目
    • replacement (bool) -

    1.4 Distributed

    DistributedSampler

    1 class torch.utils.data.distributed.DistributedSampler(dataset, num_replicas=None, rank=None)

    ????沒讀呢

    1.5 其它鏈接

  • PyTorch源碼解讀之torch.utils.data.DataLoader
  • 2 torchvision

    計算機視覺用到的庫,文檔以及碼源如下:

  • torchvision documentation
  • torchvision?其庫主要包含一下內(nèi)容:
    • torchvision.datasets
      • MNIST
      • Fashion-MNIST
      • EMNIST
      • COCO
      • LSUN
      • ImageFolder
      • DatasetFolder
      • Imagenet-12
      • CIFAR
      • STL10
      • SVHN
      • Photo Tour
      • SBU
      • Flickr
      • VOC
    • torchvision.models
      • Alexnet
      • VGG
      • ResNet
      • SqueezeNet
      • DenseNet
      • Inception v3
    • torchvision.transforms
      • Transforms on PIL Image
      • Transfroms on torch.* Tensor
      • Conversion Transforms
      • Generic Transforms
      • Functional Transforms
    • torchvision.utils

    3 應用

    3.1 init

    具有一下圖像數(shù)據(jù)如下表示:

    • train
      • normal
        • 1.png
        • 2.png
        • 8000.png
      • tumor
        • 1.png
        • 2.png
        • 8000.png
    • validation
      • normal
        • 1.png
      • tumor
        • 1.png

    希望能夠訓練模型,使得能夠識別tumor, normal兩類,將tumor–>1, normal–>0。

    3.2 數(shù)據(jù)讀取

    在PyTorch中數(shù)據(jù)的讀取借口需要經(jīng)過,Dataset和DatasetLoader (DatasetloaderIter)。下面就此分別介紹。

    Dataset

    首先導入必要的包。

    import osimport numpy as np from torch.utils.data import Dataset from PIL import Imagenp.random.seed(0)
    ??

    其次定義MyDataset類,為了代碼整潔精簡,將不必要的操作全刪,e.g. 圖像剪切等。

    class MyDataset(Dataset):def __init__(self, root, size=229, ):"""Initialize the data producer"""self._root = rootself._size = sizeself._num_image = len(os.listdir(root))self._img_name = os.listdir(root)def __len__(self):return self._num_imagedef __getitem__(self, index):img = Image.open(os.path.join(self._root, self._img_name[index]))# PIF image: H × W × C# torch image: C × H × Wimg = np.array(img, dtype-np.float32).transpose((2, 0, 1))return img
    ??

    DataLoader

    將MyDataset封裝到loader器中。

    from torch.utils.data import DataLoader# 實例化MyData dataset_tumor_train = MyDataset(root=/img/train/tumor/) dataset_normal_train = MyDataset(root=/img/train/normal/) dataset_tumor_validation = MyDataset(root=/img/validation/tumor/) dataset_normal_validation = MyDataset(root=/img/validation/normal/)# 封裝到loader dataloader_tumor_train = DataLoader(dataset_tumor_train, batch_size=10) dataloader_normal_train = DataLoader(dataset_normal_train, batch_size=10) dataloader_tumor_validation = DataLoader(dataset_tumor_validation, batch_size=10) dataloader_normal_validation = DataLoader(dataset_normal_validation, batch_size=10)
    ??

    3.3 train_epoch

    簡單將數(shù)據(jù)流接口與訓練連接起來

    def train_epoch(model, loss_fn, optimizer, dataloader_tumor, dataloader_normal):model.train()# 由于tumor圖像和normal圖像一樣多,所以將tumor,normal連接起來,steps=len(tumor_loader)=len(normal_loader)steps = len(dataloader_tumor)batch_size = dataloader_tumor.batch_sizedataiter_tumor = iter(dataloader_tumor)dataiter_normal = iter(dataloader_normal)for step in range(steps):data_tumor = next(dataiter_tumor)target_tumor = [1, 1,..,1] # 和data_tumor長度相同的tensordata_tumor = Variable(data_tumor.cuda(async=True))target_tumor = Variable(target_tumor.cuda(async=True))data_normal = next(dataiter_normal)target_normal = [0, 0,..,0] # data_normal = Variable(data_normal.cuda(async=True))target_normal = Variable(target_normal.cuda(async=True))idx_rand = Variable(torch.randperm(batch_size*2).cuda(async=True))data = torch.cat([data_tumor, data_normal])[idx_rand]target = torch.cat([target_tumor, target_normal])[idx_rand]output = model(data)loss = loss_fn(output, target)optimizer.zero_grad()loss.backward()optimizer.step()
    ??

    總結

    以上是生活随笔為你收集整理的PyTorch系列 (二): pytorch数据读取自制数据集并的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。