这是一个示例代码,用于展示如何使用ResNet18模型进行训练和测试。ResNet18是一种深度学习模型,通常用于图像分类任务。以下是代码示例:

# 导入必要的库
import torch
import torch.nn as nn
import torchvision
from torchvision import transforms
import torchvision.models as models

# 加载ResNet18预训练模型
resnet18 = models.resnet18(pretrained=True)

# 定义数据转换
transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

# 加载示例数据集(这里以ImageNet数据集为例)
dataset = torchvision.datasets.ImageNet(root='./data', split='train', transform=transform)

# 定义数据加载器
dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)

# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(resnet18.parameters(), lr=0.001, momentum=0.9)

# 训练模型
for epoch in range(10):
    for images, labels in dataloader:
        optimizer.zero_grad()
        outputs = resnet18(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

# 测试模型
resnet18.eval()
correct = 0
total = 0
with torch.no_grad():
    for images, labels in dataloader:
        outputs = resnet18(images)
        _, predicted = torch.max(outputs, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

accuracy = correct / total
print("模型准确率: {:.2f}%".format(100 * accuracy))