This code trains a simple linear model to fit y=2x+1 using SGD optimizer with weight decay to keep weights small. It prints loss each epoch and final weights.
import torch
import torch.nn as nn
import torch.optim as optim
# Simple linear model
class SimpleModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(1, 1)
def forward(self, x):
return self.linear(x)
# Create model
model = SimpleModel()
# Dummy data: y = 2x + 1
x_train = torch.tensor([[1.0], [2.0], [3.0], [4.0]])
y_train = torch.tensor([[3.0], [5.0], [7.0], [9.0]])
# Loss function
criterion = nn.MSELoss()
# Optimizer with weight decay (L2 regularization)
optimizer = optim.SGD(model.parameters(), lr=0.1, weight_decay=0.01)
# Training loop
for epoch in range(10):
optimizer.zero_grad()
outputs = model(x_train)
loss = criterion(outputs, y_train)
loss.backward()
optimizer.step()
print(f"Epoch {epoch+1}, Loss: {loss.item():.4f}")
# Print final weights
for name, param in model.named_parameters():
print(f"{name}: {param.data.flatten().tolist()}")