├── Procfile ├── .gitignore ├── v1 ├── main.py ├── board.jpg ├── cross.jpg ├── cross.png ├── zero.jpg ├── zero.png ├── Weights │ ├── checkpoint │ ├── dqn_Tik Tak To_weights.h5f.index │ ├── 1 Lakh trained weights │ │ ├── checkpoint │ │ ├── dqn_Tik Tak To_weights.h5f.index │ │ └── dqn_Tik Tak To_weights.h5f.data-00000-of-00001 │ └── dqn_Tik Tak To_weights.h5f.data-00000-of-00001 ├── minimax.py ├── play.py ├── agent_vs_human.py ├── agent_vs_algo_3.py ├── agent_vs_algo_2.py ├── agent_vs_algo.py ├── ttt_value_iter_model_human_training.ipynb └── ttt_value_iteration_self_training.ipynb ├── test_weights.pt ├── requirements.txt ├── README.md ├── app.py ├── maingame.py └── LICENSE /Procfile: -------------------------------------------------------------------------------- 1 | web: gunicorn app:app -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .env 3 | -------------------------------------------------------------------------------- /v1/main.py: -------------------------------------------------------------------------------- 1 | # check version 2 | import tensorflow 3 | print(tensorflow.__version__) -------------------------------------------------------------------------------- /v1/board.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spartificial/ttt-on-spartificial/main/v1/board.jpg -------------------------------------------------------------------------------- /v1/cross.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spartificial/ttt-on-spartificial/main/v1/cross.jpg -------------------------------------------------------------------------------- /v1/cross.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spartificial/ttt-on-spartificial/main/v1/cross.png -------------------------------------------------------------------------------- /v1/zero.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spartificial/ttt-on-spartificial/main/v1/zero.jpg -------------------------------------------------------------------------------- /v1/zero.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spartificial/ttt-on-spartificial/main/v1/zero.png -------------------------------------------------------------------------------- /test_weights.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spartificial/ttt-on-spartificial/main/test_weights.pt -------------------------------------------------------------------------------- /v1/Weights/checkpoint: -------------------------------------------------------------------------------- 1 | model_checkpoint_path: "dqn_Tik Tak To_weights.h5f" 2 | all_model_checkpoint_paths: "dqn_Tik Tak To_weights.h5f" 3 | -------------------------------------------------------------------------------- /v1/Weights/dqn_Tik Tak To_weights.h5f.index: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spartificial/ttt-on-spartificial/main/v1/Weights/dqn_Tik Tak To_weights.h5f.index -------------------------------------------------------------------------------- /v1/Weights/1 Lakh trained weights/checkpoint: -------------------------------------------------------------------------------- 1 | model_checkpoint_path: "dqn_Tik Tak To_weights.h5f" 2 | all_model_checkpoint_paths: "dqn_Tik Tak To_weights.h5f" 3 | -------------------------------------------------------------------------------- /v1/Weights/dqn_Tik Tak To_weights.h5f.data-00000-of-00001: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spartificial/ttt-on-spartificial/main/v1/Weights/dqn_Tik Tak To_weights.h5f.data-00000-of-00001 -------------------------------------------------------------------------------- /v1/Weights/1 Lakh trained weights/dqn_Tik Tak To_weights.h5f.index: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spartificial/ttt-on-spartificial/main/v1/Weights/1 Lakh trained weights/dqn_Tik Tak To_weights.h5f.index -------------------------------------------------------------------------------- /v1/Weights/1 Lakh trained weights/dqn_Tik Tak To_weights.h5f.data-00000-of-00001: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spartificial/ttt-on-spartificial/main/v1/Weights/1 Lakh trained weights/dqn_Tik Tak To_weights.h5f.data-00000-of-00001 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -f https://download.pytorch.org/whl/cpu/torch_stable.html 2 | Flask==1.1.2 3 | flask-cors 4 | gunicorn==19.9.0 5 | gym==0.7.4 6 | itsdangerous==1.1.0 7 | Jinja2==2.10.1 8 | MarkupSafe==1.1.1 9 | Werkzeug==1.0.1 10 | torch==1.10.0+cpu 11 | scipy>=0.15.1 12 | matplotlib>=1.4.3 13 | pandas>=0.19 14 | 15 | # v1 16 | absl-py==0.15.0 17 | astunparse==1.6.3 18 | cached-property==1.5.2 19 | cachetools==4.2.4 20 | certifi==2021.10.8 21 | charset-normalizer==2.0.8 22 | clang==5.0 23 | cloudpickle==2.0.0 24 | dataclasses==0.8 25 | flatbuffers==1.12 26 | gast==0.4.0 27 | google-auth==1.35.0 28 | google-auth-oauthlib==0.4.6 29 | google-pasta==0.2.0 30 | grpcio==1.42.0 31 | gym==0.21.0 32 | h5py==3.1.0 33 | idna==3.3 34 | importlib-metadata==4.8.2 35 | keras==2.6.0 36 | Keras-Preprocessing==1.1.2 37 | keras-rl2==1.0.5 38 | Markdown==3.3.6 39 | numpy==1.19.5 40 | oauthlib==3.1.1 41 | opencv-python==4.5.4.60 42 | opt-einsum==3.3.0 43 | protobuf==3.19.1 44 | pyasn1==0.4.8 45 | pyasn1-modules==0.2.8 46 | pybullet==3.2.0 47 | requests==2.26.0 48 | requests-oauthlib==1.3.0 49 | rsa==4.8 50 | six==1.15.0 51 | tensorboard==2.6.0 52 | tensorboard-data-server==0.6.1 53 | tensorboard-plugin-wit==1.8.0 54 | tensorflow==2.6.2 55 | tensorflow-estimator==2.6.0 56 | termcolor==1.1.0 57 | typing-extensions==3.7.4.3 58 | urllib3==1.26.7 59 | Werkzeug==2.0.2 60 | wrapt==1.12.1 61 | zipp==3.6.0 62 | -------------------------------------------------------------------------------- /v1/minimax.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def result(board): 4 | if board[0] == board[1] == board[2] == 1 or \ 5 | board[3] == board[4] == board[5] == 1 or \ 6 | board[6] == board[7] == board[8] == 1 or \ 7 | board[0] == board[3] == board[6] == 1 or \ 8 | board[1] == board[4] == board[7] == 1 or \ 9 | board[2] == board[5] == board[8] == 1 or \ 10 | board[0] == board[4] == board[8] == 1 or \ 11 | board[2] == board[4] == board[6] == 1: 12 | return 1 13 | if board[0] == board[1] == board[2] == 2 or \ 14 | board[3] == board[4] == board[5] == 2 or \ 15 | board[6] == board[7] == board[8] == 2 or \ 16 | board[0] == board[3] == board[6] == 2 or \ 17 | board[1] == board[4] == board[7] == 2 or \ 18 | board[2] == board[5] == board[8] == 2 or \ 19 | board[0] == board[4] == board[8] == 2 or \ 20 | board[2] == board[4] == board[6] == 2: 21 | return 2 22 | if sum(board == 0) == 0: return 3 23 | return 0 24 | 25 | def minimax(maxi, board): 26 | if result(board)!=0: 27 | if result(board)==1: 28 | return 1 29 | elif result(board)==2: 30 | return -1 31 | else: 32 | return 0 33 | 34 | score = [] 35 | if maxi==0: val=1 36 | else: val=2 37 | for i in range(9): 38 | if board[i]!=0: continue 39 | board[i] = val 40 | score.append(minimax(not maxi, board)) 41 | board[i] = 0 42 | 43 | if maxi: 44 | return max(score) 45 | else: 46 | return min(score) 47 | 48 | arr = np.zeros(9) 49 | for i in range(9): 50 | arr[i] = 1 51 | print(i, minimax(0, arr)) 52 | arr[i] = 0 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ttt-on-spartificial 2 | 3 | A Deep Q Network based reinforcement learning agent to play tic-tac-toe that learns from human interation. 4 | 5 | ## Demo 6 | 7 | Initially agent plays random moves due to extensive exploration. 8 | 9 | [Image or gif to be added later] 10 | 11 | 12 | ## How does it work 13 | 14 | Reinforcement Learning 15 | 16 | At first, the agent will play random moves, saving the states and the given reward in a limited queue (replay memory). At the end of each episode (game), the agent will train itself (using a neural network) with a random sample of the replay memory. As more and more games are played, the agent becomes smarter, achieving higher chance of winning. 17 | 18 | Since in reinforcement learning once an agent discovers a good 'path' it will stick with it, it was also considered an exploration variable (that decreases over time), so that the agent picks sometimes a random action instead of the one it considers the best. This way, it can discover new 'paths' to achieve higher scores. 19 | 20 | ## Components of RL 21 | - Environment: Game board 22 | - Action: Coordinates of the game board (Array of shape (1,9)) 23 | - Observation: 24 | 1. Current game board 25 | - Reward: 26 | 1. Positive reward if AI wins the game 27 | 2. Negative reward if AI can lose on the next move 28 | 3. Negative reward if AI plays illegal moves 29 | 30 | ## Training 31 | 32 | The training is based on the Q Learning algorithm. Instead of using just the current state and reward obtained to train the network, it is used Q Learning (that considers the transition from the current state to the future one) to find out what is the best possible score of all the given states considering the future rewards, i.e., the algorithm is not greedy. This allows for the agent to take some moves that might not give an immediate reward, so it can get a bigger one later on (e.g. waiting to clear multiple lines instead of a single one). 33 | 34 | The neural network will be updated with the given data (considering a play with reward that moves from state to next_state, the latter having an expected value of Q_next_state, found using the prediction from the neural network) 35 | 36 | ## Results 37 | 38 | Since the model is not trained at first and it only learn with human interaction, it can take a lot of time to learn and optimize it's actions. From our testing, we are hoping to get best results after 30_000 total game iterations. 39 | 40 | The interactive UI for this project will be live soon [here](https://spartificial.com/) 41 | 42 | 43 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | from maingame import Game, TicTacToe, Policy, ReplayMemory 2 | import numpy as np 3 | import torch 4 | import torch.optim as optim 5 | from flask import Flask, jsonify, request 6 | import json 7 | from flask_cors import CORS 8 | 9 | 10 | 11 | app = Flask(__name__) 12 | CORS(app) 13 | 14 | batch_size = 128 15 | gamma = 0.99 16 | eps_start = 1.0 17 | eps_end = 0.1 18 | eps_steps = 30_000 19 | 20 | game = Game() 21 | policy = Policy(n_inputs=3 * 9, n_outputs=9) 22 | 23 | policy = game.load_model("test_weights.pt") 24 | 25 | target = Policy(n_inputs=3 * 9, n_outputs=9) 26 | target.load_state_dict(policy.state_dict()) 27 | target.eval() 28 | 29 | optimizer = optim.Adam(policy.parameters(), lr=1e-3) 30 | memory = ReplayMemory(50_000) 31 | 32 | env = TicTacToe() 33 | state = env.reset() 34 | summaries = [] 35 | 36 | 37 | 38 | @app.route('/move', methods=['POST']) 39 | def play(): 40 | # 1 is user, -1 is ai 41 | 42 | game_num = env.summary['total games'] 43 | 44 | t = np.clip(game_num / eps_steps, 0, 1) 45 | eps = (1 - t) * eps_start + t * eps_end 46 | # eps = 0.3 47 | if game_num > 30_000: 48 | eps = 0 49 | 50 | # player (1) user goes ############################################################ 51 | 52 | post = request.get_json() 53 | 54 | env.board = np.array(post.get("board"), dtype = "int") # previous board from user (flatten) 55 | user_action = int(post.get("user_action")) # action on previous board from user 56 | 57 | next_state, _, done, _ = env.step(user_action, env.board, 1) 58 | 59 | if done == 1: #user won 60 | game.optimize_model( 61 | optimizer=optimizer, 62 | policy=policy, 63 | target=target, 64 | memory=memory, 65 | batch_size=batch_size, 66 | gamma=gamma, 67 | ) 68 | if game_num % 1000 == 0: 69 | target.load_state_dict(policy.state_dict()) 70 | torch.save(policy.state_dict(), "test_weights.pt") 71 | return jsonify(tied = False, 72 | ai_wins = False, 73 | user_wins = True, 74 | board = json.dumps(list(map(int, env.board))), 75 | summary = env.summary 76 | ) 77 | 78 | if done == 2: #tie 79 | game.optimize_model( 80 | optimizer=optimizer, 81 | policy=policy, 82 | target=target, 83 | memory=memory, 84 | batch_size=batch_size, 85 | gamma=gamma, 86 | ) 87 | if game_num % 1000 == 0: 88 | target.load_state_dict(policy.state_dict()) 89 | torch.save(policy.state_dict(), "test_weights.pt") 90 | return jsonify(tied = True, 91 | ai_wins = False, 92 | user_wins = False, 93 | board = json.dumps(list(map(int, env.board))), 94 | summary = env.summary) 95 | 96 | state = torch.tensor([next_state], dtype=torch.float) 97 | 98 | # player ai (-1) goes --------------------------------------------------------------- 99 | if done == 0: 100 | action, was_random = game.select_model_action(policy, state, eps) #this function requires state as tensor 101 | if was_random: 102 | env.summary["random actions"] += 1 103 | # next_state, reward, done, _ = env.step(action.item(),env.board,-1) 104 | # if done: 105 | # next_state = None 106 | # else: 107 | # next_state = torch.tensor([next_state], dtype=torch.float).to(device) 108 | 109 | # else: 110 | action1, action = action 111 | if env.board[action1.item()] != 0: 112 | next_state, reward, _ = env.step(action1.item(), env.board, -1) 113 | next_state = torch.tensor([next_state], dtype=torch.float) 114 | memory.push(state, action1, next_state, torch.tensor([reward])) 115 | 116 | next_state, reward, done, _ = env.step(action.item(), env.board, -1) 117 | if done == -1: 118 | next_state = None 119 | if done == 0: 120 | next_state = torch.tensor([next_state], dtype=torch.float) 121 | 122 | memory.push(state, action, next_state, torch.tensor([reward])) 123 | 124 | #ai won 125 | if done == -1: 126 | game.optimize_model( 127 | optimizer=optimizer, 128 | policy=policy, 129 | target=target, 130 | memory=memory, 131 | batch_size=batch_size, 132 | gamma=gamma, 133 | ) 134 | if game_num % 1000 == 0: 135 | target.load_state_dict(policy.state_dict()) 136 | torch.save(policy.state_dict(), "test_weights.pt") 137 | return jsonify(tied = False, 138 | ai_wins = True, 139 | user_wins = False, 140 | board = json.dumps(list(map(int, env.board))), 141 | summary = env.summary) 142 | 143 | # game continues 144 | if done == 0: 145 | game.optimize_model( 146 | optimizer=optimizer, 147 | policy=policy, 148 | target=target, 149 | memory=memory, 150 | batch_size=batch_size, 151 | gamma=gamma, 152 | ) 153 | if game_num % 1000 == 0: 154 | target.load_state_dict(policy.state_dict()) 155 | torch.save(policy.state_dict(), "test_weights.pt") 156 | return jsonify(tied = False, 157 | ai_wins = False, 158 | user_wins = False, 159 | board = json.dumps(list(map(int, env.board))), 160 | summary = env.summary) 161 | -------------------------------------------------------------------------------- /v1/play.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import gym 3 | import time 4 | import tensorflow as tf 5 | import cv2 6 | from tensorflow.keras.models import Sequential 7 | from tensorflow.keras.layers import Dense, Activation, Flatten 8 | from tensorflow.keras.optimizers import Adam 9 | 10 | from rl.agents.dqn import DQNAgent 11 | from rl.policy import BoltzmannQPolicy 12 | from rl.memory import SequentialMemory 13 | 14 | 15 | class CycleBalancingEnv(gym.Env): 16 | metadata = {'render.modes': ['human']} 17 | 18 | def __init__(self): 19 | self.action_space = gym.spaces.Discrete(9) 20 | self.observation_space = gym.spaces.Box(low=0, high=2, shape=(9, ), dtype=np.uint8) 21 | self.np_random, _ = gym.utils.seeding.np_random() 22 | self.x = 0 23 | self.y = 0 24 | 25 | def draw_circle(self, event,x,y,flags,param): 26 | if event == cv2.EVENT_LBUTTONDBLCLK: 27 | print('Mouse postion = ', x, y) 28 | self.x = x 29 | self.y = y 30 | return 0 31 | return 1 32 | 33 | def step(self, action): 34 | # print(action) 35 | # action = np.argmax(action) 36 | # print(action) 37 | 38 | if self.pos[action]!=0: return self.pos, -1, 0, {} 39 | 40 | x = (action//3)*100 41 | y = (action % 3)*100 42 | self.board[x+25: x+75, y+25:y+75] = self.zero 43 | self.pos[x//100*3+y//100] = 1 44 | cv2.imshow('img', self.board) 45 | cv2.waitKey(1) 46 | #print(self.pos) 47 | res = self.result() 48 | if res == 3: 49 | print("Draw") 50 | cv2.waitKey(0) 51 | return self.pos, 2, 1, {} 52 | elif res == 1: 53 | print("Win") 54 | cv2.waitKey(0) 55 | return self.pos, 10, 1, {} 56 | elif res == 2: 57 | print("Loss") 58 | cv2.waitKey(0) 59 | return self.pos, -10, 1, {} 60 | 61 | cv2.namedWindow('img') 62 | cv2.setMouseCallback('img', self.draw_circle) 63 | cv2.waitKey(0) 64 | self.x = (self.x//100)*100 65 | self.y = (self.y//100)*100 66 | 67 | self.board[self.y+25: self.y+75, self.x+25: self.x+75] = self.cross 68 | self.pos[self.y // 100 * 3 + self.x // 100] = 2 69 | cv2.imshow('img', self.board) 70 | cv2.waitKey(1) 71 | #print(self.pos) 72 | res = self.result() 73 | if res == 3: 74 | print("Draw") 75 | cv2.waitKey(0) 76 | return self.pos, 2, 1, {} 77 | elif res == 1: 78 | print("Win") 79 | cv2.waitKey(0) 80 | return self.pos, 10, 1, {} 81 | elif res == 2: 82 | print("Loss") 83 | cv2.waitKey(0) 84 | return self.pos, -10, 1, {} 85 | else: 86 | print("Continue") 87 | return self.pos, 0, 0, {} 88 | 89 | def result(self): 90 | if self.pos[0]==self.pos[1]==self.pos[2]==1 or \ 91 | self.pos[3]==self.pos[4]==self.pos[5]==1 or \ 92 | self.pos[6]==self.pos[7]==self.pos[8]==1 or \ 93 | self.pos[0]==self.pos[3]==self.pos[6]==1 or \ 94 | self.pos[1]==self.pos[4]==self.pos[7]==1 or \ 95 | self.pos[2]==self.pos[5]==self.pos[8]==1 or \ 96 | self.pos[0]==self.pos[4]==self.pos[8]==1 or \ 97 | self.pos[2]==self.pos[4]==self.pos[6]==1: 98 | return 1 99 | if self.pos[0]==self.pos[1]==self.pos[2]==2 or \ 100 | self.pos[3]==self.pos[4]==self.pos[5]==2 or \ 101 | self.pos[6]==self.pos[7]==self.pos[8]==2 or \ 102 | self.pos[0]==self.pos[3]==self.pos[6]==2 or \ 103 | self.pos[1]==self.pos[4]==self.pos[7]==2 or \ 104 | self.pos[2]==self.pos[5]==self.pos[8]==2 or \ 105 | self.pos[0]==self.pos[4]==self.pos[8]==2 or \ 106 | self.pos[2]==self.pos[4]==self.pos[6]==2: 107 | return 2 108 | if sum(self.pos == 0) == 0: return 3 109 | return 0 110 | 111 | def reset(self): 112 | self.board = cv2.imread('board.jpg') 113 | self.cross = cv2.imread('cross.jpg') 114 | self.zero = cv2.imread('zero.jpg') 115 | 116 | cv2.imshow('img', self.board) 117 | cv2.waitKey(1) 118 | self.pos = np.zeros((9)) 119 | return self.pos 120 | 121 | def render(self, mode='human'): 122 | return 0 123 | 124 | def close(self): 125 | p.disconnect(self.client) 126 | 127 | def seed(self, seed=None): 128 | self.np_random, seed = gym.utils.seeding.np_random(seed) 129 | return [seed] 130 | 131 | 132 | env = CycleBalancingEnv() 133 | env.reset() 134 | nb_actions = env.action_space.n 135 | 136 | print(env.observation_space.shape) 137 | print(nb_actions) 138 | 139 | # Next, we build a very simple model. 140 | model = Sequential() 141 | model.add(Flatten(input_shape=(1, 9))) 142 | model.add(Dense(32)) 143 | model.add(Activation('relu')) 144 | model.add(Dense(32)) 145 | model.add(Activation('relu')) 146 | model.add(Dense(32)) 147 | model.add(Activation('relu')) 148 | model.add(Dense(nb_actions)) 149 | model.add(Activation('linear')) 150 | print(model.summary()) 151 | 152 | # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and the metrics! 153 | memory = SequentialMemory(limit=50000, window_length=1) 154 | policy = BoltzmannQPolicy() 155 | dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=10, 156 | target_model_update=1e-2, policy=policy) 157 | dqn.compile(Adam(lr=1e-3), metrics=['mae']) 158 | 159 | dqn.load_weights('dqn_{}_weights.h5f'.format('Tik Tak To')) 160 | 161 | # Okay, now it's time to learn something! We visualize the training here for show, but this 162 | # slows down training quite a lot. You can always safely abort the training prematurely using 163 | dqn.fit(env, nb_steps=100, visualize=False, verbose=2) 164 | 165 | # After training is done, we save the final weights. 166 | #dqn.save_weights('dqn_{}_weights.h5f'.format('Tik Tak To'), overwrite=True) 167 | 168 | # Finally, evaluate our algorithm for 5 episodes. 169 | #dqn.test(env, nb_episodes=5, visualize=False, verbose=2) 170 | -------------------------------------------------------------------------------- /v1/agent_vs_human.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import gym 3 | import random 4 | import time 5 | import tensorflow as tf 6 | import cv2 7 | from tensorflow.keras.models import Sequential 8 | from tensorflow.keras.layers import Dense, Activation, Flatten 9 | from tensorflow.keras.optimizers import Adam 10 | 11 | from rl.agents.dqn import DQNAgent 12 | from rl.policy import BoltzmannQPolicy 13 | from rl.memory import SequentialMemory 14 | 15 | 16 | class CycleBalancingEnv(gym.Env): 17 | metadata = {'render.modes': ['human']} 18 | 19 | def __init__(self): 20 | self.action_space = gym.spaces.Discrete(9) 21 | self.observation_space = gym.spaces.Box(low=0, high=2, shape=(9, ), dtype=np.uint8) 22 | self.np_random, _ = gym.utils.seeding.np_random() 23 | self.x = 0 24 | self.y = 0 25 | self.win = 0 # Count number of Wins 26 | self.loss = 0 # Count number of losses 27 | self.draw = 0 # Count number of Draw games 28 | self.total = 0 # Count of the toatl number of games 29 | self.epsilon = 0.2000 # Probability with which we select the random move (1-epsilon is the probability with which we select best move) 30 | 31 | def step(self, action): 32 | 33 | # Take another action if the output square is already filled 34 | if self.pos[action] !=0: 35 | return self.pos, -1, 0, {} 36 | 37 | 38 | x = (action//3)*100 # X-position of the action 39 | y = (action % 3)*100 # Y-position of the action 40 | self.board[x+25: x+75, y+25:y+75] = self.zero # Draw zero on the board_image 41 | self.pos[x//100*3+y//100] = 1 # Mark the postion on the board 42 | 43 | cv2.imshow('img', self.board) 44 | cv2.waitKey(1) 45 | 46 | res = self.result() # Check if the game has ended 47 | if res == 3: # Draw 48 | print("Draw") 49 | self.draw += 1 50 | self.print_result() 51 | return self.modify_pos(self.pos), 2, 1, {} 52 | elif res == 1: # Agent Won 53 | print("Win") 54 | self.win += 1 55 | self.print_result() 56 | return self.modify_pos(self.pos), 10, 1, {} 57 | 58 | print("Double click on the square you want to move") 59 | cv2.namedWindow('img') 60 | cv2.setMouseCallback('img', self.draw_circle) 61 | cv2.waitKey(0) 62 | self.x = (self.x//100)*100 # Get X-position of the Human Player's move 63 | self.y = (self.y//100)*100 # Get Y-position of the Human Player's move 64 | 65 | self.board[self.y+25: self.y+75, self.x+25: self.x+75] = self.cross # Draw Human Player's move on the board_image 66 | self.pos[self.y // 100 * 3 + self.x // 100] = 2 # Make the Human Player's move on the board 67 | 68 | cv2.imshow('img', self.board) 69 | cv2.waitKey(1) 70 | 71 | res = self.result() # Check if the game is over 72 | if res == 3: # Draw 73 | print("Draw") 74 | self.draw += 1 75 | self.print_result() 76 | return self.modify_pos(self.pos), 2, 1, {} 77 | elif res == 2: # Human Wins 78 | print("Loss") 79 | self.loss += 1 80 | self.print_result() 81 | return self.modify_pos(self.pos), -10, 1, {} 82 | else: 83 | #print("Continue") 84 | return self.modify_pos(self.pos), 0, 0, {} 85 | 86 | def modify_pos(self, pos): 87 | pos_tmp = pos.copy() 88 | pos_tmp[pos_tmp==2] = -1 89 | print(pos_tmp) 90 | print(self.pos) 91 | return pos_tmp 92 | 93 | def draw_circle(self, event,x,y,flags,param): 94 | if event == cv2.EVENT_LBUTTONDBLCLK: 95 | print('Mouse postion = ', y//100, x//100) 96 | print("Press Enter Key...") 97 | self.x = x 98 | self.y = y 99 | return 0 100 | return 1 101 | 102 | def print_result(self): 103 | self.total += 1 104 | print("Win% = ", self.win / self.total, '\tLoss% = ', self.loss / self.total, "\tDraw% = ", self.draw / self.total) 105 | #print("Epsilon = ", self.epsilon) 106 | cv2.imshow('img', self.board) 107 | print("Press Enter Key to Continue to next game...") 108 | cv2.waitKey(0) 109 | 110 | def result(self): # Result function used to check if the game is over and who is the winner (in the "step" function) 111 | if self.pos[0]==self.pos[1]==self.pos[2]==1 or \ 112 | self.pos[3]==self.pos[4]==self.pos[5]==1 or \ 113 | self.pos[6]==self.pos[7]==self.pos[8]==1 or \ 114 | self.pos[0]==self.pos[3]==self.pos[6]==1 or \ 115 | self.pos[1]==self.pos[4]==self.pos[7]==1 or \ 116 | self.pos[2]==self.pos[5]==self.pos[8]==1 or \ 117 | self.pos[0]==self.pos[4]==self.pos[8]==1 or \ 118 | self.pos[2]==self.pos[4]==self.pos[6]==1: 119 | return 1 120 | if self.pos[0]==self.pos[1]==self.pos[2]==2 or \ 121 | self.pos[3]==self.pos[4]==self.pos[5]==2 or \ 122 | self.pos[6]==self.pos[7]==self.pos[8]==2 or \ 123 | self.pos[0]==self.pos[3]==self.pos[6]==2 or \ 124 | self.pos[1]==self.pos[4]==self.pos[7]==2 or \ 125 | self.pos[2]==self.pos[5]==self.pos[8]==2 or \ 126 | self.pos[0]==self.pos[4]==self.pos[8]==2 or \ 127 | self.pos[2]==self.pos[4]==self.pos[6]==2: 128 | return 2 129 | if sum(self.pos == 0) == 0: return 3 130 | return 0 131 | 132 | def reset(self): 133 | self.board = cv2.imread('board.jpg') # Empty board 134 | self.zero = cv2.imread('zero.jpg') # Agent's mark (zero) 135 | self.cross = cv2.imread('cross.jpg') # Human player's mark (cross) 136 | 137 | cv2.imshow('img', self.board) 138 | cv2.waitKey(1) 139 | 140 | self.pos = np.zeros((9)) # Vector or Matrice of the board postions 141 | self.epsilon = max(0.1, self.epsilon-.00005) 142 | return self.pos 143 | 144 | def render(self, mode='human'): 145 | return 0 146 | 147 | def close(self): 148 | p.disconnect(self.client) 149 | 150 | def seed(self, seed=None): 151 | self.np_random, seed = gym.utils.seeding.np_random(seed) 152 | return [seed] 153 | 154 | 155 | env = CycleBalancingEnv() 156 | env.reset() 157 | nb_actions = env.action_space.n 158 | 159 | print(env.observation_space.shape) 160 | print(nb_actions) 161 | 162 | # Next, we build a very simple model. 163 | model = Sequential() 164 | model.add(Flatten(input_shape=(1, 9))) 165 | model.add(Dense(64)) 166 | model.add(Activation('relu')) 167 | model.add(Dense(128)) 168 | model.add(Activation('relu')) 169 | model.add(Dense(64)) 170 | model.add(Activation('relu')) 171 | model.add(Dense(nb_actions)) 172 | model.add(Activation('linear')) 173 | print(model.summary()) 174 | 175 | model.load_weights('dqn_{}_weights.h5f'.format('Tik Tak To')) 176 | 177 | # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and the metrics! 178 | memory = SequentialMemory(limit=50000, window_length=1) 179 | policy = BoltzmannQPolicy() 180 | dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=1, enable_double_dqn=True, enable_dueling_network=True, 181 | dueling_type='avg', target_model_update=1e-2, policy=policy, gamma=0.9) 182 | dqn.compile(Adam(lr=1e-5), metrics=['mae']) 183 | 184 | dqn.load_weights('dqn_{}_weights.h5f'.format('Tik Tak To')) 185 | 186 | # Okay, now it's time to learn something! We visualize the training here for show, but this 187 | # slows down training quite a lot. You can always safely abort the training prematurely using 188 | dqn.fit(env, nb_steps=20000, visualize=False, verbose=2) 189 | 190 | # After training is done, we save the final weights. 191 | #dqn.save_weights('dqn_{}_weights.h5f'.format('Tik Tak To'), overwrite=True) 192 | 193 | 194 | # for i in range(1000): 195 | # pos = get_current_board_postion() 196 | # action = dqn(pos) 197 | # env.perform_action(action) 198 | # env.make_human_move() 199 | # 200 | # if env.done(): 201 | # env.reset() 202 | -------------------------------------------------------------------------------- /v1/agent_vs_algo_3.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import gym 3 | import random 4 | import time 5 | import tensorflow as tf 6 | import cv2 7 | from tensorflow.keras.models import Sequential 8 | from tensorflow.keras.layers import Dense, Activation, Flatten 9 | from tensorflow.keras.optimizers import Adam 10 | 11 | from rl.agents.dqn import DQNAgent 12 | from rl.policy import BoltzmannQPolicy 13 | from rl.memory import SequentialMemory 14 | 15 | 16 | class CycleBalancingEnv(gym.Env): 17 | metadata = {'render.modes': ['human']} 18 | 19 | def __init__(self): 20 | self.action_space = gym.spaces.Discrete(9) 21 | self.observation_space = gym.spaces.Box(low=0, high=2, shape=(9, ), dtype=np.uint8) 22 | self.np_random, _ = gym.utils.seeding.np_random() 23 | self.x = 0 24 | self.y = 0 25 | self.length = 100 26 | self.results = np.array([]) 27 | self.epsilon = 0.2000 # Probability with which we select the random move (1-epsilon is the probability with which we select best move) 28 | 29 | def step(self, action): 30 | 31 | # Take another action if the output square is already filled 32 | if self.pos[action] !=0: 33 | return self.pos, -0.1, 0, {} 34 | 35 | 36 | x = (action//3)*100 # X-position of the action 37 | y = (action % 3)*100 # Y-position of the action 38 | #self.board[x+25: x+75, y+25:y+75] = self.zero # Draw zero on the board_image 39 | self.pos[x//100*3+y//100] = 1 # Mark the postion on the board 40 | 41 | res = self.result() # Check if the game has ended 42 | if res == 3: # Draw 43 | print("Draw") 44 | self.results = np.append(self.results, res) 45 | if self.results.shape[0]>self.length: 46 | self.results = self.results[1:] 47 | self.print_result() 48 | return self.pos, 2, 1, {} 49 | elif res == 1: # Agent Won 50 | print("Win") 51 | self.results = np.append(self.results, res) 52 | if self.results.shape[0] > self.length: 53 | self.results = self.results[1:] 54 | self.print_result() 55 | return self.pos, 10, 1, {} 56 | 57 | if self.epsilon < random.random(): 58 | best_move = self.get_best_move() 59 | else: 60 | best_move = self.get_random_move() 61 | 62 | self.x = (best_move % 3) * 100 # Get X-position of the Human Player's move 63 | self.y = (best_move//3)*100 # Get Y-position of the Human Player's move 64 | 65 | #self.board[self.y+25: self.y+75, self.x+25: self.x+75] = self.cross # Draw Human Player's move on the board_image 66 | self.pos[self.y // 100 * 3 + self.x // 100] = 2 # Make the Human Player's move on the board 67 | 68 | res = self.result() # Check if the game is over 69 | if res == 3: # Draw 70 | print("Draw") 71 | self.results = np.append(self.results, res) 72 | if self.results.shape[0] > self.length: 73 | self.results = self.results[1:] 74 | self.print_result() 75 | return self.pos, 2, 1, {} 76 | elif res == 2: # Human Wins 77 | print("Loss") 78 | self.results = np.append(self.results, res) 79 | if self.results.shape[0] > self.length: 80 | self.results = self.results[1:] 81 | self.print_result() 82 | return self.pos, -10, 1, {} 83 | else: 84 | #print("Continue") 85 | return self.pos, 0, 0, {} 86 | 87 | def get_best_move(self): 88 | board = self.pos 89 | best_move = -1 90 | best_move_val = -100000 91 | for i in range(9): 92 | if board[i] != 0: continue 93 | board[i] = 2 94 | tmp = self.minimax(0, board, 1) 95 | if tmp >= best_move_val: 96 | best_move = i 97 | best_move_val = tmp 98 | board[i] = 0 99 | return best_move 100 | 101 | def get_random_move(self): 102 | moves_left = [] 103 | for i in range(9): 104 | if self.pos[i] == 0: 105 | moves_left.append(i) 106 | best_move = moves_left[random.randint(0, len(moves_left) - 1)] 107 | return best_move 108 | 109 | def print_result(self): 110 | #self.total += 1 111 | #print("Results = ", self.results) 112 | print("Win% = ", sum(self.results==1)/self.results.shape[0], '\tLoss% = ', sum(self.results==2)/self.results.shape[0], "\tDraw% = ", sum(self.results==3)/self.results.shape[0]) 113 | #print("Epsilon = ", self.epsilon) 114 | #cv2.imshow('img', self.board) 115 | #cv2.waitKey(1) 116 | 117 | def result_2(self, board): # Result function used by the minimax algorithm 118 | if board[0] == board[1] == board[2] == 1 or \ 119 | board[3] == board[4] == board[5] == 1 or \ 120 | board[6] == board[7] == board[8] == 1 or \ 121 | board[0] == board[3] == board[6] == 1 or \ 122 | board[1] == board[4] == board[7] == 1 or \ 123 | board[2] == board[5] == board[8] == 1 or \ 124 | board[0] == board[4] == board[8] == 1 or \ 125 | board[2] == board[4] == board[6] == 1: 126 | return 1 127 | if board[0] == board[1] == board[2] == 2 or \ 128 | board[3] == board[4] == board[5] == 2 or \ 129 | board[6] == board[7] == board[8] == 2 or \ 130 | board[0] == board[3] == board[6] == 2 or \ 131 | board[1] == board[4] == board[7] == 2 or \ 132 | board[2] == board[5] == board[8] == 2 or \ 133 | board[0] == board[4] == board[8] == 2 or \ 134 | board[2] == board[4] == board[6] == 2: 135 | return 2 136 | if sum(board == 0) == 0: return 3 # Draw 137 | return 0 138 | 139 | def minimax(self, maxi, board, depth): # Minimax Algorithm to find the best move 140 | if self.result_2(board) != 0: 141 | if self.result_2(board) == 2: 142 | return 100 143 | elif self.result_2(board) == 1: 144 | return -100 145 | else: 146 | return 0 147 | 148 | score = [] 149 | for i in range(9): 150 | if board[i] != 0: continue 151 | board[i] = int(maxi)+1 152 | #print("Maxi = ", int(maxi)+1) 153 | score.append(self.minimax(not maxi, board, depth+1)) 154 | board[i] = 0 155 | 156 | if maxi: 157 | return max(score)-depth 158 | else: 159 | return min(score)-depth 160 | 161 | def result(self): # Result function used to check if the game is over and who is the winner (in the "step" function) 162 | if self.pos[0]==self.pos[1]==self.pos[2]==1 or \ 163 | self.pos[3]==self.pos[4]==self.pos[5]==1 or \ 164 | self.pos[6]==self.pos[7]==self.pos[8]==1 or \ 165 | self.pos[0]==self.pos[3]==self.pos[6]==1 or \ 166 | self.pos[1]==self.pos[4]==self.pos[7]==1 or \ 167 | self.pos[2]==self.pos[5]==self.pos[8]==1 or \ 168 | self.pos[0]==self.pos[4]==self.pos[8]==1 or \ 169 | self.pos[2]==self.pos[4]==self.pos[6]==1: 170 | return 1 171 | if self.pos[0]==self.pos[1]==self.pos[2]==2 or \ 172 | self.pos[3]==self.pos[4]==self.pos[5]==2 or \ 173 | self.pos[6]==self.pos[7]==self.pos[8]==2 or \ 174 | self.pos[0]==self.pos[3]==self.pos[6]==2 or \ 175 | self.pos[1]==self.pos[4]==self.pos[7]==2 or \ 176 | self.pos[2]==self.pos[5]==self.pos[8]==2 or \ 177 | self.pos[0]==self.pos[4]==self.pos[8]==2 or \ 178 | self.pos[2]==self.pos[4]==self.pos[6]==2: 179 | return 2 180 | if sum(self.pos == 0) == 0: return 3 181 | return 0 182 | 183 | def reset(self): 184 | #self.board = cv2.imread('board.jpg') # Empty board 185 | #self.zero = cv2.imread('zero.jpg') # Agent's mark (zero) 186 | #self.cross = cv2.imread('cross.jpg') # Human player's mark (cross) 187 | 188 | self.pos = np.zeros((9)) # Vector or Matrice of the board postions 189 | self.epsilon = max(0.1, self.epsilon-.00005) 190 | return self.pos 191 | 192 | def render(self, mode='human'): 193 | return 0 194 | 195 | def close(self): 196 | p.disconnect(self.client) 197 | 198 | def seed(self, seed=None): 199 | self.np_random, seed = gym.utils.seeding.np_random(seed) 200 | return [seed] 201 | 202 | 203 | env = CycleBalancingEnv() 204 | env.reset() 205 | nb_actions = env.action_space.n 206 | 207 | print(env.observation_space.shape) 208 | print(nb_actions) 209 | 210 | # Next, we build a very simple model. 211 | model = Sequential() 212 | model.add(Flatten(input_shape=(1, 9))) 213 | model.add(Dense(16)) 214 | model.add(Activation('relu')) 215 | model.add(Dense(16)) 216 | model.add(Activation('relu')) 217 | model.add(Dense(16)) 218 | model.add(Activation('relu')) 219 | model.add(Dense(nb_actions)) 220 | model.add(Activation('Softmax')) 221 | print(model.summary()) 222 | 223 | # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and the metrics! 224 | memory = SequentialMemory(limit=50000, window_length=1) 225 | policy = BoltzmannQPolicy() 226 | dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=20, 227 | target_model_update=1e-2, policy=policy) 228 | dqn.compile(Adam(lr=1e-2), metrics=['mae']) 229 | 230 | #dqn.load_weights('dqn_{}_weights.h5f'.format('Tik Tak To')) 231 | 232 | # Okay, now it's time to learn something! We visualize the training here for show, but this 233 | # slows down training quite a lot. You can always safely abort the training prematurely using 234 | dqn.fit(env, nb_steps=20000, visualize=False, verbose=2) 235 | 236 | # After training is done, we save the final weights. 237 | #print('Saving Weights') 238 | #dqn.save_weights('dqn_{}_weights.h5f'.format('Tik Tak To'), overwrite=True) 239 | 240 | 241 | # print(dqn.model) 242 | # 243 | # print("Testing") 244 | # for i in range(10): 245 | # done = False 246 | # obs = env.reset() 247 | # while not done: 248 | # obs = obs.reshape((1, 1, -1)) 249 | # action =- dqn.model.predict(obs)[0] 250 | # for i in range(9): 251 | # if env.pos[i]!=0: 252 | # action[i] = -1000000 253 | # action = np.argmax(action) 254 | # obs, reward, done, _ = env.step(action) 255 | -------------------------------------------------------------------------------- /maingame.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import numpy as np 4 | import gym 5 | from gym import spaces 6 | import random 7 | from collections import namedtuple 8 | 9 | import torch 10 | import torch.nn as nn 11 | import torch.nn.functional as F 12 | from torch.distributions import Categorical 13 | import torch.optim as optim 14 | 15 | from typing import Tuple 16 | 17 | 18 | #Environment 19 | 20 | class TicTacToe(gym.Env): 21 | 22 | # reward_range = (-np.inf, np.inf) 23 | # observation_space = spaces.MultiDiscrete([2 for _ in range(0, 9 * 3)]) 24 | # action_space = spaces.Discrete(9) 25 | 26 | """ 27 | Board looks like: 28 | [0, 1, 2, 29 | 3, 4, 5, 30 | 6, 7, 8] 31 | """ 32 | winning_streaks = [ 33 | [0, 1, 2], 34 | [3, 4, 5], 35 | [6, 7, 8], 36 | [0, 3, 6], 37 | [1, 4, 7], 38 | [2, 5, 8], 39 | [0, 4, 8], 40 | [2, 4, 6], 41 | ] 42 | 43 | def __init__(self, summary: dict = None): 44 | super().__init__() 45 | if summary is None: 46 | summary = { 47 | "total games": 0, 48 | "ties": 0, 49 | "illegal moves": 0, 50 | "player other wins": 0, 51 | "player ai wins": 0, 52 | "random actions" : 0 53 | } 54 | self.summary = summary 55 | self.board = np.zeros(9, dtype="int") 56 | 57 | # deterministic 58 | def seed(self, seed=None): 59 | pass 60 | 61 | def one_hot_board(self): 62 | return np.eye(3)[self.board].reshape(-1) 63 | 64 | def reset(self): 65 | # other player = 1, ai_player = -1 66 | self.board = np.zeros(9, dtype="int") 67 | return self.one_hot_board() 68 | 69 | def step(self, action, prev_board, player): 70 | # done values = {0: not over, 1: other player won, -1: ai won, 2: tie} 71 | 72 | 73 | exp = {"state": "in progress"} 74 | reward = 0 75 | done = 0 76 | 77 | # illegal move 78 | if player == -1: #check for ai player only 79 | if prev_board[action] != 0 and player == -1: 80 | reward = -10 # illegal moves are really bad 81 | exp = {"state": "revisited", "reason": "Illegal move"} 82 | self.summary["illegal moves"] += 1 83 | 84 | return self.one_hot_board(), reward, exp 85 | 86 | self.board[action] = player 87 | 88 | # if the other player can win on the next turn and still ai is not being defensive 89 | for streak in self.winning_streaks: 90 | if ((self.board[streak] == 1).sum() == 2) and (self.board[streak] == 0).any(): 91 | if player == -1: 92 | reward = -2 93 | exp = { 94 | "state": "in progress", 95 | "reason": "Player ai can lose on the next turn" 96 | } 97 | 98 | for streak in self.winning_streaks: 99 | # check if ai player won 100 | if (self.board[streak] == -1).all(): 101 | reward = 2 102 | exp = { 103 | "state": "End", 104 | "reason": "Player ai has won" 105 | } 106 | self.summary["total games"] += 1 107 | self.summary["player ai wins"] += 1 108 | done = -1 109 | break 110 | 111 | # check if other player won 112 | elif (self.board[streak] == 1).all(): 113 | exp = { 114 | "state": "End", 115 | "reason": "Player other has won" 116 | } 117 | self.summary["total games"] += 1 118 | self.summary["player other wins"] += 1 119 | done = 1 120 | break 121 | 122 | # if game is drawn 123 | if (self.board != 0).all() and not done: 124 | reward = 0 125 | exp = { 126 | "state": "End", 127 | "reason": "Game Draw!" 128 | } 129 | done = 2 130 | self.summary["total games"] += 1 131 | self.summary["ties"] += 1 132 | 133 | # print("S5", self.one_hot_board(), reward, done, exp) 134 | 135 | return self.one_hot_board(), reward, done, exp 136 | 137 | def render(self, mode: str = "human"): 138 | print("{}|{}|{}\n-----\n{}|{}|{}\n-----\n{}|{}|{}".format(*self.board.tolist())) 139 | 140 | 141 | class ReplayMemory(object): 142 | 143 | def __init__(self, capacity): 144 | self.capacity = capacity 145 | self.memory = [] 146 | self.position = 0 147 | self.transition = namedtuple("Transition", ("state", "action", "next_state", "reward")) 148 | 149 | 150 | def push(self, *args): 151 | """Saves a transition.""" 152 | if len(self.memory) < self.capacity: 153 | self.memory.append(None) 154 | self.memory[self.position] = self.transition(*args) 155 | self.position = (self.position + 1) % self.capacity 156 | 157 | def sample(self, batch_size): 158 | return random.sample(self.memory, batch_size) 159 | 160 | def __len__(self): 161 | return len(self.memory) 162 | 163 | 164 | class Policy(nn.Module): 165 | 166 | def __init__(self, n_inputs= 3*9, n_outputs=9): 167 | super(Policy, self).__init__() 168 | self.fc1 = nn.Linear(n_inputs, 128) 169 | self.fc2 = nn.Linear(128, 256) 170 | self.fc3 = nn.Linear(256, 128) 171 | self.fc4 = nn.Linear(128, n_outputs) 172 | 173 | def forward(self, x): 174 | x = F.relu(self.fc1(x)) 175 | x = F.relu(self.fc2(x)) 176 | x = F.relu(self.fc3(x)) 177 | x = F.relu(self.fc4(x)) 178 | return x 179 | 180 | def valid_actions(self, state): 181 | state = state.reshape(3, 3, 3) 182 | open_spots = state[:, :, 0].reshape(-1) 183 | return open_spots 184 | 185 | def act(self, state): 186 | with torch.no_grad(): 187 | action1 = self.forward(state).max(1)[1].view(1, 1) 188 | 189 | actions = self.forward(state) 190 | actions, act_idx = actions[0].sort(descending = True) 191 | opens = self.valid_actions(state) 192 | 193 | for idx in act_idx: 194 | if opens[idx] == 1: 195 | return action1, torch.tensor([[idx]], dtype=torch.long) 196 | 197 | 198 | 199 | class Game: 200 | ''' 201 | make board 202 | get player move 203 | update state 204 | feed state into model 205 | get action from model 206 | update state 207 | ''' 208 | # def __init__(self, policy = Policy): 209 | # self.policy = Policy(n_inputs=3*9, n_outputs=9) 210 | 211 | # def player_move(self, board, ) 212 | 213 | def load_model(self, path: str): 214 | model = Policy(n_inputs=3*9, n_outputs=9) 215 | model_state_dict = torch.load(path) 216 | model.load_state_dict(model_state_dict) 217 | model.eval() 218 | return model 219 | 220 | 221 | def select_dummy_action(self, state: np.array): 222 | state = state.reshape(3, 3, 3) 223 | open_spots = state[:, :, 0].reshape(-1) 224 | p = open_spots / open_spots.sum() 225 | r = np.random.choice(np.arange(9), p=p) 226 | return r 227 | 228 | def select_model_action(self, model: Policy, state: torch.tensor, eps: float): 229 | sample = random.random() 230 | if sample > eps: 231 | return model.act(state), False 232 | else: 233 | state = state.numpy() 234 | a = torch.tensor([[random.randrange(0, 9)]],dtype=torch.long,) 235 | b = torch.tensor([[self.select_dummy_action(state)]], dtype=torch.long) 236 | 237 | return (a, b), True 238 | 239 | def optimize_model(self, 240 | optimizer: optim.Optimizer, 241 | policy: Policy, 242 | target: Policy, 243 | memory: ReplayMemory, 244 | batch_size: int, 245 | gamma: float): 246 | # from pytorch docs: https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html 247 | 248 | if len(memory) < batch_size: 249 | return 250 | transitions = memory.sample(batch_size) 251 | # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for 252 | # detailed explanation). This converts batch-array of Transitions 253 | # to Transition of batch-arrays. 254 | batch = memory.transition(*zip(*transitions)) 255 | 256 | # Compute a mask of non-final states and concatenate the batch elements 257 | # (a final state would've been the one after which simulation ended) 258 | non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, batch.next_state)), dtype=torch.bool,) 259 | non_final_next_states = torch.cat([s for s in batch.next_state if s is not None]) 260 | 261 | state_batch = torch.cat(batch.state) 262 | action_batch = torch.cat(batch.action) 263 | reward_batch = torch.cat(batch.reward) 264 | 265 | # Compute Q(s_t, a) - the model computes Q(s_t), then we select the 266 | # columns of actions taken. These are the actions which would've been taken 267 | # for each batch state according to policy_net 268 | state_action_values = policy(state_batch).gather(1, action_batch) 269 | 270 | # Compute V(s_{t+1}) for all next states. 271 | # Expected values of actions for non_final_next_states are computed based 272 | # on the "older" target_net; selecting their best reward with max(1)[0]. 273 | # This is merged based on the mask, such that we'll have either the expected 274 | # state value or 0 in case the state was final. 275 | next_state_values = torch.zeros(batch_size) 276 | next_state_values[non_final_mask] = target(non_final_next_states).max(1)[0].detach() 277 | # Compute the expected Q values 278 | 279 | expected_state_action_values = (next_state_values * gamma) + reward_batch 280 | 281 | # Compute Huber loss 282 | loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) 283 | # print(loss) 284 | 285 | # Optimize the model 286 | optimizer.zero_grad() 287 | loss.backward() 288 | for param in policy.parameters(): 289 | param.grad.data.clamp_(-1, 1) 290 | optimizer.step() 291 | 292 | 293 | 294 | -------------------------------------------------------------------------------- /v1/agent_vs_algo_2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import gym 3 | import random 4 | import time 5 | import tensorflow as tf 6 | import cv2 7 | from tensorflow.keras.models import Sequential 8 | from tensorflow.keras.layers import Dense, Activation, Flatten 9 | from tensorflow.keras.optimizers import Adam 10 | 11 | from rl.agents.dqn import DQNAgent 12 | from rl.policy import BoltzmannQPolicy 13 | from rl.memory import SequentialMemory 14 | 15 | 16 | class CycleBalancingEnv(gym.Env): 17 | metadata = {'render.modes': ['human']} 18 | 19 | def __init__(self): 20 | self.action_space = gym.spaces.Discrete(9) 21 | self.observation_space = gym.spaces.Box(low=0, high=2, shape=(9, ), dtype=np.uint8) 22 | self.np_random, _ = gym.utils.seeding.np_random() 23 | self.x = 0 24 | self.y = 0 25 | self.length = 100 26 | self.results = np.array([]) 27 | self.epsilon = 0.2000 # Probability with which we select the random move (1-epsilon is the probability with which we select best move) 28 | self.mem_table = dict() 29 | 30 | def step(self, action): 31 | 32 | # Take another action if the output square is already filled 33 | if self.pos[action] !=0: 34 | return self.pos, -0.1, 0, {} 35 | 36 | 37 | x = (action//3)*100 # X-position of the action 38 | y = (action % 3)*100 # Y-position of the action 39 | #self.board[x+25: x+75, y+25:y+75] = self.zero # Draw zero on the board_image 40 | self.pos[x//100*3+y//100] = 1 # Mark the postion on the board 41 | 42 | res = self.result() # Check if the game has ended 43 | if res == 3: # Draw 44 | #print("Draw") 45 | self.results = np.append(self.results, res) 46 | if self.results.shape[0]>self.length: 47 | self.results = self.results[1:] 48 | self.print_result() 49 | return self.modify_pos(self.pos), 0.5, 1, {} 50 | elif res == 1: # Agent Won 51 | #print("Win") 52 | self.results = np.append(self.results, res) 53 | if self.results.shape[0] > self.length: 54 | self.results = self.results[1:] 55 | self.print_result() 56 | return self.modify_pos(self.pos), 1, 1, {} 57 | 58 | if self.epsilon < random.random(): 59 | best_move = self.get_best_move() 60 | else: 61 | best_move = self.get_random_move() 62 | 63 | self.x = (best_move % 3) * 100 # Get X-position of the Human Player's move 64 | self.y = (best_move//3)*100 # Get Y-position of the Human Player's move 65 | 66 | #self.board[self.y+25: self.y+75, self.x+25: self.x+75] = self.cross # Draw Human Player's move on the board_image 67 | self.pos[self.y // 100 * 3 + self.x // 100] = 2 # Make the Human Player's move on the board 68 | 69 | res = self.result() # Check if the game is over 70 | if res == 3: # Draw 71 | #print("Draw") 72 | self.results = np.append(self.results, res) 73 | if self.results.shape[0] > self.length: 74 | self.results = self.results[1:] 75 | self.print_result() 76 | return self.modify_pos(self.pos), 0.5, 1, {} 77 | elif res == 2: # Human Wins 78 | #print("Loss") 79 | self.results = np.append(self.results, res) 80 | if self.results.shape[0] > self.length: 81 | self.results = self.results[1:] 82 | self.print_result() 83 | return self.modify_pos(self.pos), -1, 1, {} 84 | else: 85 | #print("Continue") 86 | return self.modify_pos(self.pos), 0, 0, {} 87 | 88 | def modify_pos(self, pos): 89 | pos_tmp = pos.copy() 90 | pos_tmp[pos_tmp == 2] = -1 91 | #print(pos_tmp) 92 | #print(self.pos) 93 | return pos_tmp 94 | 95 | def get_best_move(self): 96 | board = self.pos 97 | best_move = -1 98 | best_move_val = -100000 99 | for i in range(9): 100 | if board[i] != 0: continue 101 | board[i] = 2 102 | tmp = self.minimax(0, board, 1) 103 | if tmp >= best_move_val: 104 | best_move = i 105 | best_move_val = tmp 106 | board[i] = 0 107 | return best_move 108 | 109 | def get_random_move(self): 110 | moves_left = [] 111 | for i in range(9): 112 | if self.pos[i] == 0: 113 | moves_left.append(i) 114 | best_move = moves_left[random.randint(0, len(moves_left) - 1)] 115 | return best_move 116 | 117 | def print_result(self): 118 | #self.total += 1 119 | #print("Results = ", self.results) 120 | print("Win% = ", sum(self.results==1)/self.results.shape[0], '\tLoss% = ', sum(self.results==2)/self.results.shape[0], "\tDraw% = ", sum(self.results==3)/self.results.shape[0]) 121 | #print("Epsilon = ", self.epsilon) 122 | #cv2.imshow('img', self.board) 123 | #cv2.waitKey(1) 124 | return None 125 | 126 | def result_2(self, board): # Result function used by the minimax algorithm 127 | if board[0] == board[1] == board[2] == 1 or \ 128 | board[3] == board[4] == board[5] == 1 or \ 129 | board[6] == board[7] == board[8] == 1 or \ 130 | board[0] == board[3] == board[6] == 1 or \ 131 | board[1] == board[4] == board[7] == 1 or \ 132 | board[2] == board[5] == board[8] == 1 or \ 133 | board[0] == board[4] == board[8] == 1 or \ 134 | board[2] == board[4] == board[6] == 1: 135 | return 1 136 | if board[0] == board[1] == board[2] == 2 or \ 137 | board[3] == board[4] == board[5] == 2 or \ 138 | board[6] == board[7] == board[8] == 2 or \ 139 | board[0] == board[3] == board[6] == 2 or \ 140 | board[1] == board[4] == board[7] == 2 or \ 141 | board[2] == board[5] == board[8] == 2 or \ 142 | board[0] == board[4] == board[8] == 2 or \ 143 | board[2] == board[4] == board[6] == 2: 144 | return 2 145 | if sum(board == 0) == 0: return 3 # Draw 146 | return 0 147 | 148 | def minimax(self, maxi, board, depth): # Minimax Algorithm to find the best move 149 | 150 | if tuple(board) in self.mem_table.keys(): 151 | return self.mem_table[tuple(board)] 152 | 153 | if self.result_2(board) != 0: 154 | if self.result_2(board) == 2: 155 | return 100 156 | elif self.result_2(board) == 1: 157 | return -100 158 | else: 159 | return 0 160 | 161 | score = [] 162 | for i in range(9): 163 | if board[i] != 0: continue 164 | board[i] = int(maxi)+1 165 | #print("Maxi = ", int(maxi)+1) 166 | score.append(self.minimax(not maxi, board, depth+1)) 167 | board[i] = 0 168 | 169 | if maxi: 170 | self.mem_table[tuple(board)] = max(score)-depth 171 | return max(score)-depth 172 | else: 173 | self.mem_table[tuple(board)] = min(score)-depth 174 | return min(score)-depth 175 | 176 | def result(self): # Result function used to check if the game is over and who is the winner (in the "step" function) 177 | if self.pos[0]==self.pos[1]==self.pos[2]==1 or \ 178 | self.pos[3]==self.pos[4]==self.pos[5]==1 or \ 179 | self.pos[6]==self.pos[7]==self.pos[8]==1 or \ 180 | self.pos[0]==self.pos[3]==self.pos[6]==1 or \ 181 | self.pos[1]==self.pos[4]==self.pos[7]==1 or \ 182 | self.pos[2]==self.pos[5]==self.pos[8]==1 or \ 183 | self.pos[0]==self.pos[4]==self.pos[8]==1 or \ 184 | self.pos[2]==self.pos[4]==self.pos[6]==1: 185 | return 1 186 | if self.pos[0]==self.pos[1]==self.pos[2]==2 or \ 187 | self.pos[3]==self.pos[4]==self.pos[5]==2 or \ 188 | self.pos[6]==self.pos[7]==self.pos[8]==2 or \ 189 | self.pos[0]==self.pos[3]==self.pos[6]==2 or \ 190 | self.pos[1]==self.pos[4]==self.pos[7]==2 or \ 191 | self.pos[2]==self.pos[5]==self.pos[8]==2 or \ 192 | self.pos[0]==self.pos[4]==self.pos[8]==2 or \ 193 | self.pos[2]==self.pos[4]==self.pos[6]==2: 194 | return 2 195 | if sum(self.pos == 0) == 0: return 3 196 | return 0 197 | 198 | def reset(self): 199 | #self.board = cv2.imread('board.jpg') # Empty board 200 | #self.zero = cv2.imread('zero.jpg') # Agent's mark (zero) 201 | #self.cross = cv2.imread('cross.jpg') # Human player's mark (cross) 202 | 203 | self.pos = np.zeros((9)) # Vector or Matrice of the board postions 204 | self.epsilon = max(0.2, self.epsilon-.0005) 205 | return self.pos 206 | 207 | def render(self, mode='human'): 208 | return 0 209 | 210 | def close(self): 211 | p.disconnect(self.client) 212 | 213 | def seed(self, seed=None): 214 | self.np_random, seed = gym.utils.seeding.np_random(seed) 215 | return [seed] 216 | 217 | 218 | env = CycleBalancingEnv() 219 | env.reset() 220 | nb_actions = env.action_space.n 221 | 222 | print(env.observation_space.shape) 223 | print(nb_actions) 224 | 225 | # Next, we build a very simple model. 226 | model = Sequential() 227 | model.add(Flatten(input_shape=(1, 9))) 228 | model.add(Dense(16)) 229 | model.add(Activation('relu')) 230 | model.add(Dense(16)) 231 | model.add(Activation('relu')) 232 | model.add(Dense(16)) 233 | model.add(Activation('relu')) 234 | model.add(Dense(nb_actions)) 235 | model.add(Activation('linear')) 236 | print(model.summary()) 237 | 238 | # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and the metrics! 239 | memory = SequentialMemory(limit=50000, window_length=1) 240 | policy = BoltzmannQPolicy() 241 | dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=1000, enable_double_dqn=True, enable_dueling_network=False, 242 | target_model_update=1e-2, policy=policy) 243 | dqn.compile(Adam(lr=1e-5), metrics=['mae']) 244 | 245 | dqn.load_weights('dqn_{}_weights.h5f'.format('Tik Tak To')) 246 | 247 | # Okay, now it's time to learn something! We visualize the training here for show, but this 248 | # slows down training quite a lot. You can always safely abort the training prematurely using 249 | dqn.fit(env, nb_steps=10000, visualize=False, verbose=2) 250 | 251 | # After training is done, we save the final weights. 252 | print('Saving Weights') 253 | #dqn.save_weights('dqn_{}_weights.h5f'.format('Tik Tak To'), overwrite=True) 254 | 255 | 256 | print(dqn.model) 257 | 258 | print("Testing") 259 | for i in range(10): 260 | done = False 261 | obs = env.reset() 262 | while not done: 263 | obs = obs.reshape((1, 1, -1)) 264 | action =- dqn.model.predict(obs)[0] 265 | for i in range(9): 266 | if env.pos[i]!=0: 267 | action[i] = -1000000 268 | action = np.argmax(action) 269 | obs, reward, done, _ = env.step(action) 270 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /v1/agent_vs_algo.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import gym 3 | import random 4 | import time 5 | import tensorflow as tf 6 | import cv2 7 | from tensorflow.keras.models import Sequential 8 | from tensorflow.keras.layers import * 9 | from tensorflow.keras.optimizers import Adam 10 | 11 | from rl.agents.dqn import DQNAgent 12 | from rl.policy import BoltzmannQPolicy 13 | from rl.memory import SequentialMemory 14 | from rl.random import OrnsteinUhlenbeckProcess 15 | 16 | 17 | class TicTakToe(gym.Env): 18 | metadata = {'render.modes': ['human']} 19 | 20 | def __init__(self): 21 | self.action_space = gym.spaces.Discrete(9) 22 | self.observation_space = gym.spaces.MultiDiscrete([2 for _ in range(0, 9 * 3)]) 23 | self.np_random, _ = gym.utils.seeding.np_random() 24 | self.x = 0 25 | self.y = 0 26 | self.length = 500 27 | self.results = np.array([]) 28 | self.epsilon = 0.900 # Probability with which we select the random move (1-epsilon is the probability with which we select best move) 29 | self.min_epsilon = 0.5 30 | self.epsilon_diff = 0.0001 31 | self.total_games = 0 32 | self.mem_table = dict() 33 | self.neg_reward = 0 34 | 35 | def step(self, action): 36 | 37 | # Take another action if the output square is already filled 38 | if self.pos[action] != 0: 39 | self.neg_reward = max(-0.5, self.neg_reward - .05) 40 | return self.modify_pos(self.pos), self.neg_reward, 0, {} 41 | else: 42 | self.neg_reward = 0 43 | 44 | x = (action // 3) * 100 # X-position of the action 45 | y = (action % 3) * 100 # Y-position of the action 46 | # self.board[x+25: x+75, y+25:y+75] = self.zero # Draw zero on the board_image 47 | self.pos[x // 100 * 3 + y // 100] = 1 # Mark the postion on the board 48 | 49 | res = self.result() # Check if the game has ended 50 | if res == 3: # Draw 51 | # print("Draw") 52 | self.results = np.append(self.results, res) 53 | if self.results.shape[0] > self.length: 54 | self.results = self.results[1:] 55 | self.print_result() 56 | return self.modify_pos(self.pos), 0.5, 1, {} 57 | elif res == 1: # Agent Won 58 | # print("Win") 59 | self.results = np.append(self.results, res) 60 | if self.results.shape[0] > self.length: 61 | self.results = self.results[1:] 62 | self.print_result() 63 | return self.modify_pos(self.pos), 1, 1, {} 64 | 65 | if self.epsilon < random.random(): 66 | best_move = self.get_best_move() 67 | else: 68 | best_move = self.get_random_move() 69 | 70 | self.x = (best_move % 3) * 100 # Get X-position of the Human Player's move 71 | self.y = (best_move // 3) * 100 # Get Y-position of the Human Player's move 72 | 73 | # self.board[self.y+25: self.y+75, self.x+25: self.x+75] = self.cross # Draw Human Player's move on the board_image 74 | self.pos[self.y // 100 * 3 + self.x // 100] = 2 # Make the Human Player's move on the board 75 | 76 | res = self.result() # Check if the game is over 77 | if res == 3: # Draw 78 | # print("Draw") 79 | self.results = np.append(self.results, res) 80 | if self.results.shape[0] > self.length: 81 | self.results = self.results[1:] 82 | self.print_result() 83 | return self.modify_pos(self.pos), 0.5, 1, {} 84 | elif res == 2: # Human Wins 85 | # print("Loss") 86 | self.results = np.append(self.results, res) 87 | if self.results.shape[0] > self.length: 88 | self.results = self.results[1:] 89 | self.print_result() 90 | return self.modify_pos(self.pos), -1, 1, {} 91 | else: 92 | # print("Continue") 93 | return self.modify_pos(self.pos), 0.05, 0, {} 94 | 95 | def modify_pos(self, pos): 96 | #return pos.reshape((3, 3, 1)) 97 | return np.eye(3)[pos].reshape((3,3,3)) 98 | 99 | def get_best_move(self): 100 | board = self.pos 101 | best_move = -1 102 | best_move_val = -100000 103 | for i in range(9): 104 | if board[i] != 0: continue 105 | board[i] = 2 106 | tmp = self.minimax(0, board, 1) 107 | if tmp >= best_move_val: 108 | best_move = i 109 | best_move_val = tmp 110 | board[i] = 0 111 | return best_move 112 | 113 | def get_random_move(self): 114 | moves_left = [] 115 | for i in range(9): 116 | if self.pos[i] == 0: 117 | moves_left.append(i) 118 | best_move = moves_left[random.randint(0, len(moves_left) - 1)] 119 | return best_move 120 | 121 | def print_result(self): 122 | # self.total += 1 123 | # print("Results = ", self.results) 124 | if self.total_games % self.length == 0: 125 | print("\nWin% = ", sum(self.results == 1) / self.results.shape[0], '\tLoss% = ', 126 | sum(self.results == 2) / self.results.shape[0], "\tDraw% = ", 127 | sum(self.results == 3) / self.results.shape[0]) 128 | # print("Epsilon = ", self.epsilon) 129 | # cv2.imshow('img', self.board) 130 | # cv2.waitKey(1) 131 | return None 132 | 133 | def result_2(self, board): # Result function used by the minimax algorithm 134 | if board[0] == board[1] == board[2] == 1 or \ 135 | board[3] == board[4] == board[5] == 1 or \ 136 | board[6] == board[7] == board[8] == 1 or \ 137 | board[0] == board[3] == board[6] == 1 or \ 138 | board[1] == board[4] == board[7] == 1 or \ 139 | board[2] == board[5] == board[8] == 1 or \ 140 | board[0] == board[4] == board[8] == 1 or \ 141 | board[2] == board[4] == board[6] == 1: 142 | return 1 143 | if board[0] == board[1] == board[2] == 2 or \ 144 | board[3] == board[4] == board[5] == 2 or \ 145 | board[6] == board[7] == board[8] == 2 or \ 146 | board[0] == board[3] == board[6] == 2 or \ 147 | board[1] == board[4] == board[7] == 2 or \ 148 | board[2] == board[5] == board[8] == 2 or \ 149 | board[0] == board[4] == board[8] == 2 or \ 150 | board[2] == board[4] == board[6] == 2: 151 | return 2 152 | if sum(board == 0) == 0: return 3 # Draw 153 | return 0 154 | 155 | def minimax(self, maxi, board, depth): # Minimax Algorithm to find the best move 156 | 157 | if tuple(board) in self.mem_table.keys(): 158 | return self.mem_table[tuple(board)] 159 | 160 | if self.result_2(board) != 0: 161 | if self.result_2(board) == 2: 162 | return 100 163 | elif self.result_2(board) == 1: 164 | return -100 165 | else: 166 | return 0 167 | 168 | score = [] 169 | for i in range(9): 170 | if board[i] != 0: continue 171 | board[i] = int(maxi) + 1 172 | # print("Maxi = ", int(maxi)+1) 173 | score.append(self.minimax(not maxi, board, depth + 1)) 174 | board[i] = 0 175 | 176 | if maxi: 177 | self.mem_table[tuple(board)] = max(score) - depth 178 | return max(score) - depth 179 | else: 180 | self.mem_table[tuple(board)] = min(score) - depth 181 | return min(score) - depth 182 | 183 | def result(self): # Result function used to check if the game is over and who is the winner (in the "step" function) 184 | if self.pos[0] == self.pos[1] == self.pos[2] == 1 or \ 185 | self.pos[3] == self.pos[4] == self.pos[5] == 1 or \ 186 | self.pos[6] == self.pos[7] == self.pos[8] == 1 or \ 187 | self.pos[0] == self.pos[3] == self.pos[6] == 1 or \ 188 | self.pos[1] == self.pos[4] == self.pos[7] == 1 or \ 189 | self.pos[2] == self.pos[5] == self.pos[8] == 1 or \ 190 | self.pos[0] == self.pos[4] == self.pos[8] == 1 or \ 191 | self.pos[2] == self.pos[4] == self.pos[6] == 1: 192 | return 1 193 | if self.pos[0] == self.pos[1] == self.pos[2] == 2 or \ 194 | self.pos[3] == self.pos[4] == self.pos[5] == 2 or \ 195 | self.pos[6] == self.pos[7] == self.pos[8] == 2 or \ 196 | self.pos[0] == self.pos[3] == self.pos[6] == 2 or \ 197 | self.pos[1] == self.pos[4] == self.pos[7] == 2 or \ 198 | self.pos[2] == self.pos[5] == self.pos[8] == 2 or \ 199 | self.pos[0] == self.pos[4] == self.pos[8] == 2 or \ 200 | self.pos[2] == self.pos[4] == self.pos[6] == 2: 201 | return 2 202 | if sum(self.pos == 0) == 0: return 3 203 | return 0 204 | 205 | def reset(self): 206 | # self.board = cv2.imread('board.jpg') # Empty board 207 | # self.zero = cv2.imread('zero.jpg') # Agent's mark (zero) 208 | # self.cross = cv2.imread('cross.jpg') # Human player's mark (cross) 209 | 210 | self.pos = np.zeros((9), dtype='int32') # Vector or Matrice of the board postions 211 | #self.pos[random.randint(0, 8)] = 2 212 | self.epsilon = max(self.min_epsilon, self.epsilon - self.epsilon_diff) 213 | self.total_games += 1 214 | self.neg_reward = 0 215 | return self.modify_pos(self.pos) 216 | 217 | def render(self, mode='human'): 218 | return 0 219 | 220 | def close(self): 221 | p.disconnect(self.client) 222 | 223 | def seed(self, seed=None): 224 | self.np_random, seed = gym.utils.seeding.np_random(seed) 225 | return [seed] 226 | 227 | 228 | env = TicTakToe() 229 | env.reset() 230 | nb_actions = env.action_space.n 231 | 232 | print(env.observation_space.shape) 233 | print(nb_actions) 234 | 235 | # Next, we build a very simple model. 236 | model = Sequential() 237 | model.add(Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=(3, 3, 3))) 238 | #model.add(Conv2D(64, (3, 3), padding='same', activation='relu', input_shape=(3, 3, 3))) 239 | model.add(Conv2D(32, (1, 1), padding='same', activation='relu')) 240 | model.add(BatchNormalization()) 241 | #model.add(MaxPooling2D(pool_size=(2, 2))) 242 | #model.add(Flatten(input_shape=(5, 27))) 243 | model.add(Flatten()) 244 | model.add(Dense(32)) 245 | model.add(Activation('relu')) 246 | model.add(Dense(nb_actions)) 247 | model.add(Activation('softmax')) 248 | print(model.summary()) 249 | 250 | 251 | # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and the metrics! 252 | memory = SequentialMemory(limit=50000, window_length=1) 253 | policy = BoltzmannQPolicy() 254 | dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=1000, enable_double_dqn=True, 255 | enable_dueling_network=True, batch_size=512, 256 | dueling_type='avg', target_model_update=1e-2, policy=policy, gamma=0.99) 257 | dqn.compile(Adam(lr=1e-2), metrics=['mse']) 258 | 259 | #dqn.load_weights('dqn_{}_weights.h5f'.format('Tik Tak To')) 260 | 261 | # Okay, now it's time to learn something! We visualize the training here for show, but this 262 | # slows down training quite a lot. You can always safely abort the training prematurely using 263 | dqn.fit(env, nb_steps=200000, visualize=False, verbose=1) 264 | 265 | # After training is done, we save the final weights. 266 | print('Saving Weights') 267 | dqn.save_weights('dqn_{}_weights.h5f'.format('Tik Tak To'), overwrite=True) 268 | 269 | # print(dqn.model) 270 | # 271 | print("Testing") 272 | for i in range(10000): 273 | done = False 274 | obs = env.reset() 275 | while not done: 276 | obs = obs.reshape((1, 3, 3, 3)) 277 | action = - dqn.model.predict(obs)[0] 278 | for i in range(9): 279 | if env.pos[i] != 0: 280 | action[i] = -1000000 281 | action = np.argmax(action) 282 | obs, reward, done, _ = env.step(action) 283 | -------------------------------------------------------------------------------- /v1/ttt_value_iter_model_human_training.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "training model from scratch with human player, " 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import numpy as np\n", 17 | "import pickle\n", 18 | "import time" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 2, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "class State:\n", 28 | " def __init__(self, c, h):\n", 29 | " self.board = np.zeros((3,3))\n", 30 | " self.c = c\n", 31 | " self.h = h\n", 32 | " self.isEnd = False\n", 33 | " self.boardHash = None\n", 34 | " self.playerSymbol = 1\n", 35 | "\n", 36 | " def getHash(self):\n", 37 | " self.boardHash = str(self.board.reshape(3*3))\n", 38 | " return self.boardHash\n", 39 | "\n", 40 | " def availablePositions(self):\n", 41 | " positions = []\n", 42 | " for i in range(3):\n", 43 | " for j in range(3):\n", 44 | " if self.board[i,j] == 0:\n", 45 | " positions.append((i,j))\n", 46 | " return positions\n", 47 | "\n", 48 | " def updateState(self, position):\n", 49 | " self.board[position] = self.playerSymbol\n", 50 | " self.playerSymbol = -1 if self.playerSymbol == 1 else 1\n", 51 | "\n", 52 | " def winner(self):\n", 53 | " # by row or column winner\n", 54 | " for i in range(3):\n", 55 | " if sum(self.board[i, :]) == 3: \n", 56 | " self.isEnd = True\n", 57 | " return 1\n", 58 | " if sum(self.board[i, :]) == -3:\n", 59 | " self.isEnd = True\n", 60 | " return -1\n", 61 | " if sum(self.board[:, i]) == 3: \n", 62 | " self.isEnd = True\n", 63 | " return 1\n", 64 | " if sum(self.board[:, i]) == -3:\n", 65 | " self.isEnd = True\n", 66 | " return -1\n", 67 | "\n", 68 | " # by diagonal winner\n", 69 | " diag_sum1 = sum([self.board[i,i] for i in range(3)])\n", 70 | " diag_sum2 = sum([self.board[i, 3-i-1] for i in range(3)])\n", 71 | " diag_sum = max(abs(diag_sum1), abs(diag_sum2))\n", 72 | " if diag_sum == 3:\n", 73 | " self.isEnd = True\n", 74 | " if diag_sum1 == 3 or diag_sum2 == 3:\n", 75 | " return 1\n", 76 | " else:\n", 77 | " return -1\n", 78 | "\n", 79 | " # if all filled (tie)\n", 80 | " if len(self.availablePositions()) == 0:\n", 81 | " self.isEnd = True\n", 82 | " return 0\n", 83 | " \n", 84 | " # nota (game continues)\n", 85 | " self.isEnd = False\n", 86 | " return None\n", 87 | "\n", 88 | " def giveReward(self):\n", 89 | " result = self.winner()\n", 90 | " if result == 1: # if computer wins\n", 91 | " self.c.feedReward(1)\n", 92 | " elif result == -1:\n", 93 | " self.c.feedReward(-1)\n", 94 | " else:\n", 95 | " self.c.feedReward(0)\n", 96 | "\n", 97 | " def reset(self):\n", 98 | " self.board = np.zeros((3,3))\n", 99 | " self.boardHash = None\n", 100 | " self.isEnd = False\n", 101 | " self.playerSymbol = 1\n", 102 | "\n", 103 | " def play(self, rounds = 100):\n", 104 | " while not self.isEnd:\n", 105 | " #player computer\n", 106 | " print(\"computer turn\")\n", 107 | " positions = self.availablePositions()\n", 108 | " # print(\"positions:\", positions)\n", 109 | " c_action = self.c.chooseAction(positions, self.board, self.playerSymbol)\n", 110 | " print('c_action:', c_action)\n", 111 | " self.updateState(c_action)\n", 112 | " board_hash = self.getHash()\n", 113 | " self.c.addState(board_hash)\n", 114 | " self.showBoard()\n", 115 | " print(\"states_value length\", len(self.c.states_value))\n", 116 | " # print(\"c states values\", self.c.states_value)\n", 117 | " \n", 118 | " win = self.winner()\n", 119 | " if win is not None:\n", 120 | " if win == 1:\n", 121 | " print(self.c.name, \"wins\")\n", 122 | " else:\n", 123 | " print(\"tie\")\n", 124 | " self.giveReward()\n", 125 | " self.c.reset()\n", 126 | " self.h.reset()\n", 127 | " self.reset()\n", 128 | " break\n", 129 | " \n", 130 | " # player human\n", 131 | " else:\n", 132 | " print(\"human turn\")\n", 133 | " positions = self.availablePositions()\n", 134 | " # print(\"positions:\", positions)\n", 135 | " h_action = self.h.chooseAction(positions)\n", 136 | " # print('h_action:', h_action)\n", 137 | " self.updateState(h_action)\n", 138 | " # board_hash = self.getHash()\n", 139 | " # self.h.addState(board_hash)\n", 140 | " self.showBoard()\n", 141 | "\n", 142 | " win = self.winner()\n", 143 | " if win is not None:\n", 144 | " if win == -1:\n", 145 | " print(self.h.name, \"wins\")\n", 146 | " else:\n", 147 | " print(\"tie\")\n", 148 | " self.giveReward()\n", 149 | " self.c.reset()\n", 150 | " self.h.reset()\n", 151 | " self.reset()\n", 152 | " break\n", 153 | " # self.c.savePolicy()\n", 154 | "\n", 155 | " def showBoard(self):\n", 156 | " # p1: X, p2: O\n", 157 | " for i in range(3):\n", 158 | " print(\"-------------\")\n", 159 | " out = '| '\n", 160 | " for j in range(3):\n", 161 | " if self.board[i,j] == 1:\n", 162 | " token = \"X\"\n", 163 | " if self.board[i,j] == -1:\n", 164 | " token = \"O\"\n", 165 | " if self.board[i,j] == 0:\n", 166 | " token = \" \"\n", 167 | " out += token + ' | '\n", 168 | " print(out)\n", 169 | " print(\"--------------\")\n", 170 | "\n", 171 | "\n", 172 | "\n", 173 | "class Player:\n", 174 | " def __init__(self, name, exp_rate = 0.3):\n", 175 | " self.name = name\n", 176 | " self.states = []\n", 177 | " self.lr = 0.2\n", 178 | " self.exp_rate = 0.3\n", 179 | " self.decay_gamma = 0.9\n", 180 | " self.states_value = {}\n", 181 | "\n", 182 | " def getHash(self, board):\n", 183 | " boardHash = str(board.reshape(3*3))\n", 184 | " return boardHash\n", 185 | "\n", 186 | " def chooseAction(self, positions, current_board, symbol):\n", 187 | " if np.random.uniform(0,1) <= self.exp_rate:\n", 188 | " idx = np.random.choice(len(positions))\n", 189 | " action = positions[idx]\n", 190 | " # print(\"explored action\", action)\n", 191 | " return action\n", 192 | " else:\n", 193 | " value_max = -999\n", 194 | " for p in positions:\n", 195 | " next_board = current_board.copy()\n", 196 | " next_board[p] = symbol\n", 197 | " # print(\"next board \\n\", next_board)\n", 198 | " next_boardHash = self.getHash(next_board)\n", 199 | " # print(\"next boardhash \", next_boardHash)\n", 200 | " value = 0 if self.states_value.get(next_boardHash) is None else self.states_value.get(next_boardHash)\n", 201 | " # print(self.states_value)\n", 202 | " # print(\"value\", value)\n", 203 | " # print('max_value:', value_max)\n", 204 | " if value >= value_max:\n", 205 | " value_max = value\n", 206 | " action = p\n", 207 | " # print(\"learned action\", action)\n", 208 | " return action\n", 209 | "\n", 210 | " def addState(self, state):\n", 211 | " self.states.append(state)\n", 212 | " \n", 213 | " def feedReward(self, reward):\n", 214 | " for st in reversed(self.states):\n", 215 | " if self.states_value.get(st) is None:\n", 216 | " self.states_value[st] = 0\n", 217 | " self.states_value[st] += self.lr * (self.decay_gamma * reward - self.states_value[st])\n", 218 | " reward = self.states_value[st]\n", 219 | "\n", 220 | " def reset(self):\n", 221 | " self.states = []\n", 222 | "\n", 223 | " def savePolicy(self):\n", 224 | " fw = open('policy_one_' + str(self.name), 'wb')\n", 225 | " pickle.dump(self.states_value, fw)\n", 226 | " fw.close()\n", 227 | "\n", 228 | " def loadPolicy(self, file):\n", 229 | " fr = open(file, 'rb')\n", 230 | " self.states_value = pickle.load(fr)\n", 231 | " fr.close()\n", 232 | "\n", 233 | "\n", 234 | "\n", 235 | "class HumanPlayer:\n", 236 | " def __init__(self, name):\n", 237 | " self.name = name\n", 238 | "\n", 239 | " def chooseAction(self, positions):\n", 240 | " while True:\n", 241 | " moves = {\n", 242 | " 7: (0,0), 8:(0,1), 9:(0,2),\n", 243 | " 4: (1,0), 5:(1,1), 6:(1,2),\n", 244 | " 1: (2,0), 2:(2,1), 3:(2,2)\n", 245 | " }\n", 246 | "\n", 247 | " move = int(input(\"Input Move(1-9): \"))\n", 248 | " action = moves[move]\n", 249 | "\n", 250 | " if action in positions:\n", 251 | " return action\n", 252 | "\n", 253 | " def addState(self, state):\n", 254 | " pass\n", 255 | "\n", 256 | " def feedReward(self, reward):\n", 257 | " pass\n", 258 | "\n", 259 | " def reset(self):\n", 260 | " pass" 261 | ] 262 | }, 263 | { 264 | "cell_type": "code", 265 | "execution_count": 3, 266 | "metadata": {}, 267 | "outputs": [ 268 | { 269 | "name": "stdout", 270 | "output_type": "stream", 271 | "text": [ 272 | "Round: 1\n", 273 | "computer turn\n", 274 | "c_action: (2, 2)\n", 275 | "-------------\n", 276 | "| | | | \n", 277 | "-------------\n", 278 | "| | | | \n", 279 | "-------------\n", 280 | "| | | X | \n", 281 | "--------------\n", 282 | "states_value length 0\n", 283 | "human turn\n", 284 | "-------------\n", 285 | "| | | | \n", 286 | "-------------\n", 287 | "| | | | \n", 288 | "-------------\n", 289 | "| | O | X | \n", 290 | "--------------\n", 291 | "computer turn\n", 292 | "c_action: (2, 0)\n", 293 | "-------------\n", 294 | "| | | | \n", 295 | "-------------\n", 296 | "| | | | \n", 297 | "-------------\n", 298 | "| X | O | X | \n", 299 | "--------------\n", 300 | "states_value length 0\n", 301 | "human turn\n", 302 | "-------------\n", 303 | "| | | | \n", 304 | "-------------\n", 305 | "| | O | | \n", 306 | "-------------\n", 307 | "| X | O | X | \n", 308 | "--------------\n", 309 | "computer turn\n", 310 | "c_action: (1, 2)\n", 311 | "-------------\n", 312 | "| | | | \n", 313 | "-------------\n", 314 | "| | O | X | \n", 315 | "-------------\n", 316 | "| X | O | X | \n", 317 | "--------------\n", 318 | "states_value length 0\n", 319 | "human turn\n", 320 | "-------------\n", 321 | "| | O | | \n", 322 | "-------------\n", 323 | "| | O | X | \n", 324 | "-------------\n", 325 | "| X | O | X | \n", 326 | "--------------\n", 327 | "human wins\n", 328 | "Round: 2\n", 329 | "computer turn\n", 330 | "c_action: (2, 1)\n", 331 | "-------------\n", 332 | "| | | | \n", 333 | "-------------\n", 334 | "| | | | \n", 335 | "-------------\n", 336 | "| | X | | \n", 337 | "--------------\n", 338 | "states_value length 3\n", 339 | "human turn\n" 340 | ] 341 | }, 342 | { 343 | "ename": "ValueError", 344 | "evalue": "invalid literal for int() with base 10: ''", 345 | "output_type": "error", 346 | "traceback": [ 347 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 348 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", 349 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 15\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 16\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Round:\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 17\u001b[0;31m \u001b[0mst\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mplay\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 18\u001b[0m \u001b[0;31m# comp.loadPolicy(\"policy_one_computer\")\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 350 | "\u001b[0;32m\u001b[0m in \u001b[0;36mplay\u001b[0;34m(self, rounds)\u001b[0m\n\u001b[1;32m 107\u001b[0m \u001b[0mpositions\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mavailablePositions\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 108\u001b[0m \u001b[0;31m# print(\"positions:\", positions)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 109\u001b[0;31m \u001b[0mh_action\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mh\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mchooseAction\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mpositions\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 110\u001b[0m \u001b[0;31m# print('h_action:', h_action)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 111\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mupdateState\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mh_action\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 351 | "\u001b[0;32m\u001b[0m in \u001b[0;36mchooseAction\u001b[0;34m(self, positions)\u001b[0m\n\u001b[1;32m 219\u001b[0m }\n\u001b[1;32m 220\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 221\u001b[0;31m \u001b[0mmove\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Input Move(1-9): \"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 222\u001b[0m \u001b[0maction\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmoves\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mmove\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 223\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", 352 | "\u001b[0;31mValueError\u001b[0m: invalid literal for int() with base 10: ''" 353 | ] 354 | } 355 | ], 356 | "source": [ 357 | "if __name__ == \"__main__\":\n", 358 | " # p1 = Player(\"p1\")\n", 359 | " # p2 = Player(\"p2\")\n", 360 | "\n", 361 | " # st = State(p1, p2)\n", 362 | " # print(\"training...\")\n", 363 | " # st.play(1)\n", 364 | "\n", 365 | " comp = Player('computer', exp_rate = 0.3)\n", 366 | " \n", 367 | " human = HumanPlayer('human')\n", 368 | "\n", 369 | " st = State(comp, human)\n", 370 | " # open('policy_one_' + str(\"computer\"), 'wb')\n", 371 | " for i in range(3):\n", 372 | " print(\"Round:\", i+1)\n", 373 | " st.play()\n", 374 | " # comp.loadPolicy(\"policy_one_computer\")" 375 | ] 376 | }, 377 | { 378 | "cell_type": "code", 379 | "execution_count": null, 380 | "metadata": {}, 381 | "outputs": [], 382 | "source": [] 383 | } 384 | ], 385 | "metadata": { 386 | "interpreter": { 387 | "hash": "286e774b504df13e04a7d8e77e6d4af77665f84c20482e9e6db1a1f534c37820" 388 | }, 389 | "kernelspec": { 390 | "display_name": "Python 3", 391 | "language": "python", 392 | "name": "python3" 393 | }, 394 | "language_info": { 395 | "codemirror_mode": { 396 | "name": "ipython", 397 | "version": 3 398 | }, 399 | "file_extension": ".py", 400 | "mimetype": "text/x-python", 401 | "name": "python", 402 | "nbconvert_exporter": "python", 403 | "pygments_lexer": "ipython3", 404 | "version": "3.8.8" 405 | } 406 | }, 407 | "nbformat": 4, 408 | "nbformat_minor": 4 409 | } 410 | -------------------------------------------------------------------------------- /v1/ttt_value_iteration_self_training.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import numpy as np\n", 10 | "import pickle\n", 11 | "import time" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 2, 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "class State:\n", 21 | " def __init__(self, p1, p2):\n", 22 | " self.board = np.zeros((3,3))\n", 23 | " self.p1 = p1\n", 24 | " self.p2 = p2\n", 25 | " self.isEnd = False\n", 26 | " self.boardHash = None\n", 27 | " self.playerSymbol = 1\n", 28 | "\n", 29 | " def getHash(self):\n", 30 | " self.boardHash = str(self.board.reshape(3*3))\n", 31 | " return self.boardHash\n", 32 | "\n", 33 | " def availablePositions(self):\n", 34 | " positions = []\n", 35 | " for i in range(3):\n", 36 | " for j in range(3):\n", 37 | " if self.board[i,j] == 0:\n", 38 | " positions.append((i,j))\n", 39 | " return positions\n", 40 | "\n", 41 | " def updateState(self, position):\n", 42 | " self.board[position] = self.playerSymbol\n", 43 | " self.playerSymbol = -1 if self.playerSymbol == 1 else 1\n", 44 | "\n", 45 | " def winner(self):\n", 46 | " # by row or column winner\n", 47 | " for i in range(3):\n", 48 | " if sum(self.board[i, :]) == 3: \n", 49 | " self.isEnd = True\n", 50 | " return 1\n", 51 | " if sum(self.board[i, :]) == -3:\n", 52 | " self.isEnd = True\n", 53 | " return -1\n", 54 | " if sum(self.board[:, i]) == 3: \n", 55 | " self.isEnd = True\n", 56 | " return 1\n", 57 | " if sum(self.board[:, i]) == -3:\n", 58 | " self.isEnd = True\n", 59 | " return -1\n", 60 | "\n", 61 | " # by diagonal winner\n", 62 | " diag_sum1 = sum([self.board[i,i] for i in range(3)])\n", 63 | " diag_sum2 = sum([self.board[i, 3-i-1] for i in range(3)])\n", 64 | " diag_sum = max(abs(diag_sum1), abs(diag_sum2))\n", 65 | " if diag_sum == 3:\n", 66 | " self.isEnd = True\n", 67 | " if diag_sum1 == 3 or diag_sum2 == 3:\n", 68 | " return 1\n", 69 | " else:\n", 70 | " return -1\n", 71 | "\n", 72 | " # if all filled (tie)\n", 73 | " if len(self.availablePositions()) == 0:\n", 74 | " self.isEnd = True\n", 75 | " return 0\n", 76 | " \n", 77 | " # nota (game continues)\n", 78 | " self.isEnd = False\n", 79 | " return None\n", 80 | "\n", 81 | " def giveReward(self):\n", 82 | " result = self.winner()\n", 83 | " if result == 1:\n", 84 | " self.p1.feedReward(1)\n", 85 | " self.p2.feedReward(0)\n", 86 | " elif result == -1:\n", 87 | " self.p1.feedReward(0)\n", 88 | " self.p2.feedReward(1)\n", 89 | " else:\n", 90 | " self.p1.feedReward(0.1)\n", 91 | " self.p2.feedReward(0.5)\n", 92 | "\n", 93 | " def reset(self):\n", 94 | " self.board = np.zeros((3,3))\n", 95 | " self.boardHash = None\n", 96 | " self.isEnd = False\n", 97 | " self.playerSymbol = 1\n", 98 | "\n", 99 | "\n", 100 | " def play(self, rounds = 100):\n", 101 | " for i in range(rounds):\n", 102 | " if i%1000 == 0:\n", 103 | " print(\"\\nRounds\", i)\n", 104 | " if i%2 == 0:\n", 105 | " while not self.isEnd:\n", 106 | " #player 1\n", 107 | " # print(\"player 1 turn\")\n", 108 | " positions = self.availablePositions()\n", 109 | " # print(\"positions:\", positions)\n", 110 | " p1_action = self.p1.chooseAction(positions, self.board, self.playerSymbol)\n", 111 | " # print('p1_action:', p1_action)\n", 112 | " self.updateState(p1_action)\n", 113 | " board_hash = self.getHash()\n", 114 | " self.p1.addState(board_hash)\n", 115 | " # print(\"p1 states values\", self.p1.states_value)\n", 116 | "\n", 117 | " win = self.winner()\n", 118 | " if win is not None:\n", 119 | " if win == 1:\n", 120 | " print(self.p1.name, \"wins\")\n", 121 | " else:\n", 122 | " print(\"tie\")\n", 123 | " self.giveReward()\n", 124 | " self.p1.reset()\n", 125 | " self.p2.reset()\n", 126 | " self.reset()\n", 127 | " break\n", 128 | " \n", 129 | " # player 2\n", 130 | " else:\n", 131 | " # print(\"player 2 turn\")\n", 132 | " positions = self.availablePositions()\n", 133 | " # print(\"positions:\", positions)\n", 134 | " p2_action = self.p2.chooseAction(positions, self.board, self.playerSymbol)\n", 135 | " # print('p2_action:', p2_action)\n", 136 | " self.updateState(p2_action)\n", 137 | " board_hash = self.getHash()\n", 138 | " self.p2.addState(board_hash)\n", 139 | "\n", 140 | " win = self.winner()\n", 141 | " if win is not None:\n", 142 | " if win == 1:\n", 143 | " print(self.p1.name, \"wins\")\n", 144 | " else:\n", 145 | " print(\"tie\")\n", 146 | " self.giveReward()\n", 147 | " self.p1.reset()\n", 148 | " self.p2.reset()\n", 149 | " self.reset()\n", 150 | " break\n", 151 | "\n", 152 | " else:\n", 153 | " while not self.isEnd:\n", 154 | " #player 2\n", 155 | " # print(\"player 2 turn\")\n", 156 | " positions = self.availablePositions()\n", 157 | " # print(\"positions:\", positions)\n", 158 | " p2_action = self.p2.chooseAction(positions, self.board, self.playerSymbol)\n", 159 | " # print('p2_action:', p2_action)\n", 160 | " self.updateState(p2_action)\n", 161 | " board_hash = self.getHash()\n", 162 | " self.p2.addState(board_hash)\n", 163 | " # print(\"p2 states values\", self.p2.states_value)\n", 164 | "\n", 165 | " win = self.winner()\n", 166 | " if win is not None:\n", 167 | " if win == 1:\n", 168 | " print(self.p2.name, \"wins\")\n", 169 | " else:\n", 170 | " print(\"tie\")\n", 171 | " self.giveReward()\n", 172 | " self.p1.reset()\n", 173 | " self.p2.reset()\n", 174 | " self.reset()\n", 175 | " break\n", 176 | " \n", 177 | " # player 1\n", 178 | " else:\n", 179 | " # print(\"player 1 turn\")\n", 180 | " positions = self.availablePositions()\n", 181 | " # print(\"positions:\", positions)\n", 182 | " p1_action = self.p1.chooseAction(positions, self.board, self.playerSymbol)\n", 183 | " # print('p1_action:', p1_action)\n", 184 | " self.updateState(p1_action)\n", 185 | " board_hash = self.getHash()\n", 186 | " self.p1.addState(board_hash)\n", 187 | " win = self.winner()\n", 188 | " if win is not None:\n", 189 | " if win == 1:\n", 190 | " print(self.p1.name, \"wins\")\n", 191 | " else:\n", 192 | " print(\"tie\")\n", 193 | " self.giveReward()\n", 194 | " self.p1.reset()\n", 195 | " self.p2.reset()\n", 196 | " self.reset()\n", 197 | " break\n", 198 | "\n", 199 | " \n", 200 | "\n", 201 | " # self.p1.savePolicy()\n", 202 | "\n", 203 | " def play2(self):\n", 204 | " while not self.isEnd:\n", 205 | " #player 1\n", 206 | " positions = self.availablePositions()\n", 207 | " p1_action = self.p1.chooseAction(positions, self.board, self.playerSymbol)\n", 208 | " self.updateState(p1_action)\n", 209 | " # print(\"Computer Turn\")\n", 210 | " time.sleep(1)\n", 211 | " self.showBoard()\n", 212 | " print(\"Human Turn\")\n", 213 | " print()\n", 214 | "\n", 215 | " win = self.winner()\n", 216 | " if win is not None:\n", 217 | " if win == 1:\n", 218 | " print(self.p1.name, \"wins\")\n", 219 | " else:\n", 220 | " print(\"tie\")\n", 221 | " self.reset()\n", 222 | " break\n", 223 | "\n", 224 | " else:\n", 225 | " positions = self.availablePositions()\n", 226 | " p2_action = self.p2.chooseAction(positions)\n", 227 | " self.updateState(p2_action)\n", 228 | " self.showBoard()\n", 229 | "\n", 230 | " win = self.winner()\n", 231 | " if win is not None:\n", 232 | " if win == -1:\n", 233 | " print(self.p2.name, \"wins\")\n", 234 | " else:\n", 235 | " print(\"tie\")\n", 236 | " self.reset()\n", 237 | " break\n", 238 | "\n", 239 | " def showBoard(self):\n", 240 | " # p1: X, p2: O\n", 241 | " for i in range(3):\n", 242 | " print(\"-------------\")\n", 243 | " out = '| '\n", 244 | " for j in range(3):\n", 245 | " if self.board[i,j] == 1:\n", 246 | " token = \"X\"\n", 247 | " if self.board[i,j] == -1:\n", 248 | " token = \"O\"\n", 249 | " if self.board[i,j] == 0:\n", 250 | " token = \" \"\n", 251 | " out += token + ' | '\n", 252 | " print(out)\n", 253 | " print(\"--------------\")\n", 254 | "\n", 255 | "\n", 256 | "class Player:\n", 257 | " def __init__(self, name, exp_rate = 0.3):\n", 258 | " self.name = name\n", 259 | " self.states = []\n", 260 | " self.lr = 0.2\n", 261 | " self.exp_rate = 0.3\n", 262 | " self.decay_gamma = 0.9\n", 263 | " self.states_value = {}\n", 264 | "\n", 265 | "\n", 266 | " def getHash(self, board):\n", 267 | " boardHash = str(board.reshape(3*3))\n", 268 | " return boardHash\n", 269 | " \n", 270 | "\n", 271 | " def chooseAction(self, positions, current_board, symbol):\n", 272 | " if np.random.uniform(0,1) <= self.exp_rate:\n", 273 | " idx = np.random.choice(len(positions))\n", 274 | " action = positions[idx]\n", 275 | " # print(\"explored action\", action)\n", 276 | " return action\n", 277 | " else:\n", 278 | " value_max = -999\n", 279 | " for p in positions:\n", 280 | " next_board = current_board.copy()\n", 281 | " next_board[p] = symbol\n", 282 | " # print(\"next board \\n\", next_board)\n", 283 | " next_boardHash = self.getHash(next_board)\n", 284 | " # print(\"next boardhash \", next_boardHash)\n", 285 | " value = 0 if self.states_value.get(next_boardHash) is None else self.states_value.get(next_boardHash)\n", 286 | " # print(self.states_value)\n", 287 | " # print(\"value\", value)\n", 288 | " # print('max_value:', value_max)\n", 289 | " if value >= value_max:\n", 290 | " value_max = value\n", 291 | " action = p\n", 292 | " # print(\"learned action\", action)\n", 293 | " return action\n", 294 | "\n", 295 | " def addState(self, state):\n", 296 | " self.states.append(state)\n", 297 | " \n", 298 | " def feedReward(self, reward):\n", 299 | " for st in reversed(self.states):\n", 300 | " if self.states_value.get(st) is None:\n", 301 | " self.states_value[st] = 0\n", 302 | " self.states_value[st] += self.lr * (self.decay_gamma * reward - self.states_value[st])\n", 303 | " reward = self.states_value[st]\n", 304 | "\n", 305 | " def reset(self):\n", 306 | " self.states = []\n", 307 | "\n", 308 | " def savePolicy(self):\n", 309 | " fw = open('policy_' + str(self.name), 'wb')\n", 310 | " pickle.dump(self.states_value, fw)\n", 311 | " fw.close()\n", 312 | "\n", 313 | " def loadPolicy(self, file):\n", 314 | " fr = open(file, 'rb')\n", 315 | " self.states_value = pickle.load(fr)\n", 316 | " fr.close()\n", 317 | "\n", 318 | "\n", 319 | "class HumanPlayer:\n", 320 | " def __init__(self, name):\n", 321 | " self.name = name\n", 322 | "\n", 323 | " def chooseAction(self, positions):\n", 324 | " while True:\n", 325 | " moves = {\n", 326 | " 7: (0,0), 8:(0,1), 9:(0,2),\n", 327 | " 4: (1,0), 5:(1,1), 6:(1,2),\n", 328 | " 1: (2,0), 2:(2,1), 3:(2,2)\n", 329 | " }\n", 330 | "\n", 331 | " move = int(input(\"Input Move(1-9): \"))\n", 332 | " action = moves[move]\n", 333 | "\n", 334 | " if action in positions:\n", 335 | " return action\n", 336 | "\n", 337 | " def addState(self, state):\n", 338 | " pass\n", 339 | "\n", 340 | " def feedReward(self, reward):\n", 341 | " pass\n", 342 | "\n", 343 | " def reset(self):\n", 344 | " pass\n", 345 | "\n" 346 | ] 347 | }, 348 | { 349 | "cell_type": "code", 350 | "execution_count": 17, 351 | "metadata": {}, 352 | "outputs": [ 353 | { 354 | "name": "stdout", 355 | "output_type": "stream", 356 | "text": [ 357 | "-------------\n", 358 | "| | | X | \n", 359 | "-------------\n", 360 | "| | | | \n", 361 | "-------------\n", 362 | "| | | | \n", 363 | "--------------\n", 364 | "Human Turn\n", 365 | "\n" 366 | ] 367 | }, 368 | { 369 | "name": "stdin", 370 | "output_type": "stream", 371 | "text": [ 372 | "Input Move(1-9): 5\n" 373 | ] 374 | }, 375 | { 376 | "name": "stdout", 377 | "output_type": "stream", 378 | "text": [ 379 | "-------------\n", 380 | "| | | X | \n", 381 | "-------------\n", 382 | "| | O | | \n", 383 | "-------------\n", 384 | "| | | | \n", 385 | "--------------\n", 386 | "-------------\n", 387 | "| | | X | \n", 388 | "-------------\n", 389 | "| X | O | | \n", 390 | "-------------\n", 391 | "| | | | \n", 392 | "--------------\n", 393 | "Human Turn\n", 394 | "\n" 395 | ] 396 | }, 397 | { 398 | "name": "stdin", 399 | "output_type": "stream", 400 | "text": [ 401 | "Input Move(1-9): 7\n" 402 | ] 403 | }, 404 | { 405 | "name": "stdout", 406 | "output_type": "stream", 407 | "text": [ 408 | "-------------\n", 409 | "| O | | X | \n", 410 | "-------------\n", 411 | "| X | O | | \n", 412 | "-------------\n", 413 | "| | | | \n", 414 | "--------------\n", 415 | "-------------\n", 416 | "| O | | X | \n", 417 | "-------------\n", 418 | "| X | O | | \n", 419 | "-------------\n", 420 | "| | | X | \n", 421 | "--------------\n", 422 | "Human Turn\n", 423 | "\n" 424 | ] 425 | }, 426 | { 427 | "name": "stdin", 428 | "output_type": "stream", 429 | "text": [ 430 | "Input Move(1-9): 8\n" 431 | ] 432 | }, 433 | { 434 | "name": "stdout", 435 | "output_type": "stream", 436 | "text": [ 437 | "-------------\n", 438 | "| O | O | X | \n", 439 | "-------------\n", 440 | "| X | O | | \n", 441 | "-------------\n", 442 | "| | | X | \n", 443 | "--------------\n", 444 | "-------------\n", 445 | "| O | O | X | \n", 446 | "-------------\n", 447 | "| X | O | | \n", 448 | "-------------\n", 449 | "| | X | X | \n", 450 | "--------------\n", 451 | "Human Turn\n", 452 | "\n" 453 | ] 454 | }, 455 | { 456 | "name": "stdin", 457 | "output_type": "stream", 458 | "text": [ 459 | "Input Move(1-9): 1\n" 460 | ] 461 | }, 462 | { 463 | "name": "stdout", 464 | "output_type": "stream", 465 | "text": [ 466 | "-------------\n", 467 | "| O | O | X | \n", 468 | "-------------\n", 469 | "| X | O | | \n", 470 | "-------------\n", 471 | "| O | X | X | \n", 472 | "--------------\n", 473 | "-------------\n", 474 | "| O | O | X | \n", 475 | "-------------\n", 476 | "| X | O | X | \n", 477 | "-------------\n", 478 | "| O | X | X | \n", 479 | "--------------\n", 480 | "Human Turn\n", 481 | "\n", 482 | "p2 wins\n" 483 | ] 484 | } 485 | ], 486 | "source": [ 487 | "if __name__ == \"__main__\":\n", 488 | " #p1 = Player(\"p1\")\n", 489 | " #p2 = Player(\"p2\")\n", 490 | "\n", 491 | " #st = State(p1, p2)\n", 492 | " #print(\"training...\")\n", 493 | " #st.play(100000)\n", 494 | "\n", 495 | " #p1 = Player('computer', exp_rate = 0)\n", 496 | " #p1.loadPolicy(\"policy_p1\")\n", 497 | "\n", 498 | " p3 = HumanPlayer('human')\n", 499 | "\n", 500 | " st = State(p2, p3)\n", 501 | " st.play2()" 502 | ] 503 | }, 504 | { 505 | "cell_type": "code", 506 | "execution_count": null, 507 | "metadata": {}, 508 | "outputs": [], 509 | "source": [] 510 | } 511 | ], 512 | "metadata": { 513 | "interpreter": { 514 | "hash": "286e774b504df13e04a7d8e77e6d4af77665f84c20482e9e6db1a1f534c37820" 515 | }, 516 | "kernelspec": { 517 | "display_name": "Python 3", 518 | "language": "python", 519 | "name": "python3" 520 | }, 521 | "language_info": { 522 | "codemirror_mode": { 523 | "name": "ipython", 524 | "version": 3 525 | }, 526 | "file_extension": ".py", 527 | "mimetype": "text/x-python", 528 | "name": "python", 529 | "nbconvert_exporter": "python", 530 | "pygments_lexer": "ipython3", 531 | "version": "3.8.8" 532 | } 533 | }, 534 | "nbformat": 4, 535 | "nbformat_minor": 4 536 | } 537 | --------------------------------------------------------------------------------