欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python Pytorch深度學(xué)習(xí)之?dāng)?shù)據(jù)加載和處理

 更新時間:2021年10月28日 08:53:11   作者:柚子味的羊  
今天小編就為大家分享一篇Pytorch 數(shù)據(jù)加載與數(shù)據(jù)預(yù)處理方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

一、下載安裝包

packages:

  • scikit-image:用于圖像測IO和變換
  • pandas:方便進(jìn)行csv解析

二、下載數(shù)據(jù)集

數(shù)據(jù)集說明:該數(shù)據(jù)集(我在這)是imagenet數(shù)據(jù)集標(biāo)注為face的圖片當(dāng)中在dlib面部檢測表現(xiàn)良好的圖片——處理的是一個面部姿態(tài)的數(shù)據(jù)集,也就是按照入戲方式標(biāo)注人臉

在這里插入圖片描述

數(shù)據(jù)集展示

在這里插入圖片描述

在這里插入圖片描述

三、讀取數(shù)據(jù)集

#%%讀取數(shù)據(jù)集
landmarks_frame=pd.read_csv('D:/Python/Pytorch/data/faces/face_landmarks.csv')
n=65
img_name=landmarks_frame.iloc[n,0]
landmarks=landmarks_frame.iloc[n,1:].values
landmarks=landmarks.astype('float').reshape(-1,2)
print('Image name :{}'.format(img_name))
print('Landmarks shape :{}'.format(landmarks.shape))
print('First 4 Landmarks:{}'.format(landmarks[:4]))

運行結(jié)果

在這里插入圖片描述

四、編寫一個函數(shù)看看圖像和landmark

#%%編寫顯示人臉函數(shù)
def show_landmarks(image,landmarks):
    plt.imshow(image)
    plt.scatter(landmarks[:,0],landmarks[:,1],s=10,marker=".",c='r')
    plt.pause(0.001)
plt.figure()
show_landmarks(io.imread(os.path.join('D:/Python/Pytorch/data/faces/',img_name)),landmarks)
plt.show()

運行結(jié)果

在這里插入圖片描述

五、數(shù)據(jù)集類

torch.utils.data.Dataset是表示數(shù)據(jù)集的抽象類,自定義數(shù)據(jù)類應(yīng)繼承Dataset并覆蓋__len__實現(xiàn)len(dataset)返還數(shù)據(jù)集的尺寸。__getitem__用來獲取一些索引數(shù)據(jù):

#%%數(shù)據(jù)集類——將數(shù)據(jù)集封裝成一個類
class FaceLandmarksDataset(Dataset):
    def __init__(self,csv_file,root_dir,transform=None):
        # csv_file(string):待注釋的csv文件的路徑
        # root_dir(string):包含所有圖像的目錄
        # transform(callabele,optional):一個樣本上的可用的可選變換
        self.landmarks_frame=pd.read_csv(csv_file)
        self.root_dir=root_dir
        self.transform=transform
    def __len__(self):
        return len(self.landmarks_frame)
    def __getitem__(self, idx):
        img_name=os.path.join(self.root_dir,self.landmarks_frame.iloc[idx,0])
        image=io.imread(img_name)
        landmarks=self.landmarks_frame.iloc[idx,1:]
        landmarks=np.array([landmarks])
        landmarks=landmarks.astype('float').reshape(-1,2)
        sample={'image':image,'landmarks':landmarks}
        if self.transform:
            sample=self.transform(sample)
        return sample    

六、數(shù)據(jù)可視化

#%%數(shù)據(jù)可視化
# 將上面定義的類進(jìn)行實例化并便利整個數(shù)據(jù)集
face_dataset=FaceLandmarksDataset(csv_file='D:/Python/Pytorch/data/faces/face_landmarks.csv', 
                                  root_dir='D:/Python/Pytorch/data/faces/')
fig=plt.figure()
for i in range(len(face_dataset)) :
    sample=face_dataset[i]
    print(i,sample['image'].shape,sample['landmarks'].shape)
    ax=plt.subplot(1,4,i+1)
    plt.tight_layout()
    ax.set_title('Sample #{}'.format(i))
    ax.axis('off')
    show_landmarks(**sample)
    if i==3:
        plt.show()
        break

運行結(jié)果

在這里插入圖片描述

在這里插入圖片描述

七、數(shù)據(jù)變換

由上圖可以發(fā)現(xiàn)每張圖像的尺寸大小是不同的。絕大多數(shù)神經(jīng)網(wǎng)路都嘉定圖像的尺寸相同。所以需要對圖像先進(jìn)行預(yù)處理。創(chuàng)建三個轉(zhuǎn)換:

Rescale:縮放圖片

RandomCrop:對圖片進(jìn)行隨機(jī)裁剪

ToTensor:把numpy格式圖片轉(zhuǎn)成torch格式圖片(交換坐標(biāo)軸)和上面同樣的方式,將其寫成一個類,這樣就不需要在每次調(diào)用的時候川第一此參數(shù),只需要實現(xiàn)__call__的方法,必要的時候使用__init__方法

1、Function_Rescale

# 將樣本中的圖像重新縮放到給定的大小
class Rescale(object):    
    def __init__(self,output_size):
        assert isinstance(output_size,(int,tuple))
        self.output_size=output_size
    #output_size 為int或tuple,如果是元組輸出與output_size匹配,
    #如果是int,匹配較小的圖像邊緣到output_size保持縱橫比相同
    def __call__(self,sample):
        image,landmarks=sample['image'],sample['landmarks']
        h,w=image.shape[:2]
        if isinstance(self.output_size, int):#輸入?yún)?shù)是int
            if h>w:
                new_h,new_w=self.output_size*h/w,self.output_size
            else:
                new_h,new_w=self.output_size,self.output_size*w/h
        else:#輸入?yún)?shù)是元組
            new_h,new_w=self.output_size
        new_h,new_w=int(new_h),int(new_w)
        img=transform.resize(image, (new_h,new_w))
        landmarks=landmarks*[new_w/w,new_h/h]
        return {'image':img,'landmarks':landmarks}

2、Function_RandomCrop

# 隨機(jī)裁剪樣本中的圖像
class RandomCrop(object):
    def __init__(self,output_size):
        assert isinstance(output_size, (int,tuple))
        if isinstance(output_size, int):
            self.output_size=(output_size,output_size)
        else:
            assert len(output_size)==2
            self.output_size=output_size
    # 輸入?yún)?shù)依舊表示想要裁剪后圖像的尺寸,如果是元組其而包含兩個元素直接復(fù)制長寬,如果是int,則裁剪為方形
    def __call__(self,sample):
        image,landmarks=sample['image'],sample['landmarks']
        h,w=image.shape[:2]
        new_h,new_w=self.output_size
        #確定圖片裁剪位置
        top=np.random.randint(0,h-new_h)
        left=np.random.randint(0,w-new_w)
        image=image[top:top+new_h,left:left+new_w]
        landmarks=landmarks-[left,top]
        return {'image':image,'landmarks':landmarks}

3、Function_ToTensor

#%%
# 將樣本中的npdarray轉(zhuǎn)換為Tensor
class ToTensor(object):
    def __call__(self,sample):
        image,landmarks=sample['image'],sample['landmarks']
        image=image.transpose((2,0,1))#交換顏色軸
        #numpy的圖片是:Height*Width*Color
        #torch的圖片是:Color*Height*Width
        return {'image':torch.from_numpy(image),
                'landmarks':torch.from_numpy(landmarks)}

八、組合轉(zhuǎn)換

將上面編寫的類應(yīng)用到實例中

Req: 把圖像的短邊調(diào)整為256,隨機(jī)裁剪(randomcrop)為224大小的正方形。即:組合一個Rescale和RandomCrop的變換。

#%%
scale=Rescale(256)
crop=RandomCrop(128)
composed=transforms.Compose([Rescale(256),RandomCrop(224)])    
# 在樣本上應(yīng)用上述變換
fig=plt.figure() 
sample=face_dataset[65]
for i,tsfrm in enumerate([scale,crop,composed]):
    transformed_sample=tsfrm(sample)
    ax=plt.subplot(1,3,i+1)
    plt.tight_layout()
    ax.set_title(type(tsfrm).__name__)
    show_landmarks(**transformed_sample)
plt.show()

運行結(jié)果

在這里插入圖片描述

九、迭代數(shù)據(jù)集

把這些整合起來以創(chuàng)建一個帶有組合轉(zhuǎn)換的數(shù)據(jù)集,總結(jié)一下沒每次這個數(shù)據(jù)集被采樣的時候:及時的從文件中讀取圖片,對讀取的圖片應(yīng)用轉(zhuǎn)換,由于其中一部是隨機(jī)的randomcrop,數(shù)據(jù)被增強(qiáng)了??梢允褂醚h(huán)對創(chuàng)建的數(shù)據(jù)集執(zhí)行同樣的操作

transformed_dataset=FaceLandmarksDataset(csv_file='D:/Python/Pytorch/data/faces/face_landmarks.csv',
                                          root_dir='D:/Python/Pytorch/data/faces/',
                                          transform=transforms.Compose([
                                              Rescale(256),
                                              RandomCrop(224),
                                              ToTensor()
                                              ]))
for i in range(len(transformed_dataset)):
    sample=transformed_dataset[i]
    print(i,sample['image'].size(),sample['landmarks'].size())
    if i==3:
        break    

運行結(jié)果

在這里插入圖片描述

對所有數(shù)據(jù)集簡單使用for循環(huán)會犧牲很多功能——>麻煩,效率低??!改用多線程并行進(jìn)行
torch.utils.data.DataLoader可以提供上述功能的迭代器。collate_fn參數(shù)可以決定如何對數(shù)據(jù)進(jìn)行批處理,絕大多數(shù)情況下默認(rèn)值就OK

transformed_dataset=FaceLandmarksDataset(csv_file='D:/Python/Pytorch/data/faces/face_landmarks.csv',
                                          root_dir='D:/Python/Pytorch/data/faces/',
                                          transform=transforms.Compose([
                                              Rescale(256),
                                              RandomCrop(224),
                                              ToTensor()
                                              ]))
for i in range(len(transformed_dataset)):
    sample=transformed_dataset[i]
    print(i,sample['image'].size(),sample['landmarks'].size())
    if i==3:
        break    

總結(jié)

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!

相關(guān)文章

  • Django如何開發(fā)簡單的查詢接口詳解

    Django如何開發(fā)簡單的查詢接口詳解

    這篇文章主要給大家介紹了使用Django如何開發(fā)簡單的查詢接口的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Django具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • 用Python從零實現(xiàn)貝葉斯分類器的機(jī)器學(xué)習(xí)的教程

    用Python從零實現(xiàn)貝葉斯分類器的機(jī)器學(xué)習(xí)的教程

    這篇文章主要介紹了用Python從零實現(xiàn)貝葉斯分類器的教程,樸素貝葉斯算法屬于機(jī)器學(xué)習(xí)中的基礎(chǔ)內(nèi)容、實用而高效,本文詳細(xì)展示了用Python語言實現(xiàn)的步驟,需要的朋友可以參考下
    2015-03-03
  • Python編寫通訊錄通過數(shù)據(jù)庫存儲實現(xiàn)模糊查詢功能

    Python編寫通訊錄通過數(shù)據(jù)庫存儲實現(xiàn)模糊查詢功能

    數(shù)據(jù)庫存儲通訊錄,要求按姓名/電話號碼查詢,查詢條件只有一個輸入入口,自動識別輸入的是姓名還是號碼,允許模糊查詢。這篇文章主要介紹了Python編寫通訊錄,支持模糊查詢,利用數(shù)據(jù)庫存儲,需要的朋友可以參考下
    2019-07-07
  • python里面單雙下劃線的區(qū)別詳解

    python里面單雙下劃線的區(qū)別詳解

    本文主要介紹了python里面單雙下劃線的區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • Python必備技能之debug調(diào)試教程詳解

    Python必備技能之debug調(diào)試教程詳解

    這篇文章主要為大家詳細(xì)介紹了Python初學(xué)者必須要學(xué)會的技能——在Python中進(jìn)行debug操作,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下
    2023-03-03
  • Python的類成員變量默認(rèn)初始值的坑及解決

    Python的類成員變量默認(rèn)初始值的坑及解決

    這篇文章主要介紹了Python的類成員變量默認(rèn)初始值的坑及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • 利用LyScript實現(xiàn)應(yīng)用層鉤子掃描器

    利用LyScript實現(xiàn)應(yīng)用層鉤子掃描器

    Capstone 是一個輕量級的多平臺、多架構(gòu)的反匯編框架。本篇文章將運用LyScript插件結(jié)合Capstone反匯編引擎實現(xiàn)一個鉤子掃描器,感興趣的可以了解一下
    2022-08-08
  • Python?"手繪風(fēng)格"數(shù)據(jù)可視化方法實例匯總

    Python?"手繪風(fēng)格"數(shù)據(jù)可視化方法實例匯總

    這篇文章主要給大家介紹了關(guān)于Python?"手繪風(fēng)格"數(shù)據(jù)可視化方法實現(xiàn)的相關(guān)資料,本文分別給大家?guī)砹薖ython-matplotlib手繪風(fēng)格圖表繪制、Python-cutecharts手繪風(fēng)格圖表繪制以及Python-py-roughviz手繪風(fēng)格圖表繪制,需要的朋友可以參考下
    2022-02-02
  • python入門之語句(if語句、while語句、for語句)

    python入門之語句(if語句、while語句、for語句)

    這篇文章主要介紹了python入門之語句,主要包括if語句、while語句、for語句的使用,需要的朋友可以參考下
    2015-01-01
  • Python獲取時間的操作示例詳解

    Python獲取時間的操作示例詳解

    這篇文章主要為大家詳細(xì)介紹了一些Python中獲取時間的操作,例如:獲取時間戳、獲取當(dāng)前時間、獲取昨天日期等,感興趣的可以參考一下
    2022-07-07

最新評論