99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁大數(shù)據(jù)時代pytorch如何加載不同尺寸的數(shù)據(jù)集?
pytorch如何加載不同尺寸的數(shù)據(jù)集?
2023-04-12
收藏

PyTorch是一個非常流行的深度學(xué)習(xí)框架,它提供了很多有用的工具和函數(shù)來幫助我們有效地構(gòu)建和訓(xùn)練神經(jīng)網(wǎng)絡(luò)。在實際的應(yīng)用中,我們通常需要處理不同尺寸的數(shù)據(jù)集,例如圖像數(shù)據(jù)集。本文將介紹如何使用PyTorch加載不同尺寸的數(shù)據(jù)集。

PyTorch中,我們通常使用DataLoader和Dataset兩個類來加載數(shù)據(jù)集。其中Dataset是對數(shù)據(jù)集進行抽象的類,而DataLoader是用于將Dataset對象轉(zhuǎn)換為可迭代的數(shù)據(jù)加載器的類。因此,在加載不同尺寸的數(shù)據(jù)集時,我們需要對這兩個類進行適當?shù)呐渲煤驼{(diào)整。

首先,讓我們看一下如何處理相同尺寸的數(shù)據(jù)集。假設(shè)我們有一個包含RGB圖像的數(shù)據(jù)集,每張圖像的大小都是224x224像素。我們可以創(chuàng)建一個自定義的Dataset類來讀取這些圖像,并將它們轉(zhuǎn)換為PyTorch張量:

import os
from PIL import Image
import torch.utils.data as data

class CustomDataset(data.Dataset):
    def __init__(self, data_dir):
        self.data_dir = data_dir
        self.img_list = os.listdir(data_dir)

    def __getitem__(self, index):
        img_path = os.path.join(self.data_dir, self.img_list[index])
        img = Image.open(img_path)
        img = img.resize((224, 224))
        img_tensor = transforms.ToTensor()(img)
        return img_tensor

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

在這個自定義的Dataset類中,我們首先使用os.listdir函數(shù)獲取數(shù)據(jù)集目錄中所有圖像的文件名列表。然后,在__getitem__方法中,我們將圖像打開為PIL格式,并使用resize函數(shù)將其大小調(diào)整為224x224像素。最后,我們使用transforms.ToTensor()函數(shù)將圖像轉(zhuǎn)換為PyTorch張量。

接下來,我們可以創(chuàng)建一個DataLoader對象,以便在訓(xùn)練過程中迭代加載我們的數(shù)據(jù)集。假設(shè)我們想要每次從數(shù)據(jù)集中加載32張圖像,我們可以這樣做:

from torch.utils.data import DataLoader

batch_size = 32
dataset = CustomDataset(data_dir='/path/to/dataset')
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=4)

這里,我們使用CustomDataset類創(chuàng)建一個dataset對象,并將其傳遞給DataLoader類,同時設(shè)置批次大小為32,啟用隨機洗牌(shuffle=True),并使用4個進程(num_workers=4)進行數(shù)據(jù)加載和預(yù)處理。

現(xiàn)在,假設(shè)我們有一個包含不同尺寸的圖像的數(shù)據(jù)集,我們該如何處理呢?一種簡單的解決方案是在自定義的Dataset類中動態(tài)調(diào)整圖像的大小。具體來說,我們可以使用torchvision.transforms.Resize函數(shù)將所有圖像的大小統(tǒng)一調(diào)整為相同的尺寸。例如,如果我們想將所有圖像的大小調(diào)整為256x256像素,我們可以這樣修改CustomDataset類:

import os
from PIL import Image
from torchvision import transforms
import torch.utils.data as data

class CustomDataset(data.Dataset):
    def __init__(self, data_dir, img_size):
        self.data_dir = data_dir
        self.img_list = os.listdir(data_dir)
        self.transform = transforms.Compose([
            transforms.Resize((img_size, img_size)),
            transforms.ToTensor()
        ])

    def __getitem__(self, index):
        img_path = os.path.join(self.data_dir, self.img_list[index])
        img = Image.open(img_path)
        img_tensor = self.transform(img)
        return img_tensor

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

在這個修改后的CustomDataset類中,我們添加了一個新的參數(shù)img_size來指定圖像的目標大小。然后,我們使用torchvision.transforms.Compose函數(shù)將兩個轉(zhuǎn)換操作連接起來,以便

對所有圖像進行預(yù)處理。在__getitem__方法中,我們首先打開圖像文件,并使用transform對象將其調(diào)整為目標大小并轉(zhuǎn)換為PyTorch張量。

接下來,我們可以像之前一樣創(chuàng)建一個DataLoader對象,并將新的CustomDataset類傳遞給它:

from torch.utils.data import DataLoader

batch_size = 32
dataset = CustomDataset(data_dir='/path/to/dataset', img_size=256)
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=4)

在這里,我們使用img_size參數(shù)將目標大小設(shè)置為256x256像素,并且仍然使用了與之前相同的批次大小、隨機洗牌和進程數(shù)量。

需要注意的是,在加載不同尺寸的數(shù)據(jù)集時,我們需要確保所有圖像的最終大小都相同。否則,我們將無法將它們組成一個批次進行有效的訓(xùn)練。因此,必須對圖像進行適當?shù)目s放和裁剪,以便它們具有相同的大小和縱橫比。同時,我們還應(yīng)該考慮使用其他的數(shù)據(jù)增強技術(shù)來增加數(shù)據(jù)集的多樣性和泛化能力。

總之,在PyTorch中加載不同尺寸的數(shù)據(jù)集需要一些額外的工作,但它并不困難。通過動態(tài)調(diào)整圖像大小和使用合適的預(yù)處理操作,我們可以輕松地處理不同尺寸的數(shù)據(jù)集,并使用DataLoader對象在訓(xùn)練過程中進行批量加載。

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }