简体   繁体   English

如何使用经过训练的 pytorch model 进行预测

[英]How to use trained pytorch model for prediction

I have a pretrained pytorch model which is saved in.pth format.我有一个预训练的 pytorch model ,它以.pth 格式保存。 How can i use it for prediction on new dataset in a separate python file.我如何使用它来预测单独的 python 文件中的新数据集。

I need a detailed guide.我需要一份详细的指南。

To use a pretrained model you should load the state on a new instance of the architecture as explained in the docs/tutorials :要使用预训练的 model,您应该在架构的新实例上加载 state,如文档/教程中所述:

Here models is imported beforehand:这里models是预先导入的:

model = models.vgg16()
model.load_state_dict(torch.load('model_weights.pth')) # This line uses .load() to read a .pth file and load the network weights on to the architecture.
model.eval() # enabling the eval mode to test with new samples.

If you are using a custom architecture you only need to change the first line.如果您使用的是自定义架构,您只需要更改第一行。

model = MyCustomModel()

After enabling the eval mode, you can proceed as follows:启用eval模式后,您可以进行如下操作:

  • Load your data into a Dataset instance and then in a DataLoader .将数据加载到Dataset实例中,然后加载到DataLoader中。
  • Make your predictions with the data.用数据做出你的预测。
  • Calculate metrics on the results.计算结果的指标。

More about Dataset and DataLoader here .更多关于DatasetDataLoader 的信息

Well for prediction theres something called forward pass对于预测来说,有一种叫做前向传播的东西

import torch
from torch_model import Model # Made up package

device = torch.device('cpu' if torch.cuda.is_available() else 'gpu')

model = Model()
model.load_state_dict(torch.load('weights.pt'))

model = model.to(device) # Set model to gpu
model.eval();

inputs = torch.random.randn(1, 3, 224, 224) # Dtype is fp32
inputs = inputs.to(device) # You can move your input to gpu, torch defaults to cpu

# Run forward pass
with torch.no_grad():
  pred = model(inputs)

# Do something with pred
pred = pred.detach().cpu().numpy() # remove from computational graph to cpu and as numpy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM