最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

pytorch 準備、訓(xùn)練和測試自己的圖片數(shù)據(jù)的方法

 更新時間:2020年01月10日 09:42:01   作者:denny402  
這篇文章主要介紹了pytorch 準備、訓(xùn)練和測試自己的圖片數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

大部分的pytorch入門教程,都是使用torchvision里面的數(shù)據(jù)進行訓(xùn)練和測試。如果我們是自己的圖片數(shù)據(jù),又該怎么做呢?

一、我的數(shù)據(jù)

我在學(xué)習(xí)的時候,使用的是fashion-mnist。這個數(shù)據(jù)比較小,我的電腦沒有GPU,還能吃得消。關(guān)于fashion-mnist數(shù)據(jù),可以百度,也可以點此 了解一下,數(shù)據(jù)就像這個樣子:

下載地址:https://github.com/zalandoresearch/fashion-mnist

但是下載下來是一種二進制文件,并不是圖片,因此我先轉(zhuǎn)換成了圖片。

我先解壓gz文件到e:/fashion_mnist/文件夾

然后運行代碼:

import os
from skimage import io
import torchvision.datasets.mnist as mnist

root="E:/fashion_mnist/"
train_set = (
  mnist.read_image_file(os.path.join(root, 'train-images-idx3-ubyte')),
  mnist.read_label_file(os.path.join(root, 'train-labels-idx1-ubyte'))
    )
test_set = (
  mnist.read_image_file(os.path.join(root, 't10k-images-idx3-ubyte')),
  mnist.read_label_file(os.path.join(root, 't10k-labels-idx1-ubyte'))
    )
print("training set :",train_set[0].size())
print("test set :",test_set[0].size())

def convert_to_img(train=True):
  if(train):
    f=open(root+'train.txt','w')
    data_path=root+'/train/'
    if(not os.path.exists(data_path)):
      os.makedirs(data_path)
    for i, (img,label) in enumerate(zip(train_set[0],train_set[1])):
      img_path=data_path+str(i)+'.jpg'
      io.imsave(img_path,img.numpy())
      f.write(img_path+' '+str(label)+'\n')
    f.close()
  else:
    f = open(root + 'test.txt', 'w')
    data_path = root + '/test/'
    if (not os.path.exists(data_path)):
      os.makedirs(data_path)
    for i, (img,label) in enumerate(zip(test_set[0],test_set[1])):
      img_path = data_path+ str(i) + '.jpg'
      io.imsave(img_path, img.numpy())
      f.write(img_path + ' ' + str(label) + '\n')
    f.close()

convert_to_img(True)
convert_to_img(False)

這樣就會在e:/fashion_mnist/目錄下分別生成train和test文件夾,用于存放圖片。還在該目錄下生成了標簽文件train.txt和test.txt.

二、進行CNN分類訓(xùn)練和測試

先要將圖片讀取出來,準備成torch專用的dataset格式,再通過Dataloader進行分批次訓(xùn)練。

代碼如下:

import torch
from torch.autograd import Variable
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from PIL import Image
root="E:/fashion_mnist/"

# -----------------ready the dataset--------------------------
def default_loader(path):
  return Image.open(path).convert('RGB')
class MyDataset(Dataset):
  def __init__(self, txt, transform=None, target_transform=None, loader=default_loader):
    fh = open(txt, 'r')
    imgs = []
    for line in fh:
      line = line.strip('\n')
      line = line.rstrip()
      words = line.split()
      imgs.append((words[0],int(words[1])))
    self.imgs = imgs
    self.transform = transform
    self.target_transform = target_transform
    self.loader = loader

  def __getitem__(self, index):
    fn, label = self.imgs[index]
    img = self.loader(fn)
    if self.transform is not None:
      img = self.transform(img)
    return img,label

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

train_data=MyDataset(txt=root+'train.txt', transform=transforms.ToTensor())
test_data=MyDataset(txt=root+'test.txt', transform=transforms.ToTensor())
train_loader = DataLoader(dataset=train_data, batch_size=64, shuffle=True)
test_loader = DataLoader(dataset=test_data, batch_size=64)


#-----------------create the Net and training------------------------

class Net(torch.nn.Module):
  def __init__(self):
    super(Net, self).__init__()
    self.conv1 = torch.nn.Sequential(
      torch.nn.Conv2d(3, 32, 3, 1, 1),
      torch.nn.ReLU(),
      torch.nn.MaxPool2d(2))
    self.conv2 = torch.nn.Sequential(
      torch.nn.Conv2d(32, 64, 3, 1, 1),
      torch.nn.ReLU(),
      torch.nn.MaxPool2d(2)
    )
    self.conv3 = torch.nn.Sequential(
      torch.nn.Conv2d(64, 64, 3, 1, 1),
      torch.nn.ReLU(),
      torch.nn.MaxPool2d(2)
    )
    self.dense = torch.nn.Sequential(
      torch.nn.Linear(64 * 3 * 3, 128),
      torch.nn.ReLU(),
      torch.nn.Linear(128, 10)
    )

  def forward(self, x):
    conv1_out = self.conv1(x)
    conv2_out = self.conv2(conv1_out)
    conv3_out = self.conv3(conv2_out)
    res = conv3_out.view(conv3_out.size(0), -1)
    out = self.dense(res)
    return out


model = Net()
print(model)

optimizer = torch.optim.Adam(model.parameters())
loss_func = torch.nn.CrossEntropyLoss()

for epoch in range(10):
  print('epoch {}'.format(epoch + 1))
  # training-----------------------------
  train_loss = 0.
  train_acc = 0.
  for batch_x, batch_y in train_loader:
    batch_x, batch_y = Variable(batch_x), Variable(batch_y)
    out = model(batch_x)
    loss = loss_func(out, batch_y)
    train_loss += loss.data[0]
    pred = torch.max(out, 1)[1]
    train_correct = (pred == batch_y).sum()
    train_acc += train_correct.data[0]
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
  print('Train Loss: {:.6f}, Acc: {:.6f}'.format(train_loss / (len(
    train_data)), train_acc / (len(train_data))))

  # evaluation--------------------------------
  model.eval()
  eval_loss = 0.
  eval_acc = 0.
  for batch_x, batch_y in test_loader:
    batch_x, batch_y = Variable(batch_x, volatile=True), Variable(batch_y, volatile=True)
    out = model(batch_x)
    loss = loss_func(out, batch_y)
    eval_loss += loss.data[0]
    pred = torch.max(out, 1)[1]
    num_correct = (pred == batch_y).sum()
    eval_acc += num_correct.data[0]
  print('Test Loss: {:.6f}, Acc: {:.6f}'.format(eval_loss / (len(
    test_data)), eval_acc / (len(test_data))))

打印出來的網(wǎng)絡(luò)模型:

訓(xùn)練和測試結(jié)果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python簡單遍歷字典及刪除元素的方法

    Python簡單遍歷字典及刪除元素的方法

    這篇文章主要介紹了Python簡單遍歷字典及刪除元素的方法,結(jié)合實例形式分析了Python遍歷字典刪除元素的操作方法與相關(guān)注意事項,需要的朋友可以參考下
    2016-09-09
  • 如何用python合并多個有規(guī)則命名的nc文件

    如何用python合并多個有規(guī)則命名的nc文件

    在地學(xué)領(lǐng)域,nc格式的文件可謂隨處可見,這種文件可以存儲多維數(shù)字矩陣,下面這篇文章主要給大家介紹了關(guān)于如何用python合并多個有規(guī)則命名的nc文件的相關(guān)資料,需要的朋友可以參考下
    2022-03-03
  • Python中函數(shù)的多種格式和使用實例及小技巧

    Python中函數(shù)的多種格式和使用實例及小技巧

    這篇文章主要介紹了Python中函數(shù)的多種格式和使用實例及小技巧,本文講解了普通格式、帶收集位置參數(shù)的函數(shù)、帶收集關(guān)鍵字參數(shù)的函數(shù)、函數(shù)特殊用法、內(nèi)嵌函數(shù)和閉包等內(nèi)容,需要的朋友可以參考下
    2015-04-04
  • 詳解如何優(yōu)雅的用PyQt訪問http

    詳解如何優(yōu)雅的用PyQt訪問http

    這篇文章主要我打開詳細介紹了如何優(yōu)雅的用PyQt實現(xiàn)訪問http,文中的示例代碼講解詳細,具有一定的借鑒價值,感興趣的小伙伴可以了解下
    2024-11-11
  • Python命令行參數(shù)argv和argparse該如何使用

    Python命令行參數(shù)argv和argparse該如何使用

    這篇文章主要介紹了Python命令行參數(shù)argv和argparse該如何使用,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下
    2021-02-02
  • 一百多行python代碼實現(xiàn)搶票助手

    一百多行python代碼實現(xiàn)搶票助手

    一百多行python代碼輕松實現(xiàn)搶票助手,十一出行不再愁!本文具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-09-09
  • 關(guān)于Python如何安裝requests庫

    關(guān)于Python如何安裝requests庫

    這篇文章主要介紹了關(guān)于Python如何安裝requests庫,requests庫自稱“HTTP for Humans”,直譯過來的意思是專門為人類設(shè)計的HTTP庫,能夠被開發(fā)人員安全地使用,需要的朋友可以參考下
    2023-04-04
  • Python生成隨機數(shù)組的方法小結(jié)

    Python生成隨機數(shù)組的方法小結(jié)

    這篇文章主要介紹了Python生成隨機數(shù)組的方法,結(jié)合實例形式總結(jié)分析了Python使用random模塊生成隨機數(shù)與數(shù)組操作相關(guān)技巧,需要的朋友可以參考下
    2017-04-04
  • python 字符串格式化代碼

    python 字符串格式化代碼

    python 字符串格式化代碼,需要的朋友可以參考一下
    2013-03-03
  • Python迭代器的實現(xiàn)原理

    Python迭代器的實現(xiàn)原理

    這篇文章主要介紹了Python迭代器的實現(xiàn)原理,文章基于python的相關(guān)資料展開對Python迭代器的詳細介紹,需要的小伙伴可以參考一下
    2022-05-05

最新評論

桑日县| 上蔡县| 宁武县| 探索| 三明市| 涪陵区| 嘉义县| 襄汾县| 余姚市| 荆州市| 缙云县| 永新县| 平和县| 临邑县| 绍兴市| 余姚市| 安多县| 五华县| 铜鼓县| 隆尧县| 平凉市| 马山县| 绥化市| 沭阳县| 青龙| 三原县| 林州市| 桦南县| 滦南县| 随州市| 普定县| 巴东县| 雷山县| 兰西县| 信阳市| 吴桥县| 隆安县| 柳河县| 新乡市| 林周县| 科技|