国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Pytorch自己加載單通道圖片用作數(shù)據(jù)集訓(xùn)練的實(shí)例

2020-02-15 21:29:36
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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)閱瓮ǖ馈H绻覀円玫絾瓮ǖ罃?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è)程序的源代碼,我利用的還是上次的車(chē)標(biāo)識(shí)別的數(shù)據(jù)集,一共分四類(lèi),用的是2層卷積核兩層全連接。

源代碼:

# coding=utf-8import osimport cv2import numpy as npimport random import torchimport torch.nn as nnimport torch.utils.data as dataffrom torch.autograd import Variableimport torch.nn.functional as Fimport torch.optim as optim #訓(xùn)練參數(shù)cuda = Falsetrain_epoch = 20train_lr = 0.01train_momentum = 0.5batchsize = 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為最后的輸出分類(lèi)  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)             
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 仁布县| 南雄市| 莆田市| 武陟县| 任丘市| 石景山区| 石阡县| 北宁市| 信阳市| 隆尧县| 瑞安市| 东莞市| 马山县| 丹棱县| 台北县| 喜德县| 吉林省| 禄丰县| 靖宇县| 嘉义县| 绥棱县| 芒康县| 栾城县| 汽车| 公安县| 石家庄市| 罗田县| 阿勒泰市| 郧西县| 天门市| 社会| 翁牛特旗| 云浮市| 资兴市| 长武县| 鄱阳县| 宾川县| 织金县| 松潘县| 镇坪县| 阳高县|