-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBasicNN.py
67 lines (55 loc) · 2.04 KB
/
BasicNN.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from utility_functions import *
def train_BNN(train_X, train_Y, epoch, lr):
np.random.seed(75)
weights = np.random.rand(9,1)
x = weights
bias = np.random.rand(1)
errors = []
iterations = []
for i in range(epoch):
iterations.append(i)
inputs = train_X
XW = np.dot(inputs, weights)+ bias
z = sigmoid(XW)
error = z - train_Y # predicted - actual output
errors.append(float(error.sum())/len(error)) # average error
dcost = error
dpred = sigmoid_derivative(z)
z_del = dcost * dpred
inputs = train_X.T # transpose of the matrix
weights = weights - lr*np.dot(inputs, z_del)
for num in z_del:
bias = bias - lr*num
w_b = {'weight':weights, 'bias':bias, 'initial weight':x, 'error':errors, 'iterations':iterations}
return w_b
def test_BNN(test_X, test_Y, weights, bias):
results = {'actual':[], 'predicted':[], 'accuracy':0}
for i in range(len(test_X)): # prediction
p = sigmoid(np.dot(test_X[i], weights) + bias) # predicted value, np array
p = float(np.extract(True, p))
if p <= 0.5:
p = 0
else:
p = 1
results['predicted'].append(p)
for i in range(len(test_Y)):
y = int(np.extract(True, test_Y[i]))
results['actual'].append(y)
if len(results['actual']) == len(results['predicted']):
correct = 0
for i in range(len(results['actual'])):
if results['actual'][i] == results['predicted'][i]:
correct+=1
results['accuracy'] = (correct/len(results['actual']))*100
return results
def predict_BNN(record, w, b):
result = sigmoid(np.dot(record, w) + b)
result = float(np.extract(True, result))
if result <= 0:
result = 0
else:
result = 1
return result