aboutsummaryrefslogtreecommitdiff
path: root/imago/engine/keras/neuralNetwork.py
blob: d0eb4ae5a64e420214b2f678af7713d2b869b93b (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
"""Keras neural network."""

import sys
import os
import os.path

import numpy
from matplotlib import pyplot

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()

    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):
        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=20,
                shuffle=False,
                verbose=2
            )

    def _loadModel(self, modelPath):
        # Load model
        if os.path.isfile(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 oter 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 on the
        played vertex."""
        targets = []
        for move in moves:
            if len(move.nextMoves) == 0:
                continue
            target = numpy.zeros(self.boardSize * self.boardSize, dtype = float)
            target[move.nextMoves[0].getRow() * self.boardSize + move.nextMoves[0].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]
        prediction = numpy.zeros((self.boardSize, self.boardSize))
        for row in range(self.boardSize):
            for col in range(self.boardSize):
                prediction[row][col] = predictionVector[row * self.boardSize + col]
        self.saveHeatmap(prediction)

        # 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 prediction[row][col] > highest and (row, col) in playableVertices:
                    hRow = row
                    hCol = col
                    highest = prediction[row][col]

        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 = 2)

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

        fig, ax = pyplot.subplots()
        im = ax.imshow(data, cmap="YlGn")

        # Show all ticks and label them with the respective list entries
        ax.set_xticks(numpy.arange(cols))
        ax.set_xticklabels(self._getLetterLabels(cols))
        ax.set_yticks(numpy.arange(rows))
        ax.set_yticklabels(numpy.arange(rows, 0, -1))

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

        ax.set_title("Heat map of move likelihood")
        fig.tight_layout()
        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):
        plot_model(
            self.model,
            to_file="model.png",
            show_shapes=True,
            show_dtype=True,
            show_layer_names=True,
            rankdir="TB",
            expand_nested=True,
            dpi=96,
            layer_range=None,
            show_layer_activations=True,
        )