Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
deeplearningzerotoall
GitHub Repository: deeplearningzerotoall/PyTorch
Path: blob/master/CNN/lab-09-2-xor-nn.py
618 views
1
# Lab 9 XOR
2
import torch
3
4
device = 'cuda' if torch.cuda.is_available() else 'cpu'
5
6
# for reproducibility
7
torch.manual_seed(777)
8
if device == 'cuda':
9
torch.cuda.manual_seed_all(777)
10
11
X = torch.FloatTensor([[0, 0], [0, 1], [1, 0], [1, 1]]).to(device)
12
Y = torch.FloatTensor([[0], [1], [1], [0]]).to(device)
13
14
# nn layers
15
linear1 = torch.nn.Linear(2, 2, bias=True)
16
linear2 = torch.nn.Linear(2, 1, bias=True)
17
sigmoid = torch.nn.Sigmoid()
18
19
# model
20
model = torch.nn.Sequential(linear1, sigmoid, linear2, sigmoid).to(device)
21
22
# define cost/loss & optimizer
23
criterion = torch.nn.BCELoss().to(device)
24
optimizer = torch.optim.SGD(model.parameters(), lr=1) # modified learning rate from 0.1 to 1
25
26
for step in range(10001):
27
optimizer.zero_grad()
28
hypothesis = model(X)
29
30
# cost/loss function
31
cost = criterion(hypothesis, Y)
32
cost.backward()
33
optimizer.step()
34
35
if step % 100 == 0:
36
print(step, cost.item())
37
38
# Accuracy computation
39
# True if hypothesis>0.5 else False
40
with torch.no_grad():
41
predicted = (model(X) > 0.5).float()
42
accuracy = (predicted == Y).float().mean()
43
print('\nHypothesis: ', hypothesis.detach().cpu().numpy(), '\nCorrect: ', predicted.detach().cpu().numpy(), '\nAccuracy: ', accuracy.item())
44