در اینجا نمونه ای از تنظیم دقیق مدل ResNet18 در PyTorch برای طبقه بندی دو کلاسه آورده شده است:
import torch
import torchvision.models as models
import torch.nn as nn
import torch.optim as optim
# Load the pretrained ResNet18 model
model = models.resnet18(pretrained=True)
# Freeze all layers except the final layer
for param in model.parameters():
param.requires_grad = False
model.fc.requires_grad = True
# Modify the final layer to have two output classes
model.fc = nn.Linear(512, 2)
# Move the model to GPU if available
model = model.to(device) if torch.cuda.is_available() else model
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.fc.parameters(), lr=0.001, momentum=0.9)
# Train the model
for epoch in range(num_epochs):
# ...
# Calculate the loss and accuracy for each batch
# ...
optimizer.zero_grad()
loss.backward()
optimizer.step()
در این مثال، ابتدا مدل ResNet18 از پیش آموزش دیده را از Torchvision بارگذاری می کنیم. سپس تمام لایه ها به جز لایه نهایی (fc) را با استفاده از requires_grad = False فریز می کنیم. لایه نهایی را با استفاده از nn.Linear (512, 2) تغییر می دهیم تا دو کلاس خروجی داشته باشد. در نهایت، ما تابع تلفات و بهینه ساز را تعریف می کنیم و مدل را با استفاده از مینی دسته داده ها آموزش می دهیم.