Beispiel #1
0
def stat1():
    from util.corpus import MyCorpus
    from eval.evaluation import evaluate

    dataSetName = 'BBN'
    trainFilePath = 'data/{}/train.json'.format(dataSetName)
    testFilePath = 'data/{}/test.json'.format(dataSetName)

    corpus = MyCorpus(filePathList=[trainFilePath, testFilePath])
    X_train, y_train = corpus.loadFile(filePath=trainFilePath)
    X_test, y_test = corpus.loadFile(filePath=testFilePath)

    y = np.load('10_24_17_32/epoch17.npy')
    ground = MyCorpus.oneHotDecode(y_test)

    scores = []
    outputFile = open('a.txt', 'w', encoding='utf-8')
    for threshold in np.arange(0.3, 0.6, 0.01):
        y1 = MyCorpus.threshold(y, threshold)
        y1 = MyCorpus.oneHotDecode(y1)
        score = evaluate(y1, ground)
        scores.append((threshold, score))
        outputFile.write('%.3f\t%.3f\t%.3f\t%.3f\n' %
                         (threshold, score[0], score[3], score[6]))

    print(scores)
    print('Max: ' +
          str(max(scores, key=lambda kv: sum([kv[1][0], kv[1][3], kv[1][6]]))))
    outputFile.close()
def ab_min(board: chess.Board, alpha: int, beta: int, depth: int,
           tt: {}) -> int:
    """
    Min node of an alpha/beta tree, it calls ab_max until depth == 0
    :param board: the chess board
    :param alpha: alpha
    :param beta: beta
    :param depth: depth
    :param tt: transpositions tables
    :return: evaluation
    """
    if depth == 0 or board.is_game_over():
        return ev.evaluate(board)
    best_eval = math.inf
    for coup in board.legal_moves:
        board.push(coup)
        h = zb.zobrist_hash(board)
        if h in tt:
            it: HashItem = tt[h]
            if it.depth <= depth:
                ab = tt[h].evaluation
            else:
                ab = ab_max(board, alpha, beta, depth - 1, tt)
        else:
            ab = ab_max(board, alpha, beta, depth - 1, tt)
        board.pop()
        best_eval = min(best_eval, ab)
        if best_eval <= alpha:
            tt[h] = HashItem(h, depth, best_eval, (alpha, beta))
            return best_eval
        beta = min(beta, best_eval)
        tt[h] = HashItem(h, depth, best_eval, (alpha, beta))
    return best_eval
    def on_epoch_end(self, epoch, logs={}):
        y_prob = self.model.predict(self.X_test)
        np.save(self.saveDir + 'epoch{:0>2}.npy'.format(epoch), y_prob)

        y_predict = MyCorpus.topK(y_prob, topK=1)

        predictions = MyCorpus.oneHotDecode(y_predict)
        ground_truth = MyCorpus.oneHotDecode(self.y_test)
        metrics = evaluate(predictions, ground_truth)
        logging.info('acc, ma_f1, mi_f1: {}'.format(metrics[0], metrics[3],
                                                    metrics[6]))
        with open(self.saveDir + 'metric.txt', 'a') as metricFile:
            metricFile.write('\t'.join(map(str, metrics)) + '\n')
        self.history.append(metrics)
Beispiel #4
0
def _min(board, profondeur):
    """
    :param board: le tableau du jeu
    :type board: chess.Board
    :param profondeur: profondeur de l'algo
    :type profondeur: int
    """
    if profondeur == 0 or board.is_game_over():
        return ev.evaluate(board)

    val = math.inf
    for play in board.legal_moves:
        board.push(play)
        val = min(val, _max(board, profondeur - 1))
        board.pop()

    return val
    def on_epoch_end(self, epoch, logs={}):
        y_prob = self.model.predict(self.X_test)
        np.save(self.saveDir + 'epoch{:0>2}.npy'.format(epoch), y_prob)

        scores = []
        for threshold in np.arange(0.3, 0.6, 0.1):
            y_predict = MyCorpus.threshold(y_prob, threshold=threshold)

            predictions = MyCorpus.oneHotDecode(y_predict)
            ground_truth = MyCorpus.oneHotDecode(self.y_test)
            metrics = evaluate(predictions, ground_truth)
            scores.append(metrics)
        maxScore = max(scores, key=lambda kv: sum([kv[0], kv[3], kv[6]]))
        logging.info('acc, ma_f1, mi_f1: {}'.format(maxScore[0], maxScore[3],
                                                    maxScore[6]))
        with open(self.saveDir + 'metric.txt', 'a') as metricFile:
            metricFile.write('\t'.join(map(str, maxScore)) + '\n')
        self.history.append(maxScore)
Beispiel #6
0
def ab_max(board: chess.Board, alpha, beta, depth) -> int:
    """
    :param board: the board of the game
    :param alpha: alpha val
    :param beta: beta val
    :param depth: depth
    :return: the evaluation of the branch
    """
    if depth == 0 or board.is_game_over():
        return ev.evaluate(board)
    best_eval = -math.inf
    for coup in board.legal_moves:
        board.push(coup)
        best_eval = max(best_eval, ab_min(board, alpha, beta, depth - 1))
        board.pop()
        if best_eval >= beta:
            return best_eval
        alpha = max(alpha, best_eval)
    return best_eval
Beispiel #7
0
def ab_min(board: chess.Board, alpha, beta, depth: int) -> int:
    """
    :param board: board of the chess game
    :param alpha: alpha
    :param beta: beta
    :param depth: profondeur
    :return: the branch evaluation
    """
    if depth == 0 or board.is_game_over():
        return ev.evaluate(board)
    best_eval = math.inf
    for coup in board.legal_moves:
        board.push(coup)
        best_eval = min(best_eval, ab_max(board, alpha, beta, depth - 1))
        board.pop()
        if best_eval <= alpha:
            return best_eval
        beta = min(beta, best_eval)
    return best_eval
Beispiel #8
0
else:
    if os.path.exists(modelName):
        model = load_model(modelName)
    else:
        model = lstm(corpus)
    metricHistory = MetricHistory(X_test, y_test)
    model.fit(X_train,
              y_train,
              epochs=20,
              batch_size=128,
              validation_split=0.1,
              shuffle=True,
              callbacks=[metricHistory])
    model.save(modelName)
    logging.info(str(metricHistory.history))

y_prob = model.predict(X_test)

y_predict = corpus.hybrid(y_prob, threshold=0.5)

predictions = corpus.oneHotDecode(y_predict)
ground_truth = corpus.oneHotDecode(y_test)
accuracy, macro_precision, macro_recall, macro_f1, micro_precision, micro_recall, micro_f1 = evaluate(
    predictions, ground_truth)
print('---- Final result ----')
print('accuracy:', accuracy)
print('macro_precision, macro_recall, macro_f1:', macro_precision,
      macro_recall, macro_f1)
print('micro_precision, micro_recall, micro_f1:', micro_precision,
      micro_recall, micro_f1)
Beispiel #9
0
import chess

import eval.evaluation as ev
import ia.alpha_beta_tt as ab
from util.funcs import game_over_reason

board = chess.Board()

count = 0
depth = 4

while not board.is_game_over():
    print("---------------------------------")
    print("nbrcoups", count, "score:", ev.evaluate(board), "profondeur:",
          depth)
    print("---------------------------------")
    print(board)
    move = ab.best_play(board, board.turn, depth)
    board.push(move)
    count += 1

game_over_reason(board)
Beispiel #10
0
    # Entrez dans le mode de jeu ia/ia.
    if argument == 1:

        # Tour de jeu correspondant au joueur.
        if joueurIA == 1:

            # Exécution du mode de jeu correspondant : Algorithme alpha_beta
            if algorithmeIA1 == 1:
                board.push(ab.best_play(board, board.turn, profondeurIA1))
                print(
                    "\n----------------------------------------------------------------------------------------------------")
                print("+Joueur Actuel+")
                print("ia N°1 / Blanc", "Profondeur : ", profondeurIA1, "Algorithme : alpha_beta\n")
                print("+Joueur Adverse+")
                print("ia N°2 / Noir", "Profondeur : ", profondeurIA2)
                print("\nNombre de coups actuels : ", count, "Score : ", ev.evaluate(board), "\n\n")
                print(board)
                print(
                    "----------------------------------------------------------------------------------------------------\n")
                count += 1

            # Exécution du mode de jeu correspondant : Algorithme min_max
            elif algorithmeIA1 == 0:
                board.push(mm.best_play(board, board.turn, profondeurIA1))
                print(
                    "\n-------------------------------------------------------------------------------------------------")
                print("+Joueur Actuel+")
                print("ia N°1 / Blanc", "Profondeur : ", profondeurIA1, "Algorithme : min_max\n")
                print("+Joueur Adverse+")
                print("ia N°2 / Noir", "Profondeur : ", profondeurIA2)
                print("\nNombre de coups actuels : ", count, "Score : ", ev.evaluate(board), "\n\n")