python
15 lines · 1 tab
Dr. Elena Vasquez
Apr 2026
1 tab
import torch.nn as nn
from torchvision.models import resnet50, ResNet50_Weights
model = resnet50(weights=ResNet50_Weights.IMAGENET1K_V2)
for parameter in model.parameters():
parameter.requires_grad = False
model.fc = nn.Sequential(
nn.Dropout(0.3),
nn.Linear(model.fc.in_features, 4),
)
for parameter in model.fc.parameters():
parameter.requires_grad = True
1 file · python
Explain with highlit
Transfer learning is the right default when labeled data is limited and time matters. I usually freeze the backbone first, train the head, then selectively unfreeze deeper layers if the domain gap justifies it. This strategy converges faster and is much less brittle than training from scratch.
Related snips
python
import torch.nn as nn
class SmallCNN(nn.Module):
def __init__(self, num_classes: int) -> None:
super().__init__()
self.features = nn.Sequential(
Convolutional neural networks for image classification in PyTorch
pytorch
cnn
computer-vision
by Dr. Elena Vasquez
1 tab
python
import pandas as pd
import torch
from PIL import Image
from torch.utils.data import Dataset, DataLoader
class ProductImageDataset(Dataset):
Custom Datasets and DataLoaders for robust training input pipelines
pytorch
dataloader
dataset
by Dr. Elena Vasquez
1 tab
python
import torch
best_val_loss = float('inf')
for epoch in range(1, num_epochs + 1):
model.train()
A clean PyTorch training loop with validation and checkpoints
pytorch
training-loop
checkpoints
by Dr. Elena Vasquez
1 tab
python
import torch
device = 'cuda' if torch.cuda.is_available() else 'cpu'
features = torch.tensor([[1.0, 2.0], [3.0, 4.0]], requires_grad=True, device=device)
weights = torch.tensor([[0.2], [0.8]], requires_grad=True, device=device)
PyTorch tensor basics and automatic differentiation
pytorch
tensors
autograd
by Dr. Elena Vasquez
1 tab
Share this code
Here's the card — post it anywhere.