-
Notifications
You must be signed in to change notification settings - Fork 1
/
train.py
86 lines (68 loc) · 2.59 KB
/
train.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
import numpy as np
import random
import value_net
trainNum = 0
winList = []
loseList = []
# warn: probMap和posList用makeCompleteProbMap合成,(合成后的)probMap和board用toModelBoard合成
def makeCompleteProbMap(probMap,posList):
for i in range(25):
probMap[i].append(posList[i][0]) # 会改变原来的probMap
probMap[i].append(posList[i][1])
return probMap
class situation:
def __init__(self, board:list, probMap:list, posList:list, otherFeature:list, isWin:bool, log:str):
self.board = np.array(board)
if self.board.shape != (12,5):
print('Error shape: '+log)
self.probMap = np.array(makeCompleteProbMap(probMap,posList))
self.probMap = self.probMap.T
self.otherFeature = np.array(otherFeature)
if isWin:
winList.append(self)
else:
loseList.append(self)
def train(modelObj, epoch:int, batch_size:int, totEpoch:int):
for _ in range(totEpoch):
random.shuffle(winList)
random.shuffle(loseList)
total_size=min(len(winList),len(loseList))
allBoard = []
allOtherFeature = []
allIsWin = []
def add(sample, isWin):
newBoard = value_net.toModelBoard(sample.board, sample.probMap)
allBoard.append(newBoard)
allOtherFeature.append(sample.otherFeature)
allIsWin.append(isWin)
for i in range(total_size): # 每次训练里面抽total_size个(winNum+loseNum)/batch_size个),全过一遍
add(winList[i], 1)
add(loseList[i], 0)
allBoard = np.array(allBoard)
allOtherFeature = np.array(allOtherFeature)
allIsWin = np.array(allIsWin)
modelObj.train(allBoard, allOtherFeature, allIsWin, epoch, batch_size)
global trainNum
modelObj.save_model('model'+str(trainNum)+'.pkl')
trainNum += 1
def test(modelObj, batch_size:int):
allBoard = []
allOtherFeature = []
allIsWin = []
isWin = True
for j in range(batch_size):
if isWin:
sample = random.choice(winList)
else:
sample = random.choice(loseList)
newBoard = value_net.toModelBoard(sample.board, sample.probMap)
allBoard.append(newBoard)
allOtherFeature.append(sample.otherFeature)
allIsWin.append(int(isWin))
isWin = not isWin
allBoard = np.array(allBoard)
allOtherFeature = np.array(allOtherFeature)
allIsWin = np.array(allIsWin)
pos,neg=modelObj.test(allBoard,allOtherFeature,allIsWin)
print(pos, '/', batch_size / 2)
print(neg, '/', batch_size / 2)