How to conduct model evaluation in Torch?

Model evaluation in Torch usually involves using a validation or test set to assess the performance of the model. Here is a basic example to demonstrate how model evaluation is done in Torch.

import torch
import torch.nn as nn
import torch.optim as optim

# 定义模型
class SimpleModel(nn.Module):
    def __init__(self):
        super(SimpleModel, self).__init__()
        self.fc = nn.Linear(10, 1)
    
    def forward(self, x):
        return self.fc(x)

# 创建模型实例
model = SimpleModel()

# 加载训练好的模型参数
model.load_state_dict(torch.load('model.pth'))

# 定义评估函数
def evaluate(model, dataloader, criterion):
    model.eval()
    total_loss = 0.0
    total_samples = 0
    
    with torch.no_grad():
        for inputs, targets in dataloader:
            outputs = model(inputs)
            loss = criterion(outputs, targets)
            total_loss += loss.item() * inputs.size(0)
            total_samples += inputs.size(0)
    
    avg_loss = total_loss / total_samples
    return avg_loss

# 创建验证集的数据加载器
val_dataloader = ...

# 定义损失函数
criterion = nn.MSELoss()

# 计算模型在验证集上的平均损失
avg_val_loss = evaluate(model, val_dataloader, criterion)

print('Average validation loss:', avg_val_loss)

In the example above, a simple model called SimpleModel is first defined, then pre-trained model parameters are loaded. Next, an evaluation function called evaluate is defined to calculate the average loss of the model on the validation set. Finally, the model’s performance on the validation set is evaluated by calling the evaluate function, and the average loss value is outputted.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds