-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNeural Network.py
84 lines (62 loc) · 2.18 KB
/
Neural Network.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# Neural Network to predict double of number
# Instead of getting input from user you can initialize list of multiples input
# Getting input from user
print("Neural Network to predict double of number")
# This will take input from user as string
# and split by space ' ' then convert elements into integer and save elements into list li
li = list(map(int, input("Enter no. separated by space: ").split(" ")))
# Split li into training_data and testing_data
def split_data(li):
length = len(li)
part = int(abs(length/2))
training_data = li[:part]
testing_data = li[part:]
return training_data, testing_data
training_data, testing_data = split_data(li)
# Correct ans
def correct_ans(i):
corr_ans = i*2
return corr_ans
# Neural Network for training
def train_neural_network(ip):
weight = 5
for j in range(1000):
print("##Training## :: ", "Epoch=", j, ", for input=", ip)
pred_ans = ip * weight
cost = corr_ans - pred_ans
weight = weight + 0.1*cost
return pred_ans, weight
def accuracyfun(a, b):
return (a/b)*100
def append_all_weight(weight):
weight_list = []
weight_list.append(weight)
lenght_of_weight_list = len(weight_list)
avg = (sum(weight_list))/lenght_of_weight_list
return avg
# Train
for i in training_data:
corr_ans = correct_ans(i)
pred_ans, weight = train_neural_network(i)
accr = accuracyfun(corr_ans, pred_ans)
print("Accuracy after training data =", i, "is =", accr)
avg = append_all_weight(weight)
file = open("Average Weight.txt", "w")
avg = str(avg)
file.write(avg)
file.close()
# Testing answers with training data using weight generated by neural network
def test_answers(ip):
file = open("Average Weight.txt", "r")
weight = file.read()
file.close()
weight = float(weight)
test_ans = ip * weight
return test_ans
# Using Testing Data to check accuracy
for i in testing_data:
corr_ans = correct_ans(i)
test_ans = test_answers(i)
accr = accuracyfun(corr_ans, test_ans)
print("##Testing## :: ", "For input=", i, "| Correct Ans=", corr_ans, "| Predicted Ans=", test_ans, "| Accuracy=", accr)
print("Final Avg Weight: ", weight)