狗貓分類資料集劃分詳解

2021-10-03 22:52:26 字數 4443 閱讀 4276

資料解壓之後會有兩個資料夾,乙個是「train」,乙個是「test」,顧名思義乙個是用來訓練的,另乙個是作為檢驗正確性的資料,也是**要求提交標籤的。

在train資料夾裡邊是一些已經命名好的影象,有貓也有狗

而在test資料夾中是只有編號名的影象

大致了解了資料集後,下邊就開始劃分資料集

先放一段**,這是從書中擷取出來的:

"""一次返回一張的資料

"""img_path = self.imgs[index]

if self.test:

label = int(self.imgs[index].split('.')[-2].split('/')[-1])

else:

label = 1 if 'dog' in img_path.split('/')[-1] else 0

data = image.open(img_path)

data = self.transforms(data)

return data, label

def __len__(self):

return len(self.imgs)

這裡建立了乙個類,繼承自data.dataset,裡邊有三個方法是必須重寫的:

class dogcat(data.dataset):

def __init__(self, root, transforms=none, train=true, test=false):

""""""

#這個__init__方法是初始化,裡邊可以對資料進行一些預處理

def __getitem__(self, index):

"""一次返回一張的資料

"""#__getitem__方法是迭代器需要,當讀取資料集的時候就會呼叫__getitem__方法,

#一次讀取一張**,因此,這裡主要實現返回影象與標籤的功能

def __len__(self):

#這個函式的目的是返回資料集大小,也是必不可少的部分

下面開始解釋每個方法中語句的功能

def __init__(self, root, transforms=none, train=true, test=false):

#root是根目錄,用來存放資料

#transforms是對影象做出轉換

#train和test是標記

self.test = test

#os.listdir(root)獲取root目錄下所有檔名

imgs = [os.path.join(root, img) for img in os.listdir(root)]

#根據測試集與訓練集命名不同進行不同的劃分

if self.test:

imgs = sorted(imgs, key=lambda x: int(x.split('.')[-2].split('/')[-1]))

else:

imgs = sorted(imgs, key=lambda x: int(x.split('.')[-2]))

#獲取影象數量

imgs_num = len(imgs)

#將test資料夾中影象作為測試集

if self.test:

self.imgs = imgs

#將訓練集70%作為訓練集

elif train:

self.imgs = imgs[:int(0.7 * imgs_num)]

#將訓練集30%作為驗證集

else:

self.imgs = imgs[int(0.7 * imgs_num):]

#下邊對影象做變換

if transforms is none:

normalize = t.normalize(mean=[0.485, 0.456, 0.406],

std=[0.229, 0.224, 0.225])

if self.test or not train:

self.transforms = t.compose([

t.resize(224),

t.centercrop(224),

t.totensor(),

normalize

])else:

self.transforms = t.compose([

t.resize(256),

t.randomresizedcrop(224),

t.randomhorizontalflip(),

t.totensor(),

normalize

])

def __getitem__(self, index):

"""一次返回一張的資料

"""#根據下標獲取標籤

img_path = self.imgs[index]

if self.test:

label = int(self.imgs[index].split('.')[-2].split('/')[-1])

else:

label = 1 if 'dog' in img_path.split('/')[-1] else 0

data = image.open(img_path)

data = self.transforms(data)

#返回影象資料與標籤

return data, label

def __len__(self):

#返回資料集長度

return len(self.imgs)

到此位置,資料集的劃分與資料類已經完成

完整訓練過程可以看我另一篇部落格:

2019 5 14貓狗訓練集

讀取影象檔案。2 將 jpeg 檔案解碼為 rgb 畫素網格。3 將這些畫素網格轉換為浮點數張量。4 將畫素值 0 255 範圍內 縮放到 0,1 區間 正如你所知,神經網路喜歡處理較小的輸 入值 使用 imagedatagenerator 從目錄中讀取影象 from keras.preproces...

使用Keras做貓狗分類

3 建立cnn.py檔案 導入庫 現在建立乙個序列的object classifier sequential 增加第乙個卷積操作 classifier.add conv2d 32,3,3 input shape 64,64,3 activation relu 網路序列化的意思是我們可以通過add增加...

貓狗大戰的TFrecord資料集製作

import tensorflow as tf import numpy as np import os from pil import image 沒有下面兩句德華會出現 image file is truncate的問題 from pil import imagefile imagefile.l...