aboutsummaryrefslogtreecommitdiff
path: root/imago/engine/keras/neuralNetwork.py
blob: 9d0b853102f40681382a71f6e37dd0469e16e5cd (plain)
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
216
217
218
219
220
"""Keras neural network."""

import sys
import os
import os.path

import numpy
from matplotlib import pyplot

# Disable TensorFlow importing warnings
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

from tensorflow.keras.models import load_model
from tensorflow.keras.utils import plot_model

from imago.data.enums import Player

class NeuralNetwork:

    DEF_BOARD_SIZE = 9

    NETWORK_ID = "neuralNetwork"
    DEFAULT_MODEL_FILE = "models/imagoKerasModel.h5"

    def __init__(self, modelPath="", boardSize=DEF_BOARD_SIZE):
        self.boardSize = boardSize
        self.path = self.DEFAULT_MODEL_FILE
        if modelPath != "":
            self.path = modelPath
        try:
            self.model = self._loadModel(self.path)
        except FileNotFoundError:
            self.model = self._initModel(boardSize)
            #self.saveModelPlot("model.png")

    def _initModel(self, boardSize=DEF_BOARD_SIZE):
        raise NotImplementedError("Tried to directly use NeuralNetwork class. Use one of the subclasses instead.")

    def trainModel(self, games, epochs=20, verbose=2):
        trainMoves = []
        targets = []
        for game in games:
            for move in self._movesToTrainMoves(game):
                trainMoves.append(move)
            for target in self._movesToTargets(game):
                targets.append(target)
        trainMoves = numpy.array(trainMoves)
        targets = numpy.array(targets)
        self.model.fit(
                x=trainMoves,
                y=targets,
                validation_split=0.1,
                batch_size=1,
                epochs=epochs,
                shuffle=False,
                verbose=verbose
            )

    def _loadModel(self, modelPath):
        # Load model
        if os.path.isfile(modelPath) or os.path.isdir(modelPath):
            return load_model(modelPath)
        else:
            raise FileNotFoundError("Keras neural network model file not found at %s"
                    % modelPath)

    def saveModel(self, modelPath=""):
        """Saves the neural network model at the given path."""
        if modelPath != "":
            self.model.save(modelPath)
        else:
            self.model.save(self.path)

    def _movesToTrainMoves(self, moves):
        trainMoves = []
        for move in moves:
            if len(move.nextMoves) == 0:
                continue
            player = move.nextMoves[0].getPlayer()
            board = move.board.board
            trainMove = self._boardToPlayerContext(board, player)
            trainMoves.append(trainMove)
        return trainMoves

    def _boardToPlayerContext(self, board, player):
        """Converts the board to a 3D matrix with two representations of the board, one
        marking the player's stones and the other marking the opponent's stones."""
        boardRows = len(board)
        boardCols = len(board[0])
        contextBoard = numpy.zeros((boardRows, boardCols, 2), dtype = float)
        for row in range(boardRows):
            for col in range(boardCols):
                if board[row][col] != Player.EMPTY:
                    if board[row][col] == player:
                        contextBoard[row][col][0] = 1
                    else:
                        contextBoard[row][col][1] = 1
        return contextBoard

    def _movesToTargets(self, moves):
        """Converts the moves to 2D matrices with values zero except for a one indicating
        the played move."""
        targets = []
        targetsSize = self.boardSize * self.boardSize + 1 # Each vertex + 1 for pass
        for move in moves:
            if len(move.nextMoves) == 0:
                continue
            target = numpy.zeros(targetsSize, dtype = float)
            nextMove = move.nextMoves[0]
            if nextMove.isPass:
                target[-1] = 1
            else:
                target[nextMove.getRow() * self.boardSize + nextMove.getCol()] = 1
            targets.append(target.tolist())
        return targets

    def pickMove(self, gameMove, player):
        """Uses the model's predict function to pick the highest valued vertex to play."""

        predictionVector = self._predict(gameMove, player)[0]
        predictionBoard = numpy.zeros((self.boardSize, self.boardSize))
        for row in range(self.boardSize):
            for col in range(self.boardSize):
                predictionBoard[row][col] = predictionVector[row * self.boardSize + col]
        predictionPass = predictionVector[-1]
        self._saveHeatmap(predictionBoard, predictionPass)

        # Search the highest valued vertex which is also playable
        playableVertices = gameMove.getPlayableVertices()
        highest = -sys.float_info.max
        hRow = -1
        hCol = -1
        for row in range(self.boardSize):
            for col in range(self.boardSize):
                if predictionBoard[row][col] > highest and (row, col) in playableVertices:
                    hRow = row
                    hCol = col
                    highest = predictionBoard[row][col]

        if highest < predictionPass:
            return "pass"
        return [hRow, hCol]

    def _predict(self, gameMove, player):
        board = gameMove.board.board
        sampleBoards = self._boardToPlayerContext(board, player)
        sampleBoards = numpy.array([sampleBoards])
        return self.model.predict(
                x = sampleBoards,
                batch_size = 1,
                verbose = 0)

    def _saveHeatmap(self, data, passChance):
        rows = len(data)
        cols = len(data[0])

        fig, (axBoard, axPass) = pyplot.subplots(1, 2, gridspec_kw={'width_ratios': [9, 1]})
        imBoard = axBoard.imshow(data, cmap="YlGn")
        axPass.imshow([[passChance]], cmap="YlGn", norm=imBoard.norm)

        # Tick and label the board
        axBoard.set_xticks(numpy.arange(cols))
        axBoard.set_xticklabels(self._getLetterLabels(cols))
        axBoard.set_yticks(numpy.arange(rows))
        axBoard.set_yticklabels(numpy.arange(rows, 0, -1))

        # Label the pass chance
        axPass.set_xticks([0])
        axPass.set_yticks([])
        axPass.set_xticklabels(["Pass"])

        # Loop over data dimensions and create text annotations.
        textColorThreshold = data.max() / 2
        for row in range(rows):
            for col in range(cols):
                textColor = ("k" if data[row, col] < textColorThreshold else "w")
                axBoard.text(col, row, "%.2f"%(data[row, col]),
                               ha="center", va="center", color=textColor)

        textColor = ("k" if passChance < textColorThreshold else "w")
        axPass.text(0, 0, "%.2f"%(passChance),
                       ha="center", va="center", color=textColor)

        pyplot.suptitle("Heat map of move likelihood")
        #axBoard.set_title("Heat map of move likelihood")
        fig.tight_layout()

        #pyplot.show()
        pyplot.savefig("heatmaps/heatmap_%s_%s_%d.png" %
                (
                    self.NETWORK_ID,
                    self.path.replace('/','-'),
                    len([file for file in os.listdir("heatmaps")])
                )
            )

    def _getLetterLabels(self, count):
        labels = []
        letter = 'A'
        for _ in range(count):
            labels.append(letter)
            letter = chr(ord(letter) + 1)
            # Skip I
            if letter == 'I':
                letter = 'J'
        return labels

    def saveModelPlot(self, path):
        plot_model(
            self.model,
            to_file=path,
            show_shapes=True,
            show_dtype=True,
            show_layer_names=True,
            rankdir="TB",
            expand_nested=True,
            dpi=96,
            layer_range=None,
            show_layer_activations=True,
        )