-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
98 lines (75 loc) · 2.71 KB
/
model.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
from layer import *
import json
class Model():
def __init__(self, coef):
self.coef = coef
self.inputLayer = None
self.output = None
def add(self, layerSize):
if not self.inputLayer:
self.inputLayer = InputLayer(layerSize)
self.output = self.inputLayer
else:
newLayer = Layer(layerSize, self.output)
self.output.add(newLayer)
self.output = newLayer
def saveConfig(self, path):
config = {}
layers = []
layer = self.inputLayer
position = 0
while layer:
configLayer = {}
configLayer['layer'] = position
configLayer['activation'] = layer.activationType
configLayer['size'] = layer.size
if layer.prevLayer:
listWeights = []
for i in range(layer.size):
listWeights.append(list(layer.weights[i]))
configLayer['weights'] = listWeights
position += 1
layers.append(configLayer)
layer = layer.nextLayer
config['layers'] = layers
config['coef'] = self.coef
configFile = open(path, 'w')
configFile.write(json.dumps(config, indent = 4))
def loadConfig(self, path):
self.inputLayer = None
self.output = None
configFile = open(path, 'r')
configJson = configFile.read()
config = json.loads(configJson)
configFile.close()
self.coef = config['coef']
layersConfig = config['layers']
self.add(layersConfig[0]['size'])
for i in range(1, len(layersConfig)):
size = layersConfig[i]['size']
self.add(size)
weights = layersConfig[i]['weights']
self.output.setWeights(weights)
def run(self, inputs):
return self.inputLayer.activate(inputs)
def train(self, trainSet, maxEpoch):
for i in range(maxEpoch):
print(i)
results = []
coef = self.coef
run = self.run
updateWeights = self.output.updateWeights
for k in range(len(trainSet)):
res = self.run(trainSet[k][0])
updateWeights(trainSet[k][1], coef)
pred = max(res)
number = res.index(pred)
label = trainSet[k][1].index(1)
if number == label:
results.append(1)
else:
results.append(0)
correct = list(filter(lambda x: x == 1, results))
diff = len(results) - len(correct)
coef = diff / len(results)
print("Accuracy " + str((1 - coef) * 100) + "%")