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

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

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

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

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

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

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

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

我先解壓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分類訓練和測試

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

代碼如下:

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)絡模型:

訓練和測試結果:

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

相關文章

  • ubuntu系統(tǒng)下切換python版本的方法

    ubuntu系統(tǒng)下切換python版本的方法

    有時候需要在默認python中使用不通版本的python,下面這篇文章主要介紹了ubuntu系統(tǒng)下切換python版本的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-04-04
  • 使用Python中的PIL庫給圖片添加馬賽克

    使用Python中的PIL庫給圖片添加馬賽克

    Pillow是一個Python圖像處理庫,提供了廣泛的圖像處理功能包括圖像格式轉換、圖像增強等,本文就來用PIL庫實現(xiàn)給圖片添加馬賽克效果,感興趣的可以了解一下
    2023-05-05
  • 解決python tkinter界面卡死的問題

    解決python tkinter界面卡死的問題

    今天小編就為大家分享一篇解決python tkinter界面卡死的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • 詳解Python中dbm模塊和shelve模塊的使用

    詳解Python中dbm模塊和shelve模塊的使用

    這篇文章主要為大家詳細介紹了Python中dbm模塊和shelve模塊的具體用法,文中的示例代碼簡潔易懂,對我們深入學習Python有一定的幫助,需要的可以參考下
    2023-10-10
  • Python中的Numpy 矩陣運算

    Python中的Numpy 矩陣運算

    這篇文章介紹Python中的Numpy 矩陣運算,NumPy是Python的一種開源的數(shù)值計算擴展.這種工具可用來存儲和處理大型矩陣,比Python自身的嵌套列表結構要高效的多,支持大量的維度數(shù)組與矩陣運算,此外也針對數(shù)組運算提供大量的數(shù)學函數(shù)庫,下面詳細內(nèi)容,需要的朋友可以參考一下
    2021-11-11
  • pypy提升python項目性能使用詳解

    pypy提升python項目性能使用詳解

    這篇文章主要為大家介紹了pypy提升python項目性能使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • python文件和文件夾復制函數(shù)

    python文件和文件夾復制函數(shù)

    這篇文章主要為大家詳細介紹了python文件和文件夾復制函數(shù)的實現(xiàn)代碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-02-02
  • 使用python+requests+pytest實現(xiàn)接口自動化

    使用python+requests+pytest實現(xiàn)接口自動化

    這篇文章主要介紹了使用python+requests+pytest實現(xiàn)接口自動化,在當前互聯(lián)網(wǎng)產(chǎn)品迭代頻繁的背景下,回歸測試的時間越來越少,但接口自動化測試因其實現(xiàn)簡單、維護成本低,容易提高覆蓋率等特點,越來越受重視,需要的朋友可以參考下
    2023-08-08
  • Django框架中的對象列表視圖使用示例

    Django框架中的對象列表視圖使用示例

    這篇文章主要介紹了Django框架中的對象列表視圖使用示例,Django是重多Python人氣web框架中最為著名的一個,需要的朋友可以參考下
    2015-07-07
  • pampy超強的模式匹配工具的實現(xiàn)

    pampy超強的模式匹配工具的實現(xiàn)

    在自然語言處理界,模式匹配可以說是最常用的技術。甚至可以說,將NLP技術作為真實生產(chǎn)力的項目都少不了模式匹配。本文就介紹了pampy超強的模式匹配工具的實現(xiàn),感興趣的可以了解一下
    2021-07-07

最新評論