要使用PyTorch来预测模型,首先需要加载已经训练好的模型,并准备输入数据。然后使用模型对输入数据进行预测,得到输出结果。
以下是一个使用PyTorch预测模型的简单示例代码:
import torchimport torch.nn as nnimport torch.optim as optim# 定义一个简单的神经网络模型class SimpleNN(nn.Module): def __init__(self): super(SimpleNN, self).__init__() self.fc1 = nn.Linear(10, 5) self.fc2 = nn.Linear(5, 1) def forward(self, x): x = torch.relu(self.fc1(x)) x = self.fc2(x) return x# 加载已经训练好的模型model = SimpleNN()model.load_state_dict(torch.load('model.pth'))model.eval()# 准备输入数据input_data = torch.randn(1, 10)# 使用模型进行预测output = model(input_data)print(output)在上面的示例中,首先定义了一个简单的神经网络模型SimpleNN,然后加载了已经训练好的模型参数model.pth。接着准备输入数据input_data,最后使用模型对输入数据进行预测,得到输出结果output。
需要注意的是,在预测时需要将模型设置为评估模式(model.eval()),这可以确保在预测时不会影响模型的参数。




