我通过 PyTorch 训练一个简单的分类模型并通过 opencv3.3 加载它,但它抛出异常并说
OpenCV 错误:readObject、文件中未实现功能/特性(不支持的 Lua 类型)
/home/ramsus/Qt/3rdLibs/opencv/modules/dnn/src/torch/torch_importer.cpp,
797线
/home/ramsus/Qt/3rdLibs/opencv/modules/dnn/src/torch/torch_importer.cpp:797:
错误:(-213) 函数 readObject 中不支持 Lua 类型
型号定义
class conv_block(nn.Module):
def __init__(self, in_filter, out_filter, kernel):
super(conv_block, self).__init__()
self.conv1 = nn.Conv2d(in_filter, out_filter, kernel, 1, (kernel - 1)//2)
self.batchnorm = nn.BatchNorm2d(out_filter)
self.maxpool = nn.MaxPool2d(2, 2)
def forward(self, x):
x = self.conv1(x)
x = self.batchnorm(x)
x = F.relu(x)
x = self.maxpool(x)
return x
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = conv_block(3, 6, 3)
self.conv2 = conv_block(6, 16, 3)
self.fc1 = nn.Linear(16 * 8 * 8, 120)
self.bn1 = nn.BatchNorm1d(120)
self.fc2 = nn.Linear(120, 84)
self.bn2 = nn.BatchNorm1d(84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size()[0], -1)
x = F.relu(self.bn1(self.fc1(x)))
x = F.relu(self.bn2(self.fc2(x)))
x = self.fc3(x)
return x
该模型仅使用 Conv2d、ReLU、BatchNorm2d、MaxPool2d 和 Linear 层,每个层均由 opencv3.3 支持
我通过state_dict保存它
torch.save(net.state_dict(), 'cifar10_model')
通过c++加载它作为
std::string const model_file("/home/some_folder/cifar10_model");
std::cout<<"read net from torch"<<std::endl;
dnn::Net net = dnn::readNetFromTorch(model_file);
我想我保存模型的方式错误,保存 PyTorch 模型以便使用 OpenCV 加载的正确方法是什么?谢谢
Edit :
我用另一种方式保存模型,但也无法加载
torch.save(net, 'cifar10_model.net')
这是一个错误吗?还是我做错了什么?