MobileNetv1训练猫狗图片
MobileNetv1是谷歌提出的轻量级的卷积神经网络(同VGG相比),它主要采用了深度可分离的卷积,从而大大降低了参数数目和网络的计算量。深度可分离卷积包括两个部分,分别是Depthwise卷积和Pointwise卷积。
Depthwise卷积
主要进行特征的提取(filting),输入特征图为(D,D,C),则卷积核为(K,K,C),在进行卷积运算时,每个通道是独立的,即(D,D,Ci)特征图和(K,K,Ci)特征图进行卷积,结果直接作为输出特征图的第Ci个通道。
Pointwise卷积
主要进行特征的组合(combining),可以理解为1x1的标准卷积
MobileNet v1结构
如下图
Pytorch代码
import torch
from torch import nn
from torch import optimfrom PIL import Image
import numpy as npprint(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,:,:,:] = imgtrain_Y[i] = 0for 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, :, :, :] = imgtrain_Y[i+1000] = 1train_X /= 255index = 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__()def conv_bn(inp, oup, stride): # 第一层传统的卷积:conv3*3+BN+ReLUreturn nn.Sequential(nn.Conv2d(inp, oup, 3, stride, 1, bias=False),nn.BatchNorm2d(oup),nn.ReLU(inplace=True))def conv_dw(inp, oup, stride): # 其它层的depthwise convolution:conv3*3+BN+ReLU+conv1*1+BN+ReLUreturn nn.Sequential(nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False),nn.BatchNorm2d(inp),nn.ReLU(inplace=True),nn.Conv2d(inp, oup, 1, 1, 0, bias=False),nn.BatchNorm2d(oup),nn.ReLU(inplace=True),)self.model = nn.Sequential(conv_bn(3, 32, 2), # 第一层传统的卷积conv_dw(32, 64, 1), # 其它层depthwise convolutionconv_dw(64, 128, 2),conv_dw(128, 128, 1),conv_dw(128, 256, 2),conv_dw(256, 256, 1),conv_dw(256, 512, 2),conv_dw(512, 512, 1),conv_dw(512, 512, 1),conv_dw(512, 512, 1),conv_dw(512, 512, 1),conv_dw(512, 512, 1),conv_dw(512, 1024, 2),conv_dw(1024, 1024, 1),nn.AvgPool2d(7),)self.fc = nn.Linear(1024, 2) # 全连接层def forward(self, x):x = self.model(x)x = x.view(-1, 1024)x = self.fc(x)return xbatch_size = 16
net = Net().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.0005)train_loss = []
precision = 0
for epoch in range(50):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)pred = torch.argmax(out,dim=1)precision = y.eq(pred).sum().float().item()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), precision/batch_size)train_loss = []precision = 0total_correct = 0
for i in range(200):x = train_XX[i*10:i*10+10]y = train_Y[i*10:i*10+10]x = torch.from_numpy(x)y = torch.from_numpy(y)x = x.cuda()y = y.long().cuda()out = net(x)pred = torch.argmax(out,dim=1)total_correct += y.eq(pred).sum().float().item()acc = total_correct / 2000.0
print('test acc:', acc)torch.cuda.empty_cache()
训练结果
MobileNetv1训练猫狗图片相关推荐
- 使用预训练的卷积神经网络(猫狗图片分类)
本次所用数据来自ImageNet,使用预训练好的数据来预测一个新的数据集:猫狗图片分类.这里,使用VGG模型,这个模型内置在Keras中,直接导入就可以了. from keras.applicatio ...
- python狗图像识别_TensorFlow卷积神经网络之使用训练好的模型识别猫狗图片
本文是Python通过TensorFlow卷积神经网络实现猫狗识别的姊妹篇,是加载上一篇训练好的模型,进行猫狗识别 本文逻辑: 我从网上下载了十几张猫和狗的图片,用于检验我们训练好的模型. 处理我们下 ...
- PyTorch搭建预训练AlexNet、DenseNet、ResNet、VGG实现猫狗图片分类
目录 前言 AlexNet DensNet ResNet VGG 前言 在之前的文章中,利用一个简单的三层CNN猫狗图片分类,正确率不高,详见: CNN简单实战:PyTorch搭建CNN对猫狗图片进行 ...
- CNN之从头训练一个猫狗图片分类模型
猫狗图片下载地址: 链接:https://pan.baidu.com/s/1l1AnBgkAAEhh0vI5_loWKw 提取码:2xq4 说明:大概有816M大小,分为train和test,trai ...
- python 图片比较 猫_TensorFlow卷积神经网络之使用训练好的模型识别猫狗图片
本文逻辑: 我从网上下载了十几张猫和狗的图片,用于检验我们训练好的模型. 处理我们下载的图片 加载模型 将图片输入模型进行检验 代码如下: #coding=utf-8 import tensorflo ...
- kaggle(一)训练猫狗数据集
记录第一次使用kaggle训练猫狗数据集 import os import shutil os.listdir('../input/train/train') base_dir = './cat_do ...
- ResNet-50 训练猫狗分类
ResNet-50 训练猫狗分类 1.ResNet网络 2.猫狗数据 3.训练 4.测试 这里介绍一下怎么搭建ResNet网络,并说明一下残差网络的结构,并使用ResNet来训练一个二分类问题 1.R ...
- 使用深度学习分类猫狗图片
使用深度学习分类猫狗图片 前言 一.下载数据 二.构建网络 三.数据预处理 四.使用数据增强 总结 前言 本文将介绍如何使用较少的数据从头开始训练一个新的深度学习模型.首先在一个2000个训练样本上训 ...
- Top2:CNN 卷积神经网络实现猫狗图片识别二分类
Top2:CNN 卷积神经网络实现猫狗图片识别二分类 系统:Windows10 Professional 环境:python=3.6 tensorflow-gpu=1.14 ```python &qu ...
最新文章
- Go会接替Java,成为下一个企业级编程语言吗?
- windows下安装服务注册Consul
- php 工厂模式封装数据库,PHP设计模式之工厂模式
- 对于Activity的理解
- 语言ppt课件猜拳_八年级语文上册第22课 孟子三章讲解及课件下载
- [渝粤教育] 西南科技大学 婚姻家庭继承法 在线考试复习资料
- 【JDBC】JDBC的使用(数据库的增删改查询)
- 基础才是王道——TCP/IP详解学习笔记
- SPSS——描述性统计分析——列联表
- python列表数字比大小教案_幼儿园大班数学教案数字比大小
- 【论文阅读】Zero-Resource Knowledge-Grounded Dialogue Generation
- 南卡租房之Park Circle
- Markdown字体大小颜色、大小、背景色 (二)
- 使用OpenCV实现运动背景的重建
- 程序员如何营销自己?
- Qt 添加第三方字体库
- 中国余数定理练习题及规律总结,超强总结
- PLC软件测试方法,工业控制系统中PLC的相关测试方法
- OpenStack(Queens版)高集群-3.高可用配置(pacemakerhaproxy)
- 2020年中国首席营销官调查:“宅经济”助推企业加速内容营销布局