Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
deeplearningzerotoall
GitHub Repository: deeplearningzerotoall/PyTorch
Path: blob/master/CNN/lab-09-1-xor.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
linear = torch.nn.Linear(2, 1, bias=True)
16
sigmoid = torch.nn.Sigmoid()
17
18
# model
19
model = torch.nn.Sequential(linear, sigmoid).to(device)
20
21
# define cost/loss & optimizer
22
criterion = torch.nn.BCELoss().to(device)
23
optimizer = torch.optim.SGD(model.parameters(), lr=1)
24
25
for step in range(10001):
26
optimizer.zero_grad()
27
hypothesis = model(X)
28
29
# cost/loss function
30
cost = criterion(hypothesis, Y)
31
cost.backward()
32
optimizer.step()
33
34
if step % 100 == 0:
35
print(step, cost.item())
36
37
# Accuracy computation
38
# True if hypothesis>0.5 else False
39
with torch.no_grad():
40
predicted = (model(X) > 0.5).float()
41
accuracy = (predicted == Y).float().mean()
42
print('\nHypothesis: ', hypothesis.detach().cpu().numpy(), '\nCorrect: ', predicted.detach().cpu().numpy(), '\nAccuracy: ', accuracy.item())
43