Advertisement
alkkofficial

Untitled

Apr 4th, 2023
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. import numpy as np
  2. import torch
  3. import matplotlib.pyplot as plt
  4. import copy
  5. import tqdm
  6. import torch.nn as nn
  7. import torch.optim as optim
  8. from sklearn.model_selection import train_test_split
  9. import chess
  10.  
  11. # puzzle presets
  12. board = chess.Board()
  13. files = ["./ww.pgn", "./bw.pgn", "./drew.pgn"]
  14.  
  15.  
  16. def board_data(board):
  17. board_array = np.zeros((8, 8, 13), dtype=np.int8)
  18. for i in range(64):
  19. piece = board.piece_at(i)
  20. if piece is not None:
  21. color = int(piece.color)
  22. piece_type = piece.piece_type - 1
  23. board_array[i // 8][i % 8][piece_type + 6 * color] = 1
  24. else:
  25. board_array[i // 8][i % 8][-1] = 1
  26. board_array = board_array.flatten()
  27. # board_array.shape = 832 (1D)
  28. return board_array
  29.  
  30.  
  31.  
  32.  
  33. # load the numpy arrays (if any), these arrays are generated once and saved locally so that time is not wasted reloading every single time
  34. # the files are only there because during development of the code a lot of the time will be lost through loading games afresh
  35. # getting the number of games needed to analyse
  36. # set up training data
  37. train_data = np.empty(
  38. (0, 832)
  39. ) # 832 is the size of the flattened board in one hot encoding
  40. train_target = []
  41. for file in files:
  42. with open(file, "r") as f:
  43. contents = f.read()
  44. contents = contents.split(" \n")
  45. for game in tqdm.tqdm(contents, desc="each game"):
  46. game = game.split(" \n")
  47. g = "".join(game)
  48. game = g.split(" ")
  49. game = [x for x in game if x] # remove empty strings
  50. MAX_MOMENTS = min(20, len(game))
  51. unsampled_idx = [x for x in range(1, len(game))]
  52. for move in range(MAX_MOMENTS - 1):
  53. board = chess.Board()
  54. up_to = np.random.choice(unsampled_idx)
  55. unsampled_idx.remove(up_to)
  56. moment = game[:up_to]
  57. counter = 0
  58. for move in moment:
  59. board.push(chess.Move.from_uci(move))
  60. counter += 1
  61. matrix_game = np.array([board_data(board)]) # game after one hot encoding
  62. train_data = np.append(train_data, matrix_game, axis=0)
  63. status = 0
  64. if (counter % 2 == 0 and file == "./ww.pgn") or (
  65. counter % 2 == 1 and file == "./bw.pgn"
  66. ):
  67. status = 1
  68. elif (counter % 2 == 0 and file == "./bw.pgn") or (
  69. counter % 2 == 1 and file == "./ww.pgn"
  70. ):
  71. status = -1
  72. elif file == "./drew.pgn":
  73. status = 0
  74. train_target.append(status)
  75. train_target = np.array(train_target, dtype=np.float32).reshape(-1, 1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement