weigths = torch.save(model,'save.pt')
model.load_state_dict(weigths, strict = True) #model.load_state_dict()函数把加载的权重复制到模型的权重中去
这里面有个小坑,strict布尔值默认True,对,默认严格导入。如果对网络结构有所改变,则需要删除相应的权重删除,哎都是为了导入backbone的权重呀,说多了都是泪。
new_weigths = {}
for k, v in weigths.items():
if "fc" in k:
continue
new_weigth[k] = v
model.load_state_dict(weigths, strict = False)
因为我改变了全连接层,所以需要删除相应的权重,再将 strict设置成Fasle
#pragma once
#include <string>
class Infer
{
private:
/* data */
Infer(const std::string& );
public:
Infer(const Infer& instance) = delete;
// (此static是修饰函数)静态成员函数返回静态值
static Infer* get_instance(const std::string& onnx_path){
// 局部静态变量声明是可以定义的,因为静态不属于该类,且多线程初始化也是安全的
static Infer result(onnx_path);
return &result;
}
// 指针的大小是确定的4个字节
Infer* in_ptr;
static Infer jj;
~Infer();
};
#include "learn_leizhongbianliang.h"
#include <iostream>
Infer::Infer(const std::string& o_p)
{
std::cout << "初始化成功" << o_p << std::endl;
}
Infer::~Infer()
{
std::cout << "析构函数" << std::endl;
}