[PyTorch] dataloader使用教程

cv中的dataloader使用

加載頭文件

from torch.utils.data import DataLoader, Sampler
from torchvision import datasets,transforms

transforms表示對(duì)圖片的預(yù)處理方式

data_transform={'train':transforms.Compose([
                    # transforms.RandomResizedCrop(image_size),
                    # transforms.Resize(224),
                    transforms.RandomResizedCrop(int(image_size*1.2)),
                    # transforms.ToPILImage(),
                    transforms.RandomAffine(15),
                    # transforms.RandomHorizontalFlip(),
                    transforms.RandomVerticalFlip(),
                    transforms.RandomRotation(10),
                    transforms.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
                    transforms.RandomGrayscale(),
                    transforms.TenCrop(image_size),
                    transforms.Lambda(lambda crops: torch.stack([transforms.ToTensor()(crop) for crop in crops])),
                    transforms.Lambda(lambda crops: torch.stack([transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])(crop) for crop in crops])),
                   
                    # transforms.FiveCop(image_size),
                    # Lambda(lambda crops: torch.stack([transfoms.ToTensor()(crop) for crop in crops])),
                    # transforms.ToTensor(),
                    # transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
                    ]),
                "val":transforms.Compose([
                    transforms.Resize(image_size),
                    transforms.CenterCrop(image_size),
                    transforms.ToTensor(),
                    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
                ]),
                "test":transforms.Compose([
                    transforms.Resize(image_size),
                    transforms.CenterCrop(image_size),
                    transforms.ToTensor(),
                    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
                ])}

使用datasets.ImageFolder加載圖片數(shù)據(jù)

image_datasets={name:datasets.ImageFolder(os.path.join(rootpath,name),data_transform[name]) for name in ['train','val','test']}

生成dataloader

dataloaders={name : torch.utils.data.DataLoader(image_datasets[name],batch_size=batch_size,shuffle=True) for name in ['train','val']}
testDataloader=torch.utils.data.DataLoader(image_datasets['test'],batch_size=1,shuffle=False)

使用方法簸淀,每次會(huì)讀出一個(gè)batch_size的數(shù)據(jù)绕娘。

for index,item in enumerate(dataloaders['train'])

nlp中的dataloader的使用

torch.utils.data.DataLoader中的參數(shù):

  • dataset (Dataset) – dataset from which to load the data.
  • batch_size (int, optional) – how many samples per batch to load (default: 1).
  • shuffle (bool, optional) – set to True to have the data reshuffled at every epoch (default: False).
  • sampler (Sampler, optional) – defines the strategy to draw samples from the dataset. If specified, shuffle must be False.
  • batch_sampler (Sampler, optional) – like sampler, but returns a batch of indices at a time. Mutually exclusive with batch_size, shuffle, sampler, and drop_last.
  • num_workers (int, optional) – how many subprocesses to use for data loading. 0 means that the data will be loaded in the main process. (default: 0)
  • collate_fn (callable*, *optional) – merges a list of samples to form a mini-batch.
  • pin_memory (bool, optional) – If True, the data loader will copy tensors into CUDA pinned memory before returning them.
  • drop_last (bool, optional) – set to True to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If False and the size of dataset is not divisible by the batch size, then the last batch will be smaller. (default: False)
  • timeout (numeric, optional) – if positive, the timeout value for collecting a batch from workers. Should always be non-negative. (default: 0)
  • worker_init_fn (callable, 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)

需要自己構(gòu)造的兩個(gè)東西

Dataloader的處理邏輯是先通過Dataset類里面的 __getitem__ 函數(shù)獲取單個(gè)的數(shù)據(jù)锯七,然后組合成batch,再使用collate_fn所指定的函數(shù)對(duì)這個(gè)batch做一些操作翩伪,比如padding啊之類的微猖。

NLP中的使用主要是要重構(gòu)兩個(gè)兩個(gè)東西,一個(gè)是dataset,必須繼承自torch.utils.data.Dataset,內(nèi)部要實(shí)現(xiàn)兩個(gè)函數(shù)一個(gè)是__lent__用來(lái)獲取整個(gè)數(shù)據(jù)集的大小缘屹,一個(gè)是__getitem__用來(lái)從數(shù)據(jù)集中得到一個(gè)數(shù)據(jù)片段item凛剥。

class Dataset(torch.utils.data.Dataset):
    def __init__(self, filepath=None,dataLen=None):
        self.file = filepath
        self.dataLen = dataLen
        
    def __getitem__(self, index):
        A,B,path,hop= linecache.getline(self.file, index+1).split('\t')
        return A,B,path.split(' '),int(hop)

    def __len__(self):
        return self.dataLen

因?yàn)?code>dataloader是有batch_size參數(shù)的,我們可以通過自定義collate_fn=myfunction來(lái)設(shè)計(jì)數(shù)據(jù)收集的方式轻姿,意思是已經(jīng)通過上面的Dataset類中的__getitem__函數(shù)采樣了batch_size數(shù)據(jù)犁珠,以一個(gè)包的形式傳遞給collate_fn所指定的函數(shù)逻炊。

def myfunction(data):
    A,B,path,hop=zip(*data)
    print('A:',A," B:",B," path:",path," hop:",hop)
    raise Exception('utils collate_fun 147')
    return A,B,path,hop
for index,item in enumerate(dataloaders['train'])
    A,B,path.hop=item

進(jìn)行了解包

nlp任務(wù)中,經(jīng)常在collate_fn指定的函數(shù)里面做padding犁享,就是將在同一個(gè)batch中不一樣長(zhǎng)的句子padding成一樣長(zhǎng)余素。

def myfunction(data):
    src, tgt, original_src, original_tgt = zip(*data)

    src_len = [len(s) for s in src]
    src_pad = torch.zeros(len(src), max(src_len)).long()
    for i, s in enumerate(src):
        end = src_len[i]
        src_pad[i, :end] = torch.LongTensor(s[end-1::-1])

    tgt_len = [len(s) for s in tgt]
    tgt_pad = torch.zeros(len(tgt), max(tgt_len)).long()
    for i, s in enumerate(tgt):
        end = tgt_len[i]
        tgt_pad[i, :end] = torch.LongTensor(s)[:end]

    return src_pad, tgt_pad, \
           torch.LongTensor(src_len), torch.LongTensor(tgt_len), \
           original_src, original_tgt

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市炊昆,隨后出現(xiàn)的幾起案子桨吊,更是在濱河造成了極大的恐慌,老刑警劉巖凤巨,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件视乐,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡磅甩,警方通過查閱死者的電腦和手機(jī)炊林,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)卷要,“玉大人渣聚,你說我怎么就攤上這事∩妫” “怎么了奕枝?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)瓶堕。 經(jīng)常有香客問我隘道,道長(zhǎng),這世上最難降的妖魔是什么郎笆? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任谭梗,我火速辦了婚禮,結(jié)果婚禮上宛蚓,老公的妹妹穿的比我還像新娘激捏。我一直安慰自己,他們只是感情好凄吏,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布远舅。 她就那樣靜靜地躺著,像睡著了一般痕钢。 火紅的嫁衣襯著肌膚如雪图柏。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天任连,我揣著相機(jī)與錄音蚤吹,去河邊找鬼。 笑死随抠,一個(gè)胖子當(dāng)著我的面吹牛距辆,可吹牛的內(nèi)容都是我干的余佃。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼跨算,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼爆土!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起诸蚕,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤步势,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后背犯,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體坏瘩,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年漠魏,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了倔矾。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡柱锹,死狀恐怖哪自,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情禁熏,我是刑警寧澤壤巷,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站瞧毙,受9級(jí)特大地震影響胧华,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜宙彪,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一矩动、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧释漆,春花似錦悲没、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)柑潦。三九已至享言,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間渗鬼,已是汗流浹背览露。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留譬胎,地道東北人差牛。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓命锄,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親偏化。 傳聞我的和親對(duì)象是個(gè)殘疾皇子脐恩,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容