-
Notifications
You must be signed in to change notification settings - Fork 0
/
XOR_net.py
48 lines (40 loc) · 1.1 KB
/
XOR_net.py
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
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
EPOCHS_TO_TRAIN = 50000
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(2, 2, True)
self.fc2 = nn.Linear(2, 1, True)
def forward(self, x):
x = F.sigmoid(self.fc1(x))
x = self.fc2(x)
return x
net = Net()
inputs = list(map(lambda s: Variable(torch.Tensor([s])), [
[0, 0],
[0, 1],
[1, 0],
[1, 1]
]))
targets = list(map(lambda s: Variable(torch.Tensor([s])), [
[0],
[1],
[1],
[0]
]))
criterion = nn.MSELoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)
print("Training loop:")
for idx in range(0, EPOCHS_TO_TRAIN):
for input, target in zip(inputs, targets):
optimizer.zero_grad() # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step() # Does the update
if idx % 5000 == 0:
print("Epoch {: >8} Loss: {}".format(idx, loss.data.numpy() ))