您好,登錄后才能下訂單哦!
小編給大家分享一下Pytorch中如何實(shí)現(xiàn)自己加載單通道圖片用作數(shù)據(jù)集訓(xùn)練,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
pytorch 在torchvision包里面有很多的的打包好的數(shù)據(jù)集,例如minist,Imagenet-12,CIFAR10 和CIFAR100。在torchvision的dataset包里面,用的時(shí)候直接調(diào)用就行了。具體的調(diào)用格式可以去看文檔(目前好像只有英文的)。網(wǎng)上也有很多源代碼。
不過(guò),當(dāng)我們想利用自己制作的數(shù)據(jù)集來(lái)訓(xùn)練網(wǎng)絡(luò)模型時(shí),就要有自己的方法了。pytorch在torchvision.dataset包里面封裝過(guò)一個(gè)函數(shù)ImageFolder()。這個(gè)函數(shù)功能很強(qiáng)大,只要你直接將數(shù)據(jù)集路徑保存為例如“train/1/1.jpg ,rain/1/2.jpg …… ”就可以根據(jù)根目錄“./train”將數(shù)據(jù)集裝載了。
dataset.ImageFolder(root="datapath", transfroms.ToTensor())
但是后來(lái)我發(fā)現(xiàn)一個(gè)問(wèn)題,就是這個(gè)函數(shù)加載出來(lái)的圖像矩陣都是三通道的,并且沒(méi)有什么參數(shù)調(diào)用可以讓其變?yōu)閱瓮ǖ?。如果我們要用到單通道?shù)據(jù)集(灰度圖)的話,比如自己加載Lenet-5模型的數(shù)據(jù)集,就只能自己寫(xiě)numpy數(shù)組再轉(zhuǎn)為pytorch的Tensor()張量了。
接下來(lái)是我做的過(guò)程:
首先,還是要用到opencv,用灰度圖打開(kāi)一張圖片,省事。
#讀取圖片 這里是灰度圖 for item in all_path: img = cv2.imread(item[1],0) img = cv2.resize(img,(28,28)) arr = np.asarray(img,dtype="float32") data_x[i ,:,:,:] = arr i+=1 data_y.append(int(item[0])) data_x = data_x / 255 data_y = np.asarray(data_y)
其次,pytorch有自己的numpy轉(zhuǎn)Tensor函數(shù),直接轉(zhuǎn)就行了。
data_x = torch.from_numpy(data_x) data_y = torch.from_numpy(data_y)
下一步利用torch.util和torchvision里面的dataLoader函數(shù),就能直接得到和torchvision.dataset里面封裝好的包相同的數(shù)據(jù)集樣本了
dataset = dataf.TensorDataset(data_x,data_y) loader = dataf.DataLoader(dataset, batch_size=batchsize, shuffle=True)
最后就是自己建網(wǎng)絡(luò)設(shè)計(jì)參數(shù)訓(xùn)練了,這部分和文檔以及github中的差不多,就不贅述了。
下面是整個(gè)程序的源代碼,我利用的還是上次的車標(biāo)識(shí)別的數(shù)據(jù)集,一共分四類,用的是2層卷積核兩層全連接。
源代碼:
# coding=utf-8 import os import cv2 import numpy as np import random import torch import torch.nn as nn import torch.utils.data as dataf from torch.autograd import Variable import torch.nn.functional as F import torch.optim as optim #訓(xùn)練參數(shù) cuda = False train_epoch = 20 train_lr = 0.01 train_momentum = 0.5 batchsize = 5 #測(cè)試訓(xùn)練集路徑 test_path = "/home/test/" train_path = "/home/train/" #路徑數(shù)據(jù) all_path =[] def load_data(data_path): signal = os.listdir(data_path) for fsingal in signal: filepath = data_path+fsingal filename = os.listdir(filepath) for fname in filename: ffpath = filepath+"/"+fname path = [fsingal,ffpath] all_path.append(path) #設(shè)立數(shù)據(jù)集多大 count = len(all_path) data_x = np.empty((count,1,28,28),dtype="float32") data_y = [] #打亂順序 random.shuffle(all_path) i=0; #讀取圖片 這里是灰度圖 最后結(jié)果是i*i*i*i #分別表示:batch大小 , 通道數(shù), 像素矩陣 for item in all_path: img = cv2.imread(item[1],0) img = cv2.resize(img,(28,28)) arr = np.asarray(img,dtype="float32") data_x[i ,:,:,:] = arr i+=1 data_y.append(int(item[0])) data_x = data_x / 255 data_y = np.asarray(data_y) # lener = len(all_path) data_x = torch.from_numpy(data_x) data_y = torch.from_numpy(data_y) dataset = dataf.TensorDataset(data_x,data_y) loader = dataf.DataLoader(dataset, batch_size=batchsize, shuffle=True) return loader # print data_y train_load = load_data(train_path) test_load = load_data(test_path) class L5_NET(nn.Module): def __init__(self): super(L5_NET ,self).__init__(); #第一層輸入1,20個(gè)卷積核 每個(gè)5*5 self.conv1 = nn.Conv2d(1 , 20 , kernel_size=5) #第二層輸入20,30個(gè)卷積核 每個(gè)5*5 self.conv2 = nn.Conv2d(20 , 30 , kernel_size=5) #drop函數(shù) self.conv2_drop = nn.Dropout2d() #全鏈接層1,展開(kāi)30*4*4,連接層50個(gè)神經(jīng)元 self.fc1 = nn.Linear(30*4*4,50) #全鏈接層1,50-4 ,4為最后的輸出分類 self.fc2 = nn.Linear(50,4) #前向傳播 def forward(self,x): #池化層1 對(duì)于第一層卷積池化,池化核2*2 x = F.relu(F.max_pool2d( self.conv1(x) ,2 ) ) #池化層2 對(duì)于第二層卷積池化,池化核2*2 x = F.relu(F.max_pool2d( self.conv2_drop( self.conv2(x) ) , 2 ) ) #平鋪軸30*4*4個(gè)神經(jīng)元 x = x.view(-1 , 30*4*4) #全鏈接1 x = F.relu( self.fc1(x) ) #dropout鏈接 x = F.dropout(x , training= self.training) #全鏈接w x = self.fc2(x) #softmax鏈接返回結(jié)果 return F.log_softmax(x) model = L5_NET() if cuda : model.cuda() optimizer = optim.SGD(model.parameters() , lr =train_lr , momentum = train_momentum ) #預(yù)測(cè)函數(shù) def train(epoch): model.train() for batch_idx, (data, target) in enumerate(train_load): if cuda: data, target = data.cuda(), target.cuda() data, target = Variable(data), Variable(target) #求導(dǎo) optimizer.zero_grad() #訓(xùn)練模型,輸出結(jié)果 output = model(data) #在數(shù)據(jù)集上預(yù)測(cè)loss loss = F.nll_loss(output, target) #反向傳播調(diào)整參數(shù)pytorch直接可以用loss loss.backward() #SGD刷新進(jìn)步 optimizer.step() #實(shí)時(shí)輸出 if batch_idx % 10 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_load.dataset), 100. * batch_idx / len(train_load), loss.data[0])) # #測(cè)試函數(shù) def test(epoch): model.eval() test_loss = 0 correct = 0 for data, target in test_load: if cuda: data, target = data.cuda(), target.cuda() data, target = Variable(data, volatile=True), Variable(target) #在測(cè)試集上預(yù)測(cè) output = model(data) #計(jì)算在測(cè)試集上的loss test_loss += F.nll_loss(output, target).data[0] #獲得預(yù)測(cè)的結(jié)果 pred = output.data.max(1)[1] # get the index of the max log-probability #如果正確,correct+1 correct += pred.eq(target.data).cpu().sum() #loss計(jì)算 test_loss = test_loss test_loss /= len(test_load) #輸出結(jié)果 print('\nThe {} epoch result : Average loss: {:.6f}, Accuracy: {}/{} ({:.2f}%)\n'.format( epoch,test_loss, correct, len(test_load.dataset), 100. * correct / len(test_load.dataset))) for epoch in range(1, train_epoch+ 1): train(epoch) test(epoch)
最后的訓(xùn)練結(jié)果和在keras下差不多,不過(guò)我訓(xùn)練的時(shí)候好像把訓(xùn)練集和測(cè)試集弄反了,數(shù)目好像測(cè)試集比訓(xùn)練集還多,有點(diǎn)尷尬,不過(guò)無(wú)傷大雅。結(jié)果圖如下:
以上是“Pytorch中如何實(shí)現(xiàn)自己加載單通道圖片用作數(shù)據(jù)集訓(xùn)練”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。