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
| import torch import torch.nn as nn import torch.optim as optim
class RandomForest(nn.Module): def __init__(self): super(RandomForest, self).__init__() self.fc1 = nn.Linear(2, 2) def forward(self, x): x = self.fc1(x) return x
data = torch.tensor([[5.0,0], [4.0,1.0],[3.0,0], [6.0,1.0]], dtype=torch.float32) labels = torch.tensor([0,1,0,1], dtype=torch.long)
model = RandomForest() criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.01)
for epoch in range(100): optimizer.zero_grad() outputs = model(data) loss = criterion(outputs, labels) loss.backward() optimizer.step() if (epoch + 1) % 10 ==0: print(f'Epoch: {epoch + 1}/100, Loss: {loss.item():.4f}')
with torch.no_grad(): outputs = model(data) _, predicted = torch.max(outputs, 1) correct = (predicted==labels).sum().item() print(f'Accuracy: {correct / len(labels * 100)}%')
|