侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

pytorch 准备、训练和测试自己的图片数据的方法

Python  /  管理员 发布于 5年前   384

大部分的pytorch入门教程,都是使用torchvision里面的数据进行训练和测试。如果我们是自己的图片数据,又该怎么做呢?

一、我的数据

我在学习的时候,使用的是fashion-mnist。这个数据比较小,我的电脑没有GPU,还能吃得消。关于fashion-mnist数据,可以百度,也可以点此 了解一下,数据就像这个样子:

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

但是下载下来是一种二进制文件,并不是图片,因此我先转换成了图片。

我先解压gz文件到e:/fashion_mnist/文件夹

然后运行代码:

import osfrom skimage import ioimport torchvision.datasets.mnist as mnistroot="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 torchfrom torch.autograd import Variablefrom torchvision import transformsfrom torch.utils.data import Dataset, DataLoaderfrom PIL import Imageroot="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 outmodel = 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))))

打印出来的网络模型:

训练和测试结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    pytorch实现mnist分类的示例讲解
    下一条:
    pytorch GAN伪造手写体mnist数据集方式
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客