<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Corino on Medium]]></title>
        <description><![CDATA[Stories by Corino on Medium]]></description>
        <link>https://medium.com/@mycorino?source=rss-3ea1071f44c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ABwOK2NA0lj4Dt1u</url>
            <title>Stories by Corino on Medium</title>
            <link>https://medium.com/@mycorino?source=rss-3ea1071f44c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:48:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mycorino/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Deep Q-Network powered Poker Bot]]></title>
            <link>https://medium.com/@mycorino/building-a-deep-q-network-powered-poker-bot-1a48e296805d?source=rss-3ea1071f44c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a48e296805d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[poker]]></category>
            <dc:creator><![CDATA[Corino]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 22:20:18 GMT</pubDate>
            <atom:updated>2024-04-22T22:20:18.171Z</atom:updated>
            <content:encoded><![CDATA[<p>The other day I played poker with friends and thought how fun it would be to be able to train a computer to bluff and be better than humans at this game, a new project was born.</p><p>The intersection of gaming and AI has always fascinated me, particularly the strategic elements involved in card games like poker. Poker is not just a game of luck; it involves deep strategic thinking, probability, and the ability to make decisions based on incomplete information.</p><p>Why focus on a poker bot? The answer lies in the challenge it presents: poker is a dynamic and unpredictable game, making it an excellent testbed for exploring and advancing the capabilities of more complex ml models like deep reinforcement learning. I had never had the chance to implement deep reinforcement learning so I thought one calm evening lets dive into it.</p><p>In this article, I’ll share the journey of creating a poker bot using deep reinforcement learning. I’ll cover everything from the initial setup and the challenges faced, to the insights gained from implementing this project. Whether you’re an AI enthusiast, a fellow data scientist, or just curious about the application of AI in gaming, I hope you find this exploration both informative and inspiring.</p><p>Ps. The full code is shown as in my notebook so you can copy it all and run it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tx6pXAJ8Lc8vTd2Qs_1HA.png" /><figcaption>AI poker bot generated using DALL.E</figcaption></figure><h3>Technical setup</h3><p>In this project, we leveraged TensorFlow for implementing deep reinforcement learning algorithms and PyPokerEngine for simulating poker games, supported by Python libraries like NumPy for data manipulation and Matplotlib for visualization. This setup ensures that our poker bot is not only robust but also easily replicable, providing fellow data scientists with a clear path to explore and enhance AI-driven strategies in gaming (but not only).</p><pre>!pip install PyPokerEngine <br>!pip install tensorflow</pre><pre># Standard library imports<br>import os<br>import random<br>import sys<br>import contextlib<br>from collections import deque<br><br># Third-party library imports for data handling and machine learning<br>import numpy as np<br>import tensorflow as tf<br>from tensorflow import keras<br>from tensorflow.keras import models, layers, Input<br>from tensorflow.keras.utils import to_categorical<br><br># Visualization libraries<br>import matplotlib.pyplot as plt<br>from IPython.display import clear_output<br><br># PyPokerEngine imports for game setup and player configuration<br>from pypokerengine.api.game import setup_config, start_poker<br>from pypokerengine.players import BasePokerPlayer</pre><h3>I. Testing the PyPokerEngine with a random player and a smart(er) player</h3><h4>A. Building a random player class we can use in Pypokerengine</h4><p>Creating a RandomPlayer class: This class inherits from BasePokerPlayer provided by PyPokerEngine. It overrides the declare_action method to randomly choose an action from the list of valid actions at each decision point. The other methods are placeholders required by the interface, but they don’t do anything in this simple example.</p><p>Setting up the game configuration: We use setup_config to configure the game. Here, we specify that we want to play 10 rounds, each player starts with 1000 chips, and the small blind is 10 chips. Then, we register two players using our RandomPlayer class.</p><p>Starting the game: Finally, we call start_poker with our game configuration. The verbose=1 argument enables detailed logging of the game’s progress in the console, which is useful for debugging and understanding how the game flows.</p><p>This setup provides a basic environment where two players make random decisions. It’s a good starting point for testing the framework and eventually integrating more sophisticated AI algorithms. Remember, this is a very basic bot for demonstration purposes.</p><pre>class RandomPlayer(BasePokerPlayer):<br><br><br>    def declare_action(self, valid_actions, hole_card, round_state):<br>        # Choose a random action from the list of valid actions<br>        action = random.choice(valid_actions)<br><br>        # For &#39;raise&#39; action, choose a valid raise amount within the allowed range<br>        if action[&#39;action&#39;] == &#39;raise&#39;:<br>            min_raise, max_raise = action[&#39;amount&#39;][&#39;min&#39;], action[&#39;amount&#39;][&#39;max&#39;]<br>            # Ensure the raise amount is within the range, considering your stack and the min/max allowed<br>            #raise_amount = int(max_raise/ 5) <br>            raise_amount = random.randint(min_raise, max_raise)<br>            <br>            return action[&#39;action&#39;], raise_amount<br>        else:<br>            # For &#39;call&#39; or &#39;fold&#39;, the amount is fixed in the valid_actions<br>            return action[&#39;action&#39;], action[&#39;amount&#39;]<br><br><br>    def receive_game_start_message(self, game_info):<br>        pass<br><br>    def receive_round_start_message(self, round_count, hole_card, seats):<br>        pass<br><br>    def receive_street_start_message(self, street, round_state):<br>        pass<br><br>    def receive_game_update_message(self, action, round_state):<br>        pass<br><br>    def receive_round_result_message(self, winners, hand_info, round_state):<br>        pass</pre><pre># Set up the game configuration<br>config = setup_config(max_round=100, initial_stack=1000, small_blind_amount=10)<br>config.register_player(name=&quot;Player1&quot;, algorithm=RandomPlayer())<br>config.register_player(name=&quot;Player2&quot;, algorithm=RandomPlayer())<br><br># Start the poker game<br>game_result = start_poker(config, verbose=1)</pre><h4>B. Building a slightly smarter player</h4><p>After having tested the basic poker bot and engaged with our environnement, lets build a slightly stronger High card version that makes a bet if it has a pair of high cards else folds.</p><pre>class SmartPlayer(BasePokerPlayer):<br><br>    def declare_action(self, valid_actions, hole_card, round_state):<br>        # Process the current game state<br>        current_street = round_state[&#39;street&#39;]<br>        pot_size = round_state[&#39;pot&#39;][&#39;main&#39;][&#39;amount&#39;]<br>        community_cards = round_state[&#39;community_card&#39;]<br>        <br>        # Simple strategy: If we have a pair or high card (A, K, Q, J), we bet, otherwise we fold<br>        high_cards = [&#39;A&#39;, &#39;K&#39;, &#39;Q&#39;, &#39;J&#39;]<br>        has_high_card = any(card[1] in high_cards for card in hole_card)<br>        has_pair = hole_card[0][1] == hole_card[1][1]<br><br>        if has_high_card or has_pair:<br>            action = &#39;raise&#39;<br>            action_dict = next((item for item in valid_actions if item[&quot;action&quot;] == action), None)<br>            # Check if raise is a valid action, otherwise call<br>            if action_dict:<br>                action_amount = random.randint(action_dict[&quot;amount&quot;][&quot;min&quot;], action_dict[&quot;amount&quot;][&quot;max&quot;])<br>#                 action_amount = int(action_dict[&quot;amount&quot;][&quot;max&quot;] / 5)<br>            else:<br>                action = &#39;call&#39;<br>                action_dict = next((item for item in valid_actions if item[&quot;action&quot;] == action), None)<br>                action_amount = action_dict[&quot;amount&quot;]<br>        else:<br>            action = &#39;fold&#39;<br>            action_dict = next((item for item in valid_actions if item[&quot;action&quot;] == action), None)<br>            action_amount = action_dict[&quot;amount&quot;]<br><br>        return action, action_amount<br><br>    # The following methods are not modified but are required to be present<br>    def receive_game_start_message(self, game_info):<br>        pass<br><br>    def receive_round_start_message(self, round_count, hole_card, seats):<br>        pass<br><br>    def receive_street_start_message(self, street, round_state):<br>        pass<br><br>    def receive_game_update_message(self, action, round_state):<br>        pass<br><br>    def receive_round_result_message(self, winners, hand_info, round_state):<br>        pass</pre><pre># Set up the game configuration<br>config = setup_config(max_round=10000, initial_stack=1000, small_blind_amount=10)<br>config.register_player(name=&quot;SmartPlayer1&quot;, algorithm=SmartPlayer())<br>config.register_player(name=&quot;SmartPlayer2&quot;, algorithm=SmartPlayer())<br><br># Start the poker game<br>game_result = start_poker(config, verbose=1)</pre><p>Well now we know how our environnement works and we even built a rule based system that can probably even defeat some amateur players… but we are not here for that.</p><h3>II. Deep Q-Network — Lets get hands dirty</h3><h4>How a Deep Q-Network Poker Bot Works</h4><p>A Deep Q-Network (DQN) poker bot operates by integrating the principles of Q-learning, a form of reinforcement learning, with deep neural networks. At its core, the DQN bot learns to make decisions based on a policy that maximizes the expected reward over time. In the context of poker, this involves evaluating the potential payoff of different actions (like folding, calling, or raising) given the current state of the game.</p><p>State Representation: The bot first needs to understand the game’s current state, which includes the cards on the table, its own hand, and any betting actions that have occurred. This state is converted into a numerical form that serves as input to the neural network.</p><p>Action Selection: The network outputs a Q-value for each possible action, representing the expected future rewards for taking that action from the current state. Initially, the bot may explore the action space randomly, but over time, it starts to favor actions that maximize these Q-values.</p><p>Learning Process: The bot continuously updates its policy based on feedback from the game outcomes. When the bot makes a decision, the game progresses, and it receives a new state and reward. It then adjusts the neural network to better predict the Q-values using the difference between expected rewards and the actual rewards received, a process known as “backpropagation.”</p><p>Network Architecture: The neural network used typically consists of several layers of neurons, each capable of learning different aspects of the game strategy from the input data. The output layer of the network directly maps to possible actions in the poker game, providing the basis for decision-making.</p><p>Optimization and Evaluation: Over countless game iterations, the DQN bot refines its strategy, learning to anticipate future moves and outcomes based on past experience. It uses an optimizer, such as Adam, to minimize prediction errors and improve its decision-making accuracy over time.</p><p>By leveraging the capabilities of deep learning, the DQN poker bot evolves from a novice with no game knowledge to an expert capable of strategic gameplay, making it a powerful tool for both research and entertainment.</p><h4>1. Initialise Network</h4><p>This function initialize_network constructs and compiles a neural network designed for our poker bot, using TensorFlow&#39;s Keras API. The network starts with an input layer tailored to accept a specified input_shape. It features two hidden layers with 150 and 64 neurons, respectively, both using ReLU activation for non-linear transformations. The output layer is bifurcated into two parts: one for deciding the poker action with a linear activation, and another for determining the bet amount, using softmax activation for probability distribution across five possible values (1 = 1/5 of the stack, 5 = all in). The model is compiled with an Adam optimizer, using mean squared error and categorical crossentropy as loss functions for the action and bet outputs, respectively.</p><p>This setup has shown particularly suitable for learning both discrete actions and distribution of possible bet sizes in our poker game environment.</p><pre><br>def initialize_network(input_shape, action_size):<br>    # Input layer<br>    input_layer = Input(shape=input_shape)<br><br>    # Shared layers<br>    x = layers.Dense(150, activation=&#39;relu&#39;)(input_layer)<br>    x = layers.Dense(64, activation=&#39;relu&#39;)(x)<br><br>    # Action output<br>    action_output = layers.Dense(action_size, activation=&#39;linear&#39;, name=&#39;action_output&#39;)(x)<br><br>    # Bet amount output<br>    bet_amount_output = layers.Dense(5, activation=&#39;softmax&#39;, name=&#39;bet_amount_output&#39;)(x)<br><br>    # Build the model<br>    model = models.Model(inputs=input_layer, outputs=[action_output, bet_amount_output])<br><br>    # Compile the model<br>    model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),<br>                  loss={&#39;action_output&#39;: &#39;mse&#39;, &#39;bet_amount_output&#39;: &#39;categorical_crossentropy&#39;},<br>                  metrics={&#39;action_output&#39;: &#39;accuracy&#39;, &#39;bet_amount_output&#39;: &#39;accuracy&#39;})<br><br>    return model</pre><pre>def load_or_initialize_model(model_path, input_shape, action_size):<br>    print(model_path)<br>    if os.path.exists(model_path):<br>        print(f&quot;Loading model from {model_path}&quot;)<br>        model = keras.models.load_model(model_path)<br>    else:<br>        print(&quot;Initializing new model&quot;)<br>        model = initialize_network(input_shape, action_size)<br>    return model</pre><h4>2. Encode cards</h4><p>This code snippet defines several constants and a function to assist in encoding poker cards . Constants like the number of suits (NUM_SUITS), ranks (NUM_RANKS), maximum community cards (MAX_COMMUNITY_CARDS), and the size of the betting history (BETTING_HISTORY_SIZE) are set up to configure the game environment. The encode_card function is crucial for converting poker cards into a machine-readable format. It takes a card, represented by its rank and suit, and encodes it as a one-hot vector. This encoding separates the rank and suit into distinct binary categories, which are essential for processing by machine learning algorithms in a poker bot or game simulation setup. This setup allows for adjusting parameters like the number of players and the depth of betting history to tailor the simulation to various game scenarios.</p><pre><br># Constants<br>NUM_SUITS = 4<br>NUM_RANKS = 13<br>MAX_COMMUNITY_CARDS = 5<br>LARGE_NUMBER = 10000<br>NUM_PLAYERS = 4  # Adjust based on your game setup<br>BETTING_HISTORY_SIZE = 10  # Last 10 actions, adjust as needed<br><br>default_category = 0<br><br>def encode_card(card):<br>    &quot;&quot;&quot;Encode a card as a one-hot vector for its rank and suit.&quot;&quot;&quot;<br>    rank, suit = card[1], card[0]<br>    rank_index = &#39;23456789TJQKA&#39;.index(rank)<br>    suit_index = &#39;SHDC&#39;.index(suit)<br>    rank_one_hot = np.eye(NUM_RANKS)[rank_index]<br>    suit_one_hot = np.eye(NUM_SUITS)[suit_index]<br>    return np.concatenate([rank_one_hot, suit_one_hot])</pre><h4>3. Choose action</h4><p>Let’s dive into the mechanics of the choose_action function, which is instrumental in the decision-making process of our deep reinforcement learning-based bot.</p><p><strong>Understanding the </strong><strong>choose_action Function</strong></p><p>The choose_action function serves a critical role in balancing between exploring new actions and exploiting known strategies based on the learning acquired so far. Here’s how I implemented it :</p><ol><li>Initialization: The function starts by setting default values for best_action and bet_amount_category. It prepares to handle scenarios where no valid actions are provided by raising an exception.</li><li>Decision-making — Exploration vs. Exploitation:</li></ol><ul><li>Exploration: With a probability epsilon, the function enters an exploration mode. Here, it randomly selects an action from the provided list of valid actions. This randomness is crucial in the early stages of learning, allowing the model to discover and evaluate different strategies.</li><li>Exploitation: When not exploring, the function exploits the learned values by predicting the Q-values from the neural network model. These Q-values represent the expected rewards for taking certain actions given the current state.</li></ul><p>3. Predicting and Selecting Actions:</p><ul><li>The model’s predictions are split into Q-values for actions and probabilities for different bet amounts.</li><li>Only actions that are valid in the current game context are considered. This is achieved by mapping valid actions to their indices and then selecting the action with the highest Q-value among the valid options.</li><li>Similarly, the bet amount is chosen based on the highest probability predicted by the model, reflecting the most likely optimal betting strategy.</li></ul><p><strong>Importance of the </strong><strong>choose_action Function</strong></p><p>The choose_action function encapsulates a fundamental aspect of reinforcement learning: the trade-off between exploration and exploitation. By implementing this balance, the poker bot can learn from its environment and optimize its strategy over time. This is particularly vital in games like poker, where the ability to adapt strategies based on an evolving game state is key to success.</p><pre>def choose_action(state, model, valid_actions, epsilon):<br>    # Initialize default values<br>    best_action = None<br>    bet_amount_category = 0  # Default to the first category<br><br>    if not valid_actions:<br>        raise ValueError(&quot;No valid actions provided.&quot;)<br><br>    if np.random.rand() &lt;= epsilon:<br>        # Exploration: Randomly choose a valid action<br>        best_action = np.random.choice([action[&#39;action&#39;] for action in valid_actions])<br>        # Randomly choose a bet amount category (assuming a fixed number of categories)<br>        bet_amount_category = np.random.randint(0, 5)  # Adjust &#39;5&#39; to your number of bet amount categories<br>    else:<br>        # Exploitation: Predict Q-values for actions and bet amounts<br>        predictions = model.predict(state.reshape(1, -1))<br>        q_values = predictions[0][0]  # Assuming the first output corresponds to actions<br>        bet_amounts = predictions[1][0]  # Assuming the second output corresponds to bet amounts<br><br>        # Map valid actions to their indices<br>        action_indices = {action[&#39;action&#39;]: idx for idx, action in enumerate(valid_actions)}<br><br>        # Ensure there is a best action by selecting the first valid action as default<br>        if valid_actions:<br>            best_action = valid_actions[0][&#39;action&#39;]<br><br>        # Choose the best action based on Q-values, considering only valid actions<br>        valid_q_values = [q_values[action_indices[action[&#39;action&#39;]]] for action in valid_actions]<br>        best_action = valid_actions[np.argmax(valid_q_values)][&#39;action&#39;]<br><br>        # Choose the bet amount category with the highest probability<br>        bet_amount_category = np.argmax(bet_amounts)<br><br>    if best_action is None:<br>        raise ValueError(&quot;Unable to determine a best action. Check the logic and inputs.&quot;)<br><br>    return best_action, bet_amount_category</pre><h4>4. Reward Function</h4><p>The compute_reward function is designed to calculate the reward for actions taken by our poker bot during a game, factoring in various aspects of the game state and outcomes. The reward system aims to guide the bot&#39;s learning process by reinforcing beneficial actions and penalising less advantageous ones.</p><p>Key Components of the Reward Function:</p><ul><li>Winning or Losing: The function assigns a reward of +10 for winning a round and a penalty of -10 for losing. This directly ties the reward to the game’s ultimate goal — maximising winnings.</li><li>Action-Based Adjustments: Actions influence the reward:</li><li>Folding incurs a penalty (-5) to discourage excessive caution.</li><li>Raising increases the reward proportionally to the amount raised relative to the pot size before the action, promoting aggressive play when it increases the potential gain significantly.</li><li>Stack Size Changes: Changes in the player’s chip stack are also considered, providing a nuanced feedback that rewards preserving chips while still engaging actively in the game.</li></ul><p>Outcome of Using an Advanced vs. Basic Reward Function: Interestingly, the more complex reward function I built and discarded, which includes adjustments based on the game dynamics and the player’s actions, did not outperform this simpler reward system. This observation suggests that in some cases, especially in environments with high variability and uncertainty like poker, simpler metrics that focus on clear outcomes (win/loss) might be more effective for training stable strategies.</p><p><strong>Significance of the Reward Function</strong></p><p>The reward function is crucial as it shapes the learning and strategy development of the poker bot. By intricately balancing rewards based on both the results and the quality of decisions, it attempts to foster a more sophisticated understanding of the game. However, the insights gained from comparing a more advanced function with a simpler one also highlight the challenges and complexities of AI training in stochastic environments like poker, offering lessons on the design of learning mechanisms.</p><pre>def compute_reward(round_state, action, action_details, is_winner, pot_size_before, pot_size_after, stack_size_before, stack_size_after, hole_cards, community_cards):<br>    &quot;&quot;&quot;<br>    Compute a simplified reward considering the action taken and game outcome without estimating hand strength.<br>    <br>    Args:<br>        round_state (dict): The state of the current round.<br>        action (str): The action taken by the agent.<br>        action_details (dict): Additional details about the action, such as the bet amount.<br>        is_winner (bool): Indicates whether the player won in this round.<br>        pot_size_before (int): The size of the pot before the action was taken.<br>        pot_size_after (int): The size of the pot after the action was taken.<br>        stack_size_before (int): The player&#39;s stack size before the action.<br>        stack_size_after (int): The player&#39;s stack size after the action.<br>        hole_cards (list): List of player&#39;s hole cards as string.<br>        community_cards (list): List of community cards on the table as string.<br><br>    Returns:<br>        reward (float): The computed reward.<br>    &quot;&quot;&quot;<br>    reward = 0<br><br>    # Adjust rewards for winning or losing the round<br>    if is_winner:<br>        reward += 10  # Reward for winning<br>    else:<br>        reward -= 10  # Penalty for losing<br><br>    # Consider the action taken<br>    if action == &#39;fold&#39;:<br>        reward -= 5  # Discourage folding by default<br>    elif action == &#39;raise&#39;:<br>        bet_amount = action_details.get(&#39;amount&#39;, 0)<br>        pot_ratio = bet_amount / max(1, pot_size_before)  # Avoid division by zero<br>        reward += 5 * pot_ratio  # Reward for aggressive play when raising<br><br>    # Adjust reward based on changes in stack size, to encourage preservation of chips<br>    stack_change = stack_size_after - stack_size_before<br>    reward += stack_change / 100.0  # Small reward/penalty based on stack change<br><br>    return reward</pre><h4>5. Replay Buffer</h4><p>The ReplayBuffer class in this snippet plays a crucial role in the training process of our poker bot by implementing experience replay, a technique used in reinforcement learning to improve stability and efficiency. The class manages a buffer of a specified size that stores experiences, which include states, actions, bet amount categories, rewards, next states, and whether a round has ended. By random sampling of these experiences, the bot can learn from a diverse set of past actions and their outcomes, rather than relying solely on recent interactions. This approach helps mitigate the problems associated with correlated data and non-stationary distributions in online learning, providing a more robust foundation for the AI to learn effective strategies over time. The inclusion of bet_amount_category in the experiences further refines the learning details, enabling more nuanced decision-making based on past betting patterns.</p><pre><br>class ReplayBuffer:<br>    def __init__(self, buffer_size):<br>        self.buffer = deque(maxlen=buffer_size)<br><br>    def add(self, state, action, bet_amount_category, reward, next_state, done):<br>        &quot;&quot;&quot;Add a new experience to the buffer.&quot;&quot;&quot;<br>        # Include bet_amount_category in the stored experience<br>        self.buffer.append((state, action, bet_amount_category, reward, next_state, done))<br><br>    def sample(self, batch_size):<br>        &quot;&quot;&quot;Sample a batch of experiences from the buffer.&quot;&quot;&quot;<br>        batch = random.sample(self.buffer, min(len(self.buffer), batch_size))<br>        # Unpack bet_amount_category along with other experience components<br>        states, actions, bet_amount_categories, rewards, next_states, dones = zip(*batch)<br>        return states, actions, bet_amount_categories, rewards, next_states, dones</pre><h4>6. Replay Function</h4><p>The replay function is integral to the reinforcement learning process of our poker bot, particularly for updating the neural network models through the technique of Q-learning. This function takes a batch of experiences from the ReplayBuffer, which includes states, actions, rewards, and subsequent states, and uses them to refine the model predictions about the game.</p><p>Here’s how it works:</p><ul><li>Sampling and Preprocessing: The function begins by sampling experiences from the replay buffer to form a batch. It then converts these experiences into numpy arrays for efficient batch processing.</li><li>Q-value Calculation: Using the target model, it predicts the future Q-values for both actions and bet amounts from the next states. The Q-values for actions are then updated using the formula for Q-learning, which incorporates rewards received and the discounted maximum future Q-values, adjusted by whether the game round ended.</li><li>Model Update: The current model’s predictions are adjusted based on the actions taken. For the actions, the Q-values are directly updated. For bet amounts, the function first converts categories to one-hot encoding to match the model’s output, facilitating direct learning from the categorical data.</li><li>Batch Training: Finally, the model is trained on this batch, using the updated Q-values for actions and the encoded categories for bet amounts, to improve its predictive accuracy and strategic decision-making in future games.</li></ul><p>This function underscores the dynamism of reinforcement learning, allowing the poker bot to continually adapt and optimize its strategy based on accumulated experience, thus improving over time through iterative learning and adjustments. This is crucial for developing a bot that can effectively compete in the unpredictable environment of poker games.</p><pre>def replay(replay_buffer, model, target_model, batch_size, gamma):<br>    &quot;&quot;&quot;Sample a batch of experiences and use them to update the model with dual outputs (action and bet_amount).<br>    <br>    Args:<br>        replay_buffer (ReplayBuffer): The replay buffer to sample experiences from.<br>        model (tf.keras.Model): The current model.<br>        target_model (tf.keras.Model): The target model.<br>        batch_size (int): The number of experiences to sample from the buffer.<br>        gamma (float): The discount factor for future rewards.<br>    &quot;&quot;&quot;<br>    # Sample a batch of experiences from the replay buffer<br>    states, actions, bet_amount_categories, rewards, next_states, dones = replay_buffer.sample(batch_size)<br><br>    # Convert lists to numpy arrays for batch processing<br>    states = np.array(states)<br>    next_states = np.array(next_states)<br>    rewards = np.array(rewards)<br>    dones = np.array(dones)<br><br>    # Predict the Q-values for the next states using the target model<br>    next_q_values_action, next_q_values_bet_amount = target_model.predict(next_states)<br><br>    # Compute the Q-value targets for actions<br>    targets_action = rewards + gamma * np.max(next_q_values_action, axis=1) * (1 - dones)<br><br>    # Predict the Q-values for the current states using the model<br>    q_values_action, q_values_bet_amount = model.predict(states)<br><br>    # Update the Q-values for the actions taken with the computed targets<br>    for i, action in enumerate(actions):<br>        q_values_action[i, action] = targets_action[i]<br>    <br>    # Replace None with default_category<br>    bet_amount_categories = np.array([cat if cat is not None else default_category for cat in bet_amount_categories], dtype=&#39;int64&#39;)<br><br>    # Convert bet_amount_categories to one-hot encoding for training the bet amount prediction part of the model<br>    bet_amount_categories_one_hot = to_categorical(bet_amount_categories, num_classes=q_values_bet_amount.shape[1])<br><br>    # Train the model<br>    model.fit(states, [q_values_action, bet_amount_categories_one_hot], epochs=1, verbose=0)</pre><h4>7. Update target network</h4><p>The update_target_network function is essential for the stability of the Deep Q-Network (DQN) training process. It periodically copies the weights from the main Q-network to the target Q-network. The target Q-network is used to calculate the target Q-values during the training step, which helps to mitigate the moving target problem inherent in Q-learning.</p><p>In this function:</p><p>- main_q_network is the neural network being actively trained, i.e., the one that is learning the Q-value function based on the agent’s experiences.<br>- target_q_network is a separate network whose weights are periodically updated to match those of the main_q_network. The target_q_network’s Q-value predictions are used to compute the target values for updating the main_q_network, adding stability to the learning process.</p><p>Usage<br>You typically call update_target_network at fixed intervals during training, rather than after every training step. The frequency of updates is a hyperparameter you can tune. For example, you might update the target network every 1000 training steps.</p><pre>def update_target_network(main_q_network, target_q_network):<br>    &quot;&quot;&quot;Update the target Q-network&#39;s weights with the main Q-network&#39;s weights.<br>    <br>    Args:<br>        main_q_network (tf.keras.Model): The main Q-network being trained.<br>        target_q_network (tf.keras.Model): The target Q-network used for stability.<br>    &quot;&quot;&quot;<br>    # Get the weights from the main Q-network<br>    main_q_weights = main_q_network.get_weights()<br>    <br>    # Set the weights in the target Q-network<br>    target_q_network.set_weights(main_q_weights)</pre><p>Thats it ! Our Deep Q Network is done! Now we can integrate it into our environnement.</p><h3>III. Integrating into the Environnement</h3><h4>1. Building our DQNPokerAgent</h4><p>The DQNPokerAgent class encapsulates a deep Q-learning agent and leverages the functions above.</p><p>Key Features of the DQNPokerAgent:</p><ul><li>Initialization: The agent is initialized with essential parameters such as state and action sizes, and optionally, a pre-trained model. If no model is provided, it initializes a new neural network model. It also sets up a target Q-network, crucial for the stability of learning updates.</li><li>Replay Buffer: Utilizes the ReplayBuffer to store and randomly sample past experiences, facilitating the learning from older memories to reduce correlations between sequential observations.</li><li>Learning Mechanism: The learn method orchestrates the learning process by sampling from the replay buffer and applying the replay function to update the Q-network based on the sampled experiences. This method ensures that the agent learns from a diverse set of scenarios, improving its generalization over merely reacting to the most recent experiences.</li><li>Action Selection: The act method determines the agent’s actions by balancing exploration (choosing actions randomly) and exploitation (choosing the best-known actions). This balance is governed by the parameter epsilon, which decays over time, gradually reducing the emphasis on random actions as the agent becomes more confident in its strategy.</li><li>Target Network Updates: Regularly updates the weights of the target network to match those of the primary Q-network, a technique that helps stabilize the learning updates by providing a fixed baseline for computing the target Q-values during training.</li></ul><pre>class DQNPokerAgent:<br>    def __init__(self, state_size, action_size, model=None, replay_buffer_size=50000, batch_size=32, gamma=0.95, epsilon=1, epsilon_min=0.01, epsilon_decay=0.9995):<br>        self.state_size = state_size<br>        self.action_size = action_size<br>        self.replay_buffer = ReplayBuffer(replay_buffer_size)<br>        self.batch_size = batch_size<br>        self.gamma = gamma<br>        self.epsilon = epsilon<br>        self.epsilon_min = epsilon_min<br>        self.epsilon_decay = epsilon_decay<br>        self.model = model<br>        <br>        # If a model is provided, use it; otherwise, initialize a new model<br>        self.q_network = model if model else initialize_network((state_size,), action_size)<br><br>        # Initialize the target Q-network<br>        self.target_q_network = initialize_network((state_size,), action_size)<br>        self.update_target_network()<br><br>    def update_target_network(self):<br>        &quot;&quot;&quot;Updates the target Q-network&#39;s weights.&quot;&quot;&quot;<br>        update_target_network(self.q_network, self.target_q_network)<br><br>    def act(self, state, valid_actions):<br>        &quot;&quot;&quot;Choose an action and a bet amount category based on the current state.&quot;&quot;&quot;<br>        action, bet_amount_category = choose_action(np.reshape(state, [1, self.state_size]), self.q_network, valid_actions, self.epsilon)<br>        return action, bet_amount_category<br><br>    def learn(self):<br>        &quot;&quot;&quot;Trains the model using a batch of experiences from the replay buffer.&quot;&quot;&quot;<br>        # Sample a batch of experiences from the replay buffer<br>        states, actions, bet_amount_categories, rewards, next_states, dones = self.replay_buffer.sample(self.batch_size)<br><br>        # Proceed with the rest of the training process by updating the Q-network and target Q-network<br>        replay(self.replay_buffer, self.q_network, self.target_q_network, self.batch_size, self.gamma)<br>        <br>        # Epsilon decay<br>        print(self.epsilon)<br>        if self.epsilon &gt; self.epsilon_min:<br>            self.epsilon *= self.epsilon_decay<br></pre><h4>2. Defining a custom Poker Player: the DQNPokerPlayer</h4><p>Integrating our advanced functions into the pypokerengine environment to enhance our poker bot, DQNPokerPlayer, involves several crucial steps that bridge the gap between theoretical machine learning models and practical game-playing applications. Here&#39;s a succinct overview of how we orchestrate these elements to interact within the poker game environment:</p><p><strong>Integration of Key Functions into the PyPokerEngine</strong></p><p>i. Replay Buffer Integration:</p><p>The ReplayBuffer function is crucial for storing the bot&#39;s experiences during gameplay. Each game action—along with the associated state, reward, and subsequent state—is recorded in this buffer. This mechanism supports the learning process by providing a diverse set of past experiences for the bot to learn from, which is vital for effective model training.</p><p>ii. Decision Making Through the act Method:</p><p>Within each game round, the DQNPokerPlayer uses the act method from the DQNPokerAgent to decide on its next move. This method evaluates the current game state and predicts the best action using the trained neural network model, accounting for both current knowledge (exploitation) and exploration of new strategies (exploration through epsilon-greedy approach).</p><p>iii. Learning from Gameplay Using the learn Method:</p><p>After accumulating sufficient data in the replay buffer, the learn method is triggered. This function pulls a batch of experiences from the buffer to update the neural network models. It refines the bot’s strategies based on actual outcomes compared to predicted ones, ensuring the bot evolves and improves over time.</p><p>iv. State Extraction for Neural Network Input:</p><p>The DQNPokerPlayer captures the current game state through the _extract_state method, which processes and formats the game data into a neural-network-friendly structure. This includes details like the player’s hole cards and community cards, which are essential for the bot to assess its position and make informed decisions.</p><p>v. Real-Time Updates and Feedback Loop:</p><p>The game’s progress influences the bot’s learning and decision-making processes. Functions like receive_game_update_message and receive_round_result_message ensure that the bot is updated with the latest game developments and outcomes. These updates allow the bot to adjust its strategy in real time, learning from both wins and losses to enhance future performance.</p><p><strong>Practical Application in PyPokerEngine</strong></p><p>By embedding these functions into the pypokerengine framework (similarly as we did for our random player but way more advanced), we ensure that our AI poker bot can actively participate in games, learn from its experiences, and adapt its strategies dynamically.</p><pre>class DQNPokerPlayer(BasePokerPlayer):<br>    def __init__(self, dqn_agent, name, state_size, training_mode=True):<br>        super().__init__()<br>        self.dqn_agent = dqn_agent<br>        self.name = name<br>        self.current_state = np.zeros(state_size)<br>        self.prev_state = np.zeros(state_size)<br>        self.hole_card = None<br>        self.last_action = None<br>        self.action_index = None<br>        self.bet_amount_category = None<br>        self.done = False<br>        self.last_action_details = {&#39;action&#39;: None, &#39;amount&#39;: 0}  # Initialize with default values<br>        <br>        self.training_mode = training_mode  # New flag to indicate training mode<br>        self.games_since_last_learn = 0  <br><br><br>    def declare_action(self, valid_actions, hole_card, round_state):<br>        if self.current_state is None:<br>            self.current_state = self._extract_state(round_state, hole_card)<br>            print(&quot;State size:&quot;, state.shape)  # Should output (130,)<br><br><br>        action, bet_amount_category = self.dqn_agent.act(self.current_state, valid_actions)<br>        self.last_action = action<br>        self.bet_amount_category = bet_amount_category<br><br>        action_index = self.map_action_to_index(action, valid_actions)<br>        self.action_index = action_index<br><br>        action_dict = next((item for item in valid_actions if item[&quot;action&quot;] == action), None)<br><br>        if action == &#39;raise&#39; and isinstance(action_dict[&#39;amount&#39;], dict):<br>            min_raise = action_dict[&#39;amount&#39;][&#39;min&#39;]<br>            max_raise = action_dict[&#39;amount&#39;][&#39;max&#39;]<br>            fraction = (self.bet_amount_category + 1) / 5<br>            amount = int(min_raise + fraction * (max_raise - min_raise))<br>        else:<br>            amount = action_dict[&#39;amount&#39;] if action_dict else 0<br>#         print(&#39;## amount&#39;, amount)<br><br>        self.last_action_details = {&#39;action&#39;: action, &#39;amount&#39;: amount}  # Update action details<br>#         print(f&quot;declare_action - last_action_details: {self.last_action_details}&quot;)<br><br>        return action, amount<br><br>    <br>    <br>    <br>    def receive_game_start_message(self, game_info):<br>        for seat in game_info[&#39;seats&#39;]:<br>            if seat[&#39;name&#39;] == self.name:<br>                self.uuid = seat[&#39;uuid&#39;]<br>                break<br>                <br>    def receive_round_start_message(self, round_count, hole_card, seats):<br>        self.hole_card = hole_card  # Update hole_card at the start of each round<br><br>        <br>    def receive_game_update_message(self, action, round_state):<br>        self.prev_state = self.current_state  # Store the current state as the previous state<br>        <br>        if self.current_state is None:<br>                print(&#39;None detected in receive_game_update_message&#39;, self.current_state)<br>        <br>        if self.hole_card:  # Ensure hole_card has been set<br>            self.current_state = self._extract_state(round_state, self.hole_card)<br>            <br>        self.pot_size_before = round_state[&#39;pot&#39;][&#39;main&#39;][&#39;amount&#39;]<br>        self.stack_size_before = self._get_stack_size(self.uuid, round_state)<br>    <br>    def _get_stack_size(self, player_uuid, round_state):<br>        # Iterate through the list of players (seats) in the round_state<br>        for player_info in round_state[&#39;seats&#39;]:<br>            # Check if the current player&#39;s UUID matches the specified player_uuid<br>            if player_info[&#39;uuid&#39;] == player_uuid:<br>                # Return the stack size of the matching player<br>                return player_info[&#39;stack&#39;]<br>        # Return None or an appropriate default value if the player is not found<br>        return None<br><br>    <br><br>    def receive_round_result_message(self, winners, hand_info, round_state):<br>        is_winner = any(winner[&#39;uuid&#39;] == self.uuid for winner in winners)<br><br>        # Use the stored action details directly, ensuring it&#39;s not None<br>        action_details = self.last_action_details if self.last_action_details is not None else {&#39;action&#39;: &#39;default&#39;, &#39;amount&#39;: 0}<br><br>        # Adjust to handle cards that might already be strings<br>        hole_cards = [card if isinstance(card, str) else card.to_str() for card in self.hole_card]<br>        community_cards = [card if isinstance(card, str) else card.to_str() for card in round_state[&#39;community_card&#39;]]<br><br>        pot_size_before = self.pot_size_before<br>        pot_size_after = round_state[&#39;pot&#39;][&#39;main&#39;][&#39;amount&#39;]<br>        stack_size_before = self.stack_size_before<br>        stack_size_after = self._get_stack_size(self.uuid, round_state)<br><br><br>        self.done = True<br><br>        if self.bet_amount_category is None:<br>            self.bet_amount_category = 0  # Assuming &#39;0&#39; as default category<br><br>        if self.training_mode:<br>            <br>            # Compute the reward with additional parameters<br>            reward = compute_reward(<br>                round_state,<br>                self.last_action,<br>                action_details,<br>                is_winner,<br>                pot_size_before,<br>                pot_size_after,<br>                stack_size_before,<br>                stack_size_after,<br>                hole_cards,<br>                community_cards,<br>                  # Number of players<br>            )<br>            <br>            self.dqn_agent.replay_buffer.add(self.prev_state, self.action_index, self.bet_amount_category, reward, self.current_state, self.done)<br>            self.games_since_last_learn += 1<br><br>            if self.games_since_last_learn &gt;= 10:<br>                self.dqn_agent.learn()<br>                self.games_since_last_learn = 0<br><br>        # Reset for the next round<br>        self.done = False<br>        self.prev_state = None<br>        self.action_index = None<br>        self.bet_amount_category = None<br>        self.last_action_details = {&#39;action&#39;: None, &#39;amount&#39;: 0}<br><br><br>        <br>    def _get_stack_size(self, uuid, round_state):<br>        for player in round_state[&#39;seats&#39;]:<br>            if player[&#39;uuid&#39;] == uuid:<br>                return player[&#39;stack&#39;]<br>        return None<br><br><br><br>    def _extract_state(self, round_state, hole_card):<br>        MAX_COMMUNITY_CARDS = 5<br>        MAX_PLAYERS = 10  # Define the maximum number of players you expect in any game<br>        LARGE_NUMBER = 10000  # Normalization factor for large values like stacks and pots<br><br>        # Encoding hole and community cards<br>        hole_cards_encoded = [encode_card(card) for card in hole_card]<br>        community_cards_encoded = [encode_card(card) for card in round_state[&#39;community_card&#39;]]<br><br>        # Determine the vector size for a single card<br>        N = len(encode_card(hole_card[0])) if hole_card else 26  # Example fallback size if encode_card size is not standard<br><br>        # Flatten encoded cards into single vectors<br>        hole_cards_vector = np.concatenate(hole_cards_encoded) if hole_cards_encoded else np.zeros(N * 2)<br>        community_cards_vector = np.concatenate(community_cards_encoded) if community_cards_encoded else np.zeros(N * len(community_cards_encoded))<br><br>        # Define a zero vector for padding community cards<br>        zero_vector = np.zeros(N)<br>        padded_community_cards = np.concatenate([community_cards_vector] + [zero_vector for _ in range(MAX_COMMUNITY_CARDS - len(community_cards_encoded))])<br><br>        # Additional game features<br>        pot_size = np.array([round_state[&#39;pot&#39;][&#39;main&#39;][&#39;amount&#39;] / LARGE_NUMBER])  # Normalize pot size<br><br>        # Encoding player stack sizes and positions<br>        seats = round_state[&#39;seats&#39;]<br>        stack_sizes = [seat[&#39;stack&#39;] / LARGE_NUMBER for seat in seats if &#39;stack&#39; in seat]<br>        positions = [1 if i == round_state.get(&#39;dealer_btn&#39;) else 0 for i in range(len(seats))]<br><br>        # Optional: Number of active players (can be useful in strategy decision making)<br>        active_players = [1 if &#39;folded&#39; not in seat[&#39;state&#39;] else 0 for seat in seats]<br><br>        # Padding for player-related features if there are fewer players than MAX_PLAYERS<br>        stack_sizes += [0] * (MAX_PLAYERS - len(stack_sizes))<br>        positions += [0] * (MAX_PLAYERS - len(positions))<br>        active_players += [0] * (MAX_PLAYERS - len(active_players))<br><br>        # Convert lists to numpy arrays<br>        stack_sizes = np.array(stack_sizes)<br>        positions = np.array(positions)<br>        active_players = np.array(active_players)<br><br>        # Concatenate all parts to form the full state vector<br>        state = np.concatenate([hole_cards_vector, padded_community_cards, pot_size, stack_sizes, positions, active_players])<br><br>        return state<br><br><br>    def map_action_to_index(self, action, valid_actions):<br>        # Convert the action to an index. This implementation depends on how your actions are structured.<br>        action_dict = {act[&#39;action&#39;]: idx for idx, act in enumerate(valid_actions)}<br>        return action_dict.get(action, -1)  # Return -1 or another value for invalid actions<br>    <br>    def receive_street_start_message(self, street, round_state):<br>        pass<br><br></pre><h4>3. Setup the Poker Game</h4><p>i. Initialisation of Game Parameters:</p><p>The function sets up a basic poker game configuration with parameters like initial_stack, max_round, and small_blind_amount. These settings define the game&#39;s basic financial structure and length.</p><p>ii. Creation of the Main Training Player:</p><p>A DQNPokerPlayer instance is created for the primary DRL agent (dqn_agent1). This player is registered in the game with a specific name and set to training mode, indicating that this player will use the experiences from the game to learn and adjust its strategy.</p><p>iii. Dynamic Registration of Other Players:</p><ul><li>The number of players in the game is determined randomly between 2 and 5. This randomness is crucial for simulating a variety of game dynamics, as different numbers of players can significantly alter the gameplay and the strategies needed to succeed.</li><li>Additional players are created using older versions of the model or different strategies. Each of these players is registered under a unique name. This setup allows the main training player to encounter a diverse range of opponents, enhancing the robustness and general adaptability of the learned strategies.</li></ul><p>iv. Loading or Initialising Additional Models:</p><p>For each additional player, the function checks for a pre-existing model at a specified path or initializes a new model. These players are configured not to explore (i.e., epsilon=0.0), meaning they strictly follow the learned strategies without random actions. This setting ensures that the training environment is both challenging and controlled.</p><pre><br><br>def setup_poker_game(dqn_agent1, initial_stack = 1000):<br>    state_size = 150<br>    action_size = 3<br>    <br>    # Randomly decide the number of players (between 2 and 10 for example)<br>    num_players = random.randint(2, 5)<br>    <br>    config = setup_config(max_round=100, initial_stack = initial_stack, small_blind_amount=10)<br>    <br>    # Register the main training player<br>    dqn_player1 = DQNPokerPlayer(dqn_agent1, &quot;DQN_Player_Train&quot;, state_size, training_mode=True)<br>    config.register_player(name=&quot;DQN_Player_Train&quot;, algorithm=dqn_player1)<br>    <br>    # Optionally, load or initialize additional models if needed<br>    model_path = &#39;./my_dqn_model.keras&#39;<br>    <br>    # Register other players, potentially older versions or different strategies<br>    for i in range(1, num_players):<br>        dqn_model = load_or_initialize_model(model_path, state_size, action_size)<br>        dqn_agent = DQNPokerAgent(state_size, action_size, model=dqn_model, epsilon=0.0)<br>        dqn_player = DQNPokerPlayer(dqn_agent, f&quot;DQN_Player_Old_{i}&quot;, state_size, training_mode=False)<br>        config.register_player(name=f&quot;DQN_Player_Old_{i}&quot;, algorithm=dqn_player)<br><br>    # # Optionally, add other types of players<br>    # config.register_player(name=&quot;Random_Player&quot;, algorithm=RandomPlayer())<br>    # config.register_player(name=&quot;SmartPlayer&quot;, algorithm=SmartPlayer())<br><br>    return config</pre><h3>Train the model</h3><p>To gauge the bot’s learning progress and effectiveness, I initiated dictionaries to track total gains, cumulative rewards, and win rates for each player. These metrics are vital as they provide a quantitative measure of the bot’s ability to adapt and succeed over time. I know we could come up with better metrics but that’s for a future article.</p><p>Here, throughout the training, the bot competes in a dynamic poker environment where the initial stacks vary, introducing a level of unpredictability and complexity like to real-world poker scenarios. After each game, I update the performance metrics for each player, offering a detailed view of the bot’s ability to leverage its learned strategies effectively.</p><p>Every 100 episodes, we save the current model and generate visual plots of the cumulative rewards and win rates. This ensures that the bot’s most recent and optimized strategies are preserved and soon loaded and applied in the next cycle.</p><pre><br>#This is to suppress stdouts of tensorflow which I can&#39;t somhow suppress<br>@contextlib.contextmanager<br>def suppress_stdout():<br>    original_stdout = sys.stdout<br>    sys.stdout = open(os.devnull, &#39;w&#39;)<br>    try:<br>        yield<br>    finally:<br>        sys.stdout.close()<br>        sys.stdout = original_stdout</pre><pre><br><br># Initialize dictionaries to store metrics for each player<br>total_gains = {}<br>cumulative_rewards = {}<br>win_rates = {}<br><br># Define model path<br>model_path = &#39;./my_dqn_model.keras&#39;<br><br># Define the input shape and action size for your model<br>input_shape = (150,)<br>action_size = 3<br>state_size = input_shape[0]<br><br># Initialize or load the main model<br>dqn_model = load_or_initialize_model(model_path, input_shape, action_size)<br>dqn_agent = DQNPokerAgent(state_size, action_size, model=dqn_model,epsilon = 1)<br># Save the current model for the other players<br>dqn_model.save(model_path)<br><br><br># Training loop...<br>for episode in range(1000000):<br><br>    with suppress_stdout():<br><br>        initial_stack = random.randint(1, 10) * 100 #every game will have different initial stacks for now small blind remains 10<br>        <br>#     if 1==1:<br>        # Setup and start the poker game with the current model playing against its previous version<br>        config = setup_poker_game(dqn_agent, initial_stack = initial_stack)<br>        game_result = start_poker(config, verbose=0)<br><br>        # Update metrics based on game results...<br>        for player in game_result[&#39;players&#39;]:<br>            name = player[&#39;name&#39;]<br>            stack_change = player[&#39;stack&#39;] - initial_stack<br><br>            # Initialize player metrics if new<br>            if name not in total_gains:<br>                total_gains[name] = [0]<br>                cumulative_rewards[name] = []<br>                win_rates[name] = []<br><br>            # Update player metrics<br>            total_gains[name].append(total_gains[name][-1] + stack_change)<br>            cumulative_rewards[name].append(total_gains[name][-1])<br>            win_rate = sum(r &gt; 0 for r in total_gains[name]) / len(total_gains[name])<br>            win_rates[name].append(win_rate)<br><br>    if episode % 100 == 0:<br>        clear_output(wait=True)<br>        print(f&quot;Epsilon after episode {episode}: {dqn_agent.epsilon}&quot;)<br><br>        # Save the current model<br>        dqn_model.save(model_path)<br>#         print(&quot;Saved the current model.&quot;)<br><br>        # Clear the current figure to ensure old plots are not shown<br>        plt.clf()<br><br>        # Plot metrics<br>        plt.figure(figsize=(12, 6))<br><br>        # Plot cumulative rewards<br>        plt.subplot(1, 2, 1)<br>        for name, rewards in cumulative_rewards.items():<br>            plt.plot(rewards, label=f&#39;{name} Total Gains&#39;)<br>        plt.xlabel(&#39;Episode&#39;)<br>        plt.ylabel(&#39;Total Gains&#39;)<br>        plt.title(&#39;Total Gains per Episode&#39;)<br>        plt.legend()<br><br>        # Plot win rates<br>        plt.subplot(1, 2, 2)<br>        for name, rates in win_rates.items():<br>            plt.plot(rates, label=f&#39;{name} Win Rate&#39;)<br>        plt.xlabel(&#39;Episode&#39;)<br>        plt.ylabel(&#39;Win Rate&#39;)<br>        plt.title(&#39;Win Rate per Episode&#39;)<br>        plt.legend()<br><br>        plt.tight_layout()<br>        plt.show()<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NI-4lfsgMeTjySPBjvmYbQ.png" /></figure><p>Lets now train this bot for a couple hundred thousand games and lets see how it performs, but lets debrief that in another article.</p><h3>Conclusion</h3><p>Thank you for sticking with me. I hope I could show you something useful and with a complete code example you can run edit and improve as you want.</p><p>Please let me know if I forgot something or if I’m wrong somewhere. I’m still learning (and hope I will never stop learning).</p><p>I will shortly add another article on how you can play against our bot and how we evaluate its strategy. This is my V.1 of the poker bot, a lot of iterations were needed to come here and many more will be needed to become really good.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a48e296805d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>