import torch import torch.nn as nn
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.hidden = nn.Linear(50, 100) self.relu = nn.ReLU() self.output = nn.Linear(100, 2)
def forward(self, x): x = self.hidden(x) x = self.relu(x) x = self.output(x) return x
model = Net()
criterion = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
inputs = torch.randn(100, 50) labels = torch.randint(0, 2, (100,))
for epochs in range(100): outputs = model(inputs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() print('Loss:', loss.item())
test_inputs = torch.randn(5, 50)
outputs = model(test_inputs)
_, predicted = torch.max(outputs, 1)
print('Predicted:', predicted)
|