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 58 59
| import torch import torch.nn as nn import torch.optim as optimxw from torch.utils.data import DataLoader, TensorDataset
features = torch.randn(100, 10) targets = torch.randint(0, 2, (100,))
dataset = TensorDataset(features, targets)
train_loader = DataLoader(dataset=dataset, batch_size=10, shuffle=True)
class SimpleModel(nn.Module): def __init(self): super(SimpleModel, self).__init__() self.layer = nn.Linear(10, 2) def forward(self, x): return self.layer(x)
model = SimpleModel() criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.01)
num_epochs = 3 for epoch in range(num_epochs): model.train() train_loss = 0.0 for inputs, targets in train_loader: optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() train_loss += loss.item() * inputs.size(0) train_loss /= len(train_loader.dataset) print(f'Epoch {epoch + 1}, Train Loss: {train_loss:.4f}') model.eval() valid_loss = 0.0 with torch.no_grad(): for inputs, targets in train_loader: outputs = model(inputs) loss = criterion(outputs, targets) valid_loss += loss.item() * inputs.size(0) valid_loss /= len(train_loader.dataset) print(f'Epoch {epoch + 1} Validation Loss: {valid_loss:.4f}')
|