下面是源代码,我用它来加载.pth
文件并进行多类图像分类预测。
model = Classifier() # The Model Class.
model.load_state_dict(torch.load('<PTH-FILE-HERE>.pth'))
model = model.to(device)
model.eval()
Run Code Online (Sandbox Code Playgroud)
# prediction function to test images
def predict(img_path):
image = Image.open(img_path)
resize = transforms.Compose(
[ transforms.Resize((256,256)), transforms.ToTensor()])
image = resize(image)
image = image.to(device)
y_result = model(image.unsqueeze(0))
result_idx = y_result.argmax(dim=1)
print(result_idx)
Run Code Online (Sandbox Code Playgroud)
我.pth
使用 将该文件转换为 ONNX 文件torch.onnx.export
。
现在,如何单独使用 ONNX 文件而不使用该.pth
文件来编写与上述类似的预测脚本?可以这样做吗?
您可以使用 ONNX 运行时。
# !pip install onnx onnxruntime-gpu
import onnx, onnxruntime
model_name = 'model.onnx'
onnx_model = onnx.load(model_name)
onnx.checker.check_model(onnx_model)
image = Image.open(img_path)
resize = transforms.Compose(
[ transforms.Resize((256,256)), transforms.ToTensor()])
image = resize(image)
image = image.unsqueeze(0) # add fake batch dimension
image = image.to(device)
EP_list = ['CUDAExecutionProvider', 'CPUExecutionProvider']
ort_session = onnxruntime.InferenceSession(model_name, providers=EP_list)
def to_numpy(tensor):
return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
# compute ONNX Runtime output prediction
ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(image)}
ort_outs = ort_session.run(None, ort_inputs)
max = float('-inf')
max_index = -1
for i in range(0, len(ort_outs[0][0])):
if(ort_outs[0][0][i] > max):
max = ort_outs[0][0][i]
max_index = i
print(max_index)
Run Code Online (Sandbox Code Playgroud)
您可以按照教程获取详细说明。
通常,使用 onnx 的目的是在不同的框架中加载模型并在那里运行推理,例如 PyTorch -> ONNX -> TensorRT。
归档时间: |
|
查看次数: |
6576 次 |
最近记录: |