1.首先确定自己电脑上的pytorch版本,然后下载合适的libtorch版本。
使用libtorch调用c++接口,要保证下载的libtorch的版本和pytorch的版本对应
至少使用低版本的pytorch和高版本的libtorch是没法成功的。反过来是可以的:即高版本的pytorch和低版本的libtorch。
各个版本的libtorch下载参考地址
2.训练
训练的时候推荐只保存模型参数,我之前是保存整个模型但是一值转换不成功。
训练完后会保存一个xxx.pth文件,然后就可以转换这个文件了。
3.转换
需要将训练好的xxx.pth文件转换成xxx.pt文件。直接贴代码(每个人的需求不一样,根据自己的需求改)
from PIL import Image
import torch
from torchvision import transforms,models
import torch.nn as nn
from efficientnet_pytorch import EfficientNet
from torch.autograd import Variable
def Transfer_cup_model():
#这个代码使用的前提是需要在你的虚拟环境中下载好EfficientNet的包 ( pip install efficientnet_pytorch)
model = EfficientNet.from_name('efficientnet-b5')
model.set_swish(memory_efficient=False)
num_ftrs = model._fc.in_features
model._fc = nn.Linear(num_ftrs, 6) #我训练的是6类,对应着自己的类别数改
# model.load_state_dict(torch.load('Garbage/each_model/epoch_29.pth'))
model.load_state_dict(
{k.replace('module.', ''): v for k, v in torch.load('Garbage/each_model/epoch_29.pth').items()})
model.eval()
model.cpu()
example = torch.randn(1, 3, 456, 456)
with torch.no_grad():
traced_script_module = torch.jit.trace(model, example)
traced_script_module.save('model-cpu.pt')
def Transfer_GPU_model():
model = EfficientNet.from_name('efficientnet-b5')
model.set_swish(memory_efficient=False)
num_ftrs = model._fc.in_features
model._fc = nn.Linear(num_ftrs, 6)
# model.load_state_dict(torch.load('Garbage/each_model/epoch_29.pth'))
#我是用四个GPU并行训练的,需要加这一句,如果是单GPU可以用上面的一句
model.load_state_dict(
{k.replace('module.', ''): v for k, v in torch.load('Garbage/each_model/epoch_29.pth').items()})
model.eval()
# model = torch.load('Garbage/epoch_29.pth')
# model = torch.nn.DataParallel(model).cuda()
if torch.cuda.is_available():
model.cuda()
# 转libtorch
example = torch.randn(1, 3, 456, 456).cuda()
with torch.no_grad():
traced_script_module = torch.jit.trace(model, example)
traced_script_module.save('model-gpu.pt')
def Transfer_onnx_model():
model = EfficientNet.from_name('efficientnet-b5')
model.set_swish(memory_efficient=False)
num_ftrs = model._fc.in_features
model._fc = nn.Linear(num_ftrs, 6)
# model.load_state_dict(torch.load('Garbage/each_model/epoch_29.pth'))
model.load_state_dict(
{k.replace('module.', ''): v for k, v in torch.load('Garbage/each_model/epoch_29.pth').items()})
model.eval()
# model = torch.load('Garbage/epoch_29.pth')
# model = torch.nn.DataParallel(model).cuda()
if torch.cuda.is_available():
model.cuda()
#转onnx
dummy_input1 = torch.randn(1, 3, 456, 456).cuda()
torch.onnx.export(model,dummy_input1,"Efficient.onnx",export_params=True, verbose=True, training=False)
def Transfer_type(Type):
if Type == 0:
Transfer_cup_model() #cpu模型
elif Type == 1:
Transfer_GPU_model() #Gpu模型
elif Type == 2:
Transfer_onnx_model() #onnx模型(GPU)
else:
print("The model of this type cann't transfer")
def main():
Transfer_type(1)
if __name__ == '__main__':
main()
4.调用
网上由很多教程,写的很详细 参考。
其实就是调用下载好的libtorch库,跟调用opencv库一样,VS中包含目录、库目录、依赖项 添加好就行(不清楚添加libtorch的哪些包都,都添加进去也行)。
数据预处理和模型使用可以参考这篇博客: 数据预处理及模型使用