Path: blob/master/CNN/lab-09-3-xor-nn-wide-deep.py
620 views
# Lab 9 XOR1import torch23device = 'cuda' if torch.cuda.is_available() else 'cpu'45# for reproducibility6torch.manual_seed(777)7if device == 'cuda':8torch.cuda.manual_seed_all(777)910X = torch.FloatTensor([[0, 0], [0, 1], [1, 0], [1, 1]]).to(device)11Y = torch.FloatTensor([[0], [1], [1], [0]]).to(device)1213# nn layers14linear1 = torch.nn.Linear(2, 10, bias=True)15linear2 = torch.nn.Linear(10, 10, bias=True)16linear3 = torch.nn.Linear(10, 10, bias=True)17linear4 = torch.nn.Linear(10, 1, bias=True)18sigmoid = torch.nn.Sigmoid()1920# model21model = torch.nn.Sequential(linear1, sigmoid, linear2, sigmoid, linear3, sigmoid, linear4, sigmoid).to(device)2223# define cost/loss & optimizer24criterion = torch.nn.BCELoss().to(device)25optimizer = torch.optim.SGD(model.parameters(), lr=1) # modified learning rate from 0.1 to 12627for step in range(10001):28optimizer.zero_grad()29hypothesis = model(X)3031# cost/loss function32cost = criterion(hypothesis, Y)33cost.backward()34optimizer.step()3536if step % 100 == 0:37print(step, cost.item())3839# Accuracy computation40# True if hypothesis>0.5 else False41with torch.no_grad():42predicted = (model(X) > 0.5).float()43accuracy = (predicted == Y).float().mean()44print('\nHypothesis: ', hypothesis.detach().cpu().numpy(), '\nCorrect: ', predicted.detach().cpu().numpy(), '\nAccuracy: ', accuracy.item())4546