利用PyTorch实现VGG16教程


Posted in Python onJune 24, 2020

我就废话不多说了,大家还是直接看代码吧~

import torch
import torch.nn as nn
import torch.nn.functional as F
class VGG16(nn.Module):
 
 def __init__(self):
  super(VGG16, self).__init__()
  
  # 3 * 224 * 224
  self.conv1_1 = nn.Conv2d(3, 64, 3) # 64 * 222 * 222
  self.conv1_2 = nn.Conv2d(64, 64, 3, padding=(1, 1)) # 64 * 222* 222
  self.maxpool1 = nn.MaxPool2d((2, 2), padding=(1, 1)) # pooling 64 * 112 * 112
  
  self.conv2_1 = nn.Conv2d(64, 128, 3) # 128 * 110 * 110
  self.conv2_2 = nn.Conv2d(128, 128, 3, padding=(1, 1)) # 128 * 110 * 110
  self.maxpool2 = nn.MaxPool2d((2, 2), padding=(1, 1)) # pooling 128 * 56 * 56
  
  self.conv3_1 = nn.Conv2d(128, 256, 3) # 256 * 54 * 54
  self.conv3_2 = nn.Conv2d(256, 256, 3, padding=(1, 1)) # 256 * 54 * 54
  self.conv3_3 = nn.Conv2d(256, 256, 3, padding=(1, 1)) # 256 * 54 * 54
  self.maxpool3 = nn.MaxPool2d((2, 2), padding=(1, 1)) # pooling 256 * 28 * 28
  
  self.conv4_1 = nn.Conv2d(256, 512, 3) # 512 * 26 * 26
  self.conv4_2 = nn.Conv2d(512, 512, 3, padding=(1, 1)) # 512 * 26 * 26
  self.conv4_3 = nn.Conv2d(512, 512, 3, padding=(1, 1)) # 512 * 26 * 26
  self.maxpool4 = nn.MaxPool2d((2, 2), padding=(1, 1)) # pooling 512 * 14 * 14
  
  self.conv5_1 = nn.Conv2d(512, 512, 3) # 512 * 12 * 12
  self.conv5_2 = nn.Conv2d(512, 512, 3, padding=(1, 1)) # 512 * 12 * 12
  self.conv5_3 = nn.Conv2d(512, 512, 3, padding=(1, 1)) # 512 * 12 * 12
  self.maxpool5 = nn.MaxPool2d((2, 2), padding=(1, 1)) # pooling 512 * 7 * 7
  # view
  
  self.fc1 = nn.Linear(512 * 7 * 7, 4096)
  self.fc2 = nn.Linear(4096, 4096)
  self.fc3 = nn.Linear(4096, 1000)
  # softmax 1 * 1 * 1000
  
 def forward(self, x):
  
  # x.size(0)即为batch_size
  in_size = x.size(0)
  
  out = self.conv1_1(x) # 222
  out = F.relu(out)
  out = self.conv1_2(out) # 222
  out = F.relu(out)
  out = self.maxpool1(out) # 112
  
  out = self.conv2_1(out) # 110
  out = F.relu(out)
  out = self.conv2_2(out) # 110
  out = F.relu(out)
  out = self.maxpool2(out) # 56
  
  out = self.conv3_1(out) # 54
  out = F.relu(out)
  out = self.conv3_2(out) # 54
  out = F.relu(out)
  out = self.conv3_3(out) # 54
  out = F.relu(out)
  out = self.maxpool3(out) # 28
  
  out = self.conv4_1(out) # 26
  out = F.relu(out)
  out = self.conv4_2(out) # 26
  out = F.relu(out)
  out = self.conv4_3(out) # 26
  out = F.relu(out)
  out = self.maxpool4(out) # 14
  
  out = self.conv5_1(out) # 12
  out = F.relu(out)
  out = self.conv5_2(out) # 12
  out = F.relu(out)
  out = self.conv5_3(out) # 12
  out = F.relu(out)
  out = self.maxpool5(out) # 7
  
  # 展平
  out = out.view(in_size, -1)
  
  out = self.fc1(out)
  out = F.relu(out)
  out = self.fc2(out)
  out = F.relu(out)
  out = self.fc3(out)
  
  out = F.log_softmax(out, dim=1)
  return out

补充知识:Pytorch实现VGG(GPU版)

看代码吧~

import torch
from torch import nn
from torch import optim
from PIL import Image
import numpy as np

print(torch.cuda.is_available())
device = torch.device('cuda:0')
path="/content/drive/My Drive/Colab Notebooks/data/dog_vs_cat/"

train_X=np.empty((2000,224,224,3),dtype="float32")
train_Y=np.empty((2000,),dtype="int")
train_XX=np.empty((2000,3,224,224),dtype="float32")

for i in range(1000):
 file_path=path+"cat."+str(i)+".jpg"
 image=Image.open(file_path)
 resized_image = image.resize((224, 224), Image.ANTIALIAS)
 img=np.array(resized_image)
 train_X[i,:,:,:]=img
 train_Y[i]=0

for i in range(1000):
 file_path=path+"dog."+str(i)+".jpg"
 image = Image.open(file_path)
 resized_image = image.resize((224, 224), Image.ANTIALIAS)
 img = np.array(resized_image)
 train_X[i+1000, :, :, :] = img
 train_Y[i+1000] = 1

train_X /= 255

index = np.arange(2000)
np.random.shuffle(index)

train_X = train_X[index, :, :, :]
train_Y = train_Y[index]

for i in range(3):
 train_XX[:,i,:,:]=train_X[:,:,:,i]
# 创建网络

class Net(nn.Module):

 def __init__(self):
  super(Net, self).__init__()
  self.conv1 = nn.Sequential(
   nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.BatchNorm2d(num_features=64, eps=1e-05, momentum=0.1, affine=True),
   nn.MaxPool2d(kernel_size=2,stride=2)
  )
  self.conv2 = nn.Sequential(
   nn.Conv2d(in_channels=64,out_channels=128,kernel_size=3,stride=1,padding=1),
   nn.ReLU(),
   nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.BatchNorm2d(128,eps=1e-5,momentum=0.1,affine=True),
   nn.MaxPool2d(kernel_size=2,stride=2)
  )
  self.conv3 = nn.Sequential(
   nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.BatchNorm2d(256,eps=1e-5, momentum=0.1, affine=True),
   nn.MaxPool2d(kernel_size=2, stride=2)
  )
  self.conv4 = nn.Sequential(
   nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.BatchNorm2d(512, eps=1e-5, momentum=0.1, affine=True),
   nn.MaxPool2d(kernel_size=2, stride=2)
  )
  self.conv5 = nn.Sequential(
   nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
   nn.ReLU(),
   nn.BatchNorm2d(512, eps=1e-5, momentum=0.1, affine=True),
   nn.MaxPool2d(kernel_size=2, stride=2)
  )
  self.dense1 = nn.Sequential(
   nn.Linear(7*7*512,4096),
   nn.ReLU(),
   nn.Linear(4096,4096),
   nn.ReLU(),
   nn.Linear(4096,2)
  )

 def forward(self, x):
  x=self.conv1(x)
  x=self.conv2(x)
  x=self.conv3(x)
  x=self.conv4(x)
  x=self.conv5(x)
  x=x.view(-1,7*7*512)
  x=self.dense1(x)
  return x

batch_size=16
net = Net().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.0005)

train_loss = []
for epoch in range(10):

 for i in range(2000//batch_size):
  x=train_XX[i*batch_size:i*batch_size+batch_size]
  y=train_Y[i*batch_size:i*batch_size+batch_size]

  x = torch.from_numpy(x)  #(batch_size,input_feature_shape)
  y = torch.from_numpy(y)  #(batch_size,label_onehot_shape)
  x = x.cuda()
  y = y.long().cuda()

  out = net(x)

  loss = criterion(out, y)   # 计算两者的误差
  optimizer.zero_grad()    # 清空上一步的残余更新参数值
  loss.backward()     # 误差反向传播, 计算参数更新值
  optimizer.step()     # 将参数更新值施加到 net 的 parameters 上
  train_loss.append(loss.item())

  print(epoch, i*batch_size, np.mean(train_loss))
  train_loss=[]

total_correct = 0
for i in range(2000):
 x = train_XX[i].reshape(1,3,224,224)
 y = train_Y[i]
 x = torch.from_numpy(x)

 x = x.cuda()
 out = net(x).cpu()
 out = out.detach().numpy()
 pred=np.argmax(out)
 if pred==y:
  total_correct += 1
 print(total_correct)

acc = total_correct / 2000.0
print('test acc:', acc)

torch.cuda.empty_cache()

将上面代码中batch_size改为32,训练次数改为100轮,得到如下准确率

利用PyTorch实现VGG16教程

过拟合了~

以上这篇利用PyTorch实现VGG16教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python在不同层级目录import模块的方法
Jan 31 Python
Python贪吃蛇游戏编写代码
Oct 26 Python
python3.6连接MySQL和表的创建与删除实例代码
Dec 28 Python
Python通过调用mysql存储过程实现更新数据功能示例
Apr 03 Python
详解Django 中是否使用时区的区别
Jun 14 Python
Python 十六进制整数与ASCii编码字符串相互转换方法
Jul 09 Python
IntelliJ IDEA安装运行python插件方法
Dec 10 Python
安装PyInstaller失败问题解决
Dec 14 Python
Python 2种方法求某个范围内的所有素数(质数)
Jan 31 Python
详解pandas中利用DataFrame对象的.loc[]、.iloc[]方法抽取数据
Dec 13 Python
Python读取文件夹下的所有文件实例代码
Apr 02 Python
宝塔更新Python及Flask项目的部署
Apr 11 Python
python安装读取grib库总结(推荐)
Jun 24 #Python
Pytorch mask-rcnn 实现细节分享
Jun 24 #Python
在Pytorch中使用Mask R-CNN进行实例分割操作
Jun 24 #Python
OpenCV+python实现实时目标检测功能
Jun 24 #Python
基于Python下载网络图片方法汇总代码实例
Jun 24 #Python
Python 分布式缓存之Reids数据类型操作详解
Jun 24 #Python
PyTorch中model.zero_grad()和optimizer.zero_grad()用法
Jun 24 #Python
You might like
PHP编实现程动态图像的创建代码
2008/09/28 PHP
php初始化对象和析构函数的简单实例
2014/03/11 PHP
php发送html格式文本邮件的方法
2015/06/10 PHP
PHP程序员必须知道的两种日志实例分析
2020/05/14 PHP
jQuery最佳实践完整篇
2011/08/20 Javascript
ASP.NET jQuery 实例4(复制TextBox的文本到本地剪贴板上)
2012/01/13 Javascript
js URL参数的拼接方法比较
2012/02/15 Javascript
jquery的live使用注意事项
2014/02/18 Javascript
JS实现判断滚动条滚到页面底部并执行事件的方法
2014/12/18 Javascript
jQuery简单几行代码实现tab切换
2015/03/10 Javascript
JavaScript制作简易的微信打飞机
2015/03/31 Javascript
jQuery+css实现的时钟效果(兼容各浏览器)
2016/01/27 Javascript
超漂亮的Bootstrap 富文本编辑器summernote
2016/04/05 Javascript
Query常用DIV操作获取和设置长度宽度的实现方法
2016/09/19 Javascript
模板视图和AngularJS之间冲突的解决方法
2016/11/22 Javascript
纯js实现html转pdf的简单实例(推荐)
2017/02/16 Javascript
JavaScript模板引擎应用场景及实现原理详解
2018/12/14 Javascript
vue+layui实现select动态加载后台数据的例子
2019/09/20 Javascript
解决vue项目中页面调用数据 在数据加载完毕之前出现undefined问题
2019/11/14 Javascript
JS表单验证插件之数据与逻辑分离操作实例分析【策略模式】
2020/05/01 Javascript
Python open()文件处理使用介绍
2014/11/30 Python
在Linux上安装Python的Flask框架和创建第一个app实例的教程
2015/03/30 Python
Python爬取三国演义的实现方法
2016/09/12 Python
Django 根据数据模型models创建数据表的实例
2018/05/27 Python
Python可迭代对象操作示例
2019/05/07 Python
解决pycharm上的jupyter notebook端口被占用问题
2019/12/17 Python
Python中filter与lambda的结合使用详解
2019/12/24 Python
python中使用paramiko模块并实现远程连接服务器执行上传下载功能
2020/02/29 Python
基于keras中的回调函数用法说明
2020/06/17 Python
HTML5之SVG 2D入门7—SVG元素的重用与引用
2013/01/30 HTML / CSS
Zipadee-Zip襁褓过渡毯:Sleeping Baby
2018/12/30 全球购物
三年级科学教学反思
2014/01/29 职场文书
自习课吵闹检讨书范文
2014/09/26 职场文书
2015年车间管理工作总结
2015/07/23 职场文书
《角的初步认识》教学反思
2016/02/17 职场文书
七年级作文(600字3篇)
2019/09/24 职场文书