有没有办法将创建的脚本模块转换torch.jit.script
为跟踪的脚本模块?
使用代码创建模型后
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms
import numpy as np
class TheModelClass(nn.Module):
def __init__(self):
super(TheModelClass, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# Initialize model
model = TheModelClass()
# Initialize optimizer
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
我正在从其脚本中保存脚本模块
m = torch.jit.script(model)
torch.jit.save(m, "model.pt")
保存的模型稍后将被使用,我需要通过示例输入找到它的跟踪。有什么办法吗?当我尝试这样做时,
model=torch.jit.load('model.pt')
dummy=torch.rand((1,3,224,224))
model=torch.jit.trace(model.code, dummy)
以下被抛出,
UserWarning: The input to trace is already a ScriptModule, tracing it is a no-op. Returning the object as is.