-
Notifications
You must be signed in to change notification settings - Fork 0
/
MachineLearning.py
215 lines (183 loc) · 7.93 KB
/
MachineLearning.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import random
from copy import copy, deepcopy
from model.Board import Board
from enum import Enum
from model.SquareType import SquareType
import time
from model.AIPlayer import AIPlayer
class GameFeatureState(Enum):
Win = 'w'
Equal = 'e'
Lose = 'l'
class MachineLearningFeatures:
def __init__(self):
self.featureRange = 50
self.numberOfFeatures = 7
self.numberOfTeams = 7
self.crossOverRate = 0.8
self.mutationRate = 0.3
self.geneticFeatures = []
self.generation = 0
def randomBeginingPopulation(self):
for i in range(0, self.numberOfTeams):
temp = []
for j in range(0, self.numberOfFeatures):
temp.append(random.randint(-self.featureRange, self.featureRange))
self.geneticFeatures.append(temp)
# does cross over
def doCrossOver(self, feature1, feature2):
crossOverPoint1 = random.randint(0, self.numberOfFeatures - 1)
crossOverPoint2 = random.randint(crossOverPoint1, self.numberOfFeatures - 1)
while crossOverPoint2 - crossOverPoint1 == self.numberOfFeatures - 1:
crossOverPoint2 = random.randint(crossOverPoint1, self.numberOfFeatures - 1)
tempFeature1 = deepcopy(feature1)
tempFeature2 = deepcopy(feature2)
for i in range(crossOverPoint1, crossOverPoint2):
tempFeature1[i] = (feature2[i])
tempFeature2[i] = (feature1[i])
return [tempFeature1, tempFeature2]
# does mutation
def doMutation(self, feature):
randIndex = random.randint(0, self.numberOfFeatures - 1)
randFeatureNum = random.randint(-self.featureRange, self.featureRange)
feature[randIndex] = randFeatureNum
randIndex2 = randIndex
while randIndex2 == randIndex:
randIndex2 = random.randint(0, self.numberOfFeatures - 1)
randFeatureNum2 = random.randint(-self.featureRange, self.featureRange)
feature[randIndex2] = randFeatureNum2
return feature
def doGeneticAlgorithm(self):
allChilds = deepcopy(self.geneticFeatures)
for ind1, feature1 in enumerate(self.geneticFeatures):
for ind2, feature2 in enumerate(self.geneticFeatures):
if ind1 <= ind2:
continue
crossOverRandNum = random.uniform(0, 1)
childs = []
if crossOverRandNum <= self.crossOverRate:
childs = self.doCrossOver(feature1, feature2)
for iChild in range(0, 2):
mutationRandNum = random.uniform(0, 1)
if mutationRandNum <= self.mutationRate:
childs[iChild] = self.doMutation(childs[iChild])
self.mutationRate *= 0.95
allChilds.append(childs[0])
allChilds.append(childs[1])
self.geneticFeatures = allChilds
def makeAIPlayerFeatures(self, feature):
squareScores = [[120, -20, 20, 5, 5, 20, -20, 120],
[-20, -40, -5, -5, -5, -5, -40, -20],
[ 20, -5, 15, 3, 3, 15, -5, 20],
[ 5, -5, 3, 3, 3, 3, -5, 5],
[ 5, -5, 3, 3, 3, 3, -5, 5],
[ 20, -5, 15, 3, 3, 15, -5, 20],
[-20, -40, -5, -5, -5, -5, -40, -20],
[120, -20, 20, 5, 5, 20, -20, 120]]
for ind1, row in enumerate(squareScores):
for ind2, f in enumerate(row):
if f == 120:
squareScores[ind1][ind2] = feature[0]
if f == 20:
squareScores[ind1][ind2] = feature[1]
if f == 5:
squareScores[ind1][ind2] = feature[2]
if f == 3:
squareScores[ind1][ind2] = feature[3]
if f == -5:
squareScores[ind1][ind2] = feature[4]
if f == -20:
squareScores[ind1][ind2] = feature[5]
if f == -40:
squareScores[ind1][ind2] = feature[6]
return squareScores
def doGame(self, feautre1, feautre2):
boardGame = Board()
while not boardGame.isEnded:
player1 = AIPlayer(boardGame, SquareType.BLACK, self.makeAIPlayerFeatures(feautre1))
item = player1.getNextMove()
boardGame.move(item[0], item[1])
player2 = AIPlayer(boardGame, SquareType.WHITE, self.makeAIPlayerFeatures(feautre2))
item = player2.getNextMove()
if not boardGame.isEnded:
boardGame.move(item[0], item[1])
result = []
if boardGame.blackCount < boardGame.whiteCount:
result.append(GameFeatureState.Lose)
result.append(GameFeatureState.Win)
elif boardGame.blackCount > boardGame.whiteCount:
result.append(GameFeatureState.Win)
result.append(GameFeatureState.Lose)
else:
result.append(GameFeatureState.Equal)
result.append(GameFeatureState.Equal)
return result
def filterGeneticFeatures(self, scores):
tempFeature = []
for ind, score in enumerate(scores):
tempFeature.append((score, ind))
tempFeature.sort(key= lambda x: x[0])
tempChance = []
listLen = len(tempFeature)
divisorNum = (listLen * (listLen - 1)) / 2
if divisorNum == 0:
return []
tmpCh = 0
for index in range(0, len(tempFeature)):
tmpCh = (index + 1) / divisorNum
tempChance.append(tmpCh)
cum_chance = tuple(tempChance)
res = []
resSize = 0
while resSize < self.numberOfTeams:
randomItem = random.choices(tempFeature, cum_weights = cum_chance, k = 1)
if randomItem[0][1] not in res:
res.append(randomItem[0][1])
resSize += 1
tmpGeneticFeatures = []
for ind in res:
tmpGeneticFeatures.append(self.geneticFeatures[ind])
self.geneticFeatures = tmpGeneticFeatures
def runGenetic(self):
self.doGeneticAlgorithm()
score = [0 for _ in range(0, len(self.geneticFeatures))]
numberOfGame = len(self.geneticFeatures) * (len(self.geneticFeatures) - 1) / 2
for ind1, feautre1 in enumerate(self.geneticFeatures):
for ind2, feautre2 in enumerate(self.geneticFeatures):
if ind1 <= ind2:
continue
print(f"Generation: {self.generation}, Number of games left: {numberOfGame} ", end='')
numberOfGame -= 1
start = time.time()
res = self.doGame(feautre1, feautre2)
end = time.time()
print(f"Time: {end - start}")
if (res[0] == GameFeatureState.Equal):
score[ind1] += 1
score[ind2] += 1
elif (res[0] == GameFeatureState.Win):
score[ind1] += 3
elif (res[0] == GameFeatureState.Lose):
score[ind2] += 3
self.filterGeneticFeatures(score)
for row in self.geneticFeatures:
print(row)
ml = MachineLearningFeatures()
ml.randomBeginingPopulation()
for i in range(0, 15):
ml.generation += 1
start = time.time()
ml.runGenetic()
end = time.time()
with open('log.txt', 'a') as f:
f.write(f"Generation: {ml.generation}\n")
f.write(f"Time: {(end - start) / 60} minutes\n")
f.write(f"Features:\n")
for item in ml.geneticFeatures:
f.write("%s\n" % item)
with open('hidden/log.txt', 'a') as f:
f.write(f"Generation: {ml.generation}\n")
f.write(f"Time: {(end - start) / 60} minutes\n")
f.write(f"Features:\n")
for item in ml.geneticFeatures:
f.write("%s\n" % item)