温馨提示×

怎么使用pytorch预测模型

小亿
89
2024-04-11 12:23:11
栏目: 深度学习

要使用PyTorch来预测模型,首先需要加载已经训练好的模型,并准备输入数据。然后使用模型对输入数据进行预测,得到输出结果。

以下是一个使用PyTorch预测模型的简单示例代码:

import torch
import torch.nn as nn
import 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()),这可以确保在预测时不会影响模型的参数。

0