参考:教你自己训练的pytorch模型转caffe(二)_pytorch 转caffe 转 tensorrt-CSDN博客
一、安装docker
docker安装和使用参考视频:Docker 简介和安装_哔哩哔哩_bilibili
安装包地址:Dock自己er Desktop: The #1 Containerization Tool for Developers | Docker
二、设置镜像源
打开右上角设置->点击第三行Doceker Engine->复制下面代码至框中->点击Apply&&restart
"registry-mirrors": ["https://registry.docker-cn.com","https://docker.mirrors.ustc.edu.cn"],
三、下载镜像
点击桌面左下角Win图标->搜索Windows PowerShell->右键管理员身份运行,输入:
docker pull yaphets4desmond/brocolli:v1.0
四、创建容器
docker run -it yaphets4desmond/brocolli:v1.0 bash
五、测试是否安装成功
进入文件夹,执行程序
cd /root/brocolli
python test/test_caffe_nets.py
程序执行完成后,进入tmp文件夹,出现转换后模型表示安装成功
cd tmp
ls
六、训练自己的pytorch模型
模型:tudui_net.py
# -*- coding: utf-8 -*-
# 作者:小土堆
# 公众号:土堆碎念
import torch
from torch import nn
# 搭建神经网络
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5, 1, 2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64*4*4, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model(x)
return x
train.py
# -*- coding: utf-8 -*-
# 作者:小土堆
# 公众号:土堆碎念
import torch
import torchvision
from torch.utils.tensorboard import SummaryWriter
from src.model import *
#from model import *
# 准备数据集
from torch import nn
from torch.utils.data import DataLoader
train_data = torchvision.datasets.CIFAR10(root="../data", train=True, transform=torchvision.transforms.ToTensor(),
download=True)
test_data = torchvision.datasets.CIFAR10(root="../data", train=False, transform=torchvision.transforms.ToTensor(),
download=True)
# length 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
# 如果train_data_size=10, 训练数据集的长度为:10
print("训练数据集的长度为:{}".format(train_data_size))
print("测试数据集的长度为:{}".format(test_data_size))
# 利用 DataLoader 来加载数据集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
# 创建网络模型
tudui = Tudui()
# 损失函数
loss_fn = nn.CrossEntropyLoss()
# 优化器
# learning_rate = 0.01
# 1e-2=1 x (10)^(-2) = 1 /100 = 0.01
learning_rate = 1e-2
optimizer = torch.optim.SGD(tudui.parameters(), lr=learning_rate)
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epoch = 10
# 添加tensorboard
writer = SummaryWriter("../logs_train")
for i in range(epoch):
print("-------第 {} 轮训练开始-------".format(i+1))
# 训练步骤开始
tudui.train()
for data in train_dataloader:
imgs, targets = data
outputs = tudui(imgs)
loss = loss_fn(outputs, targets)
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_train_step = total_train_step + 1
if total_train_step % 100 == 0:
print("训练次数:{}, Loss: {}".format(total_train_step, loss.item()))
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 测试步骤开始
tudui.eval()
total_test_loss = 0
total_accuracy = 0
with torch.no_grad():
for data in test_dataloader:
imgs, targets = data
outputs = tudui(imgs)
loss = loss_fn(outputs, targets)
total_test_loss = total_test_loss + loss.item()
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy = total_accuracy + accuracy
print("整体测试集上的Loss: {}".format(total_test_loss))
print("整体测试集上的正确率: {}".format(total_accuracy/test_data_size))
writer.add_scalar("test_loss", total_test_loss, total_test_step)
writer.add_scalar("test_accuracy", total_accuracy/test_data_size, total_test_step)
total_test_step = total_test_step + 1
torch.save(tudui, "tudui_{}.pth".format(i))
print("模型已保存")
writer.close()
运行后得到模型:tudui_4.pth
七、写一个转换脚本
参考:inisis/brocolli at v1.0 (github.com)
的readme
修改对应的模型名字和输入图像大小
run_tudui.py
from bin.pytorch2caffe import Runner # if caffe, use bin.pytorch2caffe, if TensorRT use bin.pytorch2trt;
from custom_models.tudui_net import *
import torch
import torchvision
model=Tudui()# Here, you should use your ownd model
model.load_state_dict(torch.load("./tudui_4.pth",map_location=torch.device('cpu')),)
# input = torch.rand(1,3,32,32)
# output = model(input)
# 13:is the op_set version,use 13 by default
runner = Runner("tuduinet", model, [1, 3, 32, 32], 13,True)
runner.pyotrch_inference()
runner.convert()
runner.caffe_inference() # if caffe, use caffe_inference, if TensorRT use trt_inference;
runner.check_result()
八、将自己的模型复制进容器
把我们的tudui_net.py ,run_tudui.py和tudui_4.pth用dcoker cp 复制到容器的/root/brocolli目录下
docker cp C:/Users/15495/Desktop/tudui_net.py 89679841586dc8a94195f81e26230124a2bac1646737c053648d67494007a186:/root/brocolli/custom_models
docker cp C:/Users/15495/Desktop/run_tudui.py 89679841586dc8a94195f81e26230124a2bac1646737c053648d67494007a186:/root/brocolli/custom_models
docker cp C:/Users/15495/Desktop/tudui_4.pth 89679841586dc8a94195f81e26230124a2bac1646737c053648d67494007a186:/root/brocolli/custom_models
前面地址改为自己模型地址位置,后面数字改为容器ID。
九、执行脚本
重新进入容器
docker exec -it 89679841586dc8a94195f81e26230124a2bac1646737c053648d67494007a186 bash
在brocolli目录下运行run_tudui.py
python custom_models/run_tudui.py
运行成功
将tmp文件夹下tuduinet.prototxt和tuduinet.caffemodel复制出来
docker cp 89679841586dc8a94195f81e26230124a2bac1646737c053648d67494007a186:/root/brocolli/tmp C:/Users/15495/Desktop/Mymodels
成功
十、遇到的问题
1.urllib.error.HTTPError: HTTP Error 403: rate limit exceeded
解决办法:
参考:BUG--urllib.error.HTTPError: HTTP Error 403: rate limit exceeded-CSDN博客
在models.py文件前添加一行代码
torch.hub._validate_not_a_forked_repo=lambda a,b,c: True