1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset
x_train = torch.randn(1000, 1) y_train = 2 * x_train + 1 + torch.randn(1000, 1)
x_val = x_train[:500] y_val = y_train[:500] x_train = x_train[:500] y_train = y_train[:500]
train_data = TensorDataset(x_train, y_train) val_data = TensorDataset(x_val, y_val) train_loader = DataLoader(train_data, batch_size=32) val_loader = DataLoader(val_data, batch_size=32)
class LinearModel(nn.Module): def __init__(self): super(LinearModel, self).__init__()
self.linear = nn.Linear(1, 1)
def forward(self, x): return self.linear(x)
model = LinearModel()
criterion = nn.MSELoss() optimizer = optim.SGD(model.parameters(), lr=0.01)
for epoch in range(10): for inputs, targets in train_loader: optimizer.zero_grad() prediction = model(inputs) loss = criterion(prediction, targets) loss.backward() optimizer.step() with torch.no_grad(): val_loss = 0.0 for inputs, targets in val_loader: preds = model(inputs) val_loss = criterion(preds, targets).item() * len(inputs) val_loss /= len(val_data) print(f'Epoch {epoch + 1}, validation Loss: {val_loss:.4f}')
|