<?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 Ryan Leong on Medium]]></title>
        <description><![CDATA[Stories by Ryan Leong on Medium]]></description>
        <link>https://medium.com/@ryan-leong?source=rss-51b3afa34f08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_6VSxwejhQXkUMCkwj51Pg.jpeg</url>
            <title>Stories by Ryan Leong on Medium</title>
            <link>https://medium.com/@ryan-leong?source=rss-51b3afa34f08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 02:14:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryan-leong/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[The intuition behind LLMs]]></title>
            <link>https://blog.gopenai.com/the-intuition-behind-llms-a9002250035f?source=rss-51b3afa34f08------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9002250035f</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ryan Leong]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 04:55:55 GMT</pubDate>
            <atom:updated>2025-10-12T19:01:39.252Z</atom:updated>
            <content:encoded><![CDATA[<h3>A simple explanation of how chatbots like ChatGPT work</h3><p>Imagine you come across a script of a scene between a user and their helpful AI assistant. However, the part with the AI’s response is missing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*_FtgqonrsuUCLn0R0iA9Gw.png" /></figure><p>Now imagine we also have a powerful machine that can take any piece of text and provide a reasonable prediction of what word comes next. We feed it the start of the script, and it predicts the first word of the AI assistant’s response. Then we can take this output and feed it back in for the next word, and so on, until we’ve generated the full response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*8qlZVGURxL-mh8D208masw.png" /></figure><p>This is exactly what happens when you interact with a chatbot.</p><p>The word-prediction machine is called a <strong>large language model</strong>. You can think of it as a system that studies patterns in how words usually follow one another, then writes down its own internal “guidelines” for predicting what should come next.</p><p>At first, these guidelines are random, so the text it produces is complete nonsense. But as the model sees more and more examples, it starts to notice useful patterns. It learns that some rules help predict the next word better than others. For example, it notices that words like <em>“the”</em> or <em>“a”</em> often come before nouns. Over time, its guidelines become more refined, and by the end of training it can generate coherent sentences that sound like something a person might write.</p><h3>How They’re Trained to Be Helpful</h3><p><strong>Takeaway:</strong> A second training step uses human feedback to teach models how to give more helpful responses to people.</p><p>This first round of training is called pre-training, where the model learns grammar and coherence from text on the Internet. However, it hasn’t learned how to be helpful to humans yet.</p><p>In the second round of training, human experts write answers to common questions, and these question-answer pairs are fed to the model. This is when we teach it not to give dangerous advice or to politely decline a malicious request. Using the same process as before, the model adjusts its internal guidelines so that it predicts words leading to responses humans find more useful and appropriate.</p><p>The first version of ChatGPT widely released to the public was created through these two steps.</p><h3>Why Early Models Struggled With Reasoning</h3><p><strong>Takeaway:</strong> Early models could mimic language but weren’t very good at logic or multi-step reasoning.</p><p>All early models had one major weakness: they were terrible at math. Actually, they were terrible at solving all logic problems.</p><p>They could sometimes solve multi-step questions, because logical reasoning occasionally helped predict the next word. But since problems requiring logic made up only a tiny fraction of the Internet, their reasoning abilities remained limited. It was like trying to learn chess from random conversations online.</p><p>However, researchers noticed that instructing the model to “show its work” or think through a problem step by step caused accuracy to increase. This led to the next big idea.</p><h3>Newer Approaches to Reasoning</h3><p><strong>Takeaway:</strong> By teaching models to think through problems step by step, researchers made them much better problem-solvers.</p><p>Researchers began giving models countless math, science, and logic problems along with the answers, and asked them to <strong>show their work</strong>. The reasoning steps the model generated were called its <strong>chain of thought</strong>.</p><p>When the model’s step-by-step thinking led to the right answer, they used it as an example to train the model so it could learn what ‘good reasoning’ looks like.</p><p>This process of teaching the model to ‘think’ played a key role in enabling OpenAI’s o1 model — the world’s first reasoning model — to set unprecedented records at the time.</p><p>It wasn’t perfect, but it was still a major leap in the reasoning ability of models.</p><p>Now whenever you see the model’s “thinking” animation, you know that’s just the system generating steps to solve the problem internally before giving you a response.</p><p>If you wanted to learn more about the inner workings of an LLM, check <a href="https://www.3blue1brown.com/lessons/mini-llm">this</a> out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9002250035f" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/the-intuition-behind-llms-a9002250035f">The intuition behind LLMs</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a tic-tac-toe neural network =D]]></title>
            <link>https://ryan-leong.medium.com/building-a-tic-tac-toe-neural-network-d-5456254970ab?source=rss-51b3afa34f08------2</link>
            <guid isPermaLink="false">https://medium.com/p/5456254970ab</guid>
            <category><![CDATA[tic-tac-toe]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[experiment]]></category>
            <category><![CDATA[monte-carlo-tree-search]]></category>
            <dc:creator><![CDATA[Ryan Leong]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 16:54:55 GMT</pubDate>
            <atom:updated>2024-12-27T03:32:23.000Z</atom:updated>
            <content:encoded><![CDATA[<p>If you just want to experiment with the network, here’s the <a href="https://github.com/Programmer484/SL-TicTacToe-NN">Github repo</a>:</p><p>Just a heads up, this article focuses on a high-level overview rather than detailed code explanations. The full tutorial is <a href="https://colab.research.google.com/drive/12G5C9Bqm6aclkmQ1Q4rg2mPmia-0LPRr">here</a>! Here’s the article summary</p><ol><li>Create training data</li><li>Train the model</li><li>Results</li><li>Experiment with the model yourself!</li><li>Extra learnings about MCTS</li></ol><h4>Creating the training data</h4><p>First, I decided what the network should output. Option one was predicting a player’s win likelihood for any given position and running this evaluation on the position resulting from each possible move to determine the best one. Option two, which I chose, involved assigning scores (probabilities) to each move, reflecting how strongly the network favored them.</p><p>I then used Monte Carlo Tree Search (MCTS) to evaluate positions (check out <a href="https://ryan-leong.medium.com/an-intuitive-explanation-of-how-computers-play-chess-mcts-algorithm-e327ae6bea60">this</a> article for the intuition behind MCTS!). Each position and its evaluation were paired as a tuple and added to the training data list.</p><pre>import itertools<br>import pickle<br>import tqdm<br>from game_logic import *<br><br><br>def valid_turns(board):<br>    # Input: 1D list<br>    if board.count(1) == board.count(-1) or board.count(1) - 1  == board.count(-1):<br>        return True<br>    return False<br><br><br>def outcome_1D(board):<br>    win_conditions= [<br>            [0, 1, 2], [3, 4, 5], [6, 7, 8],  # rows<br>            [0, 3, 6], [1, 4, 7], [2, 5, 8],  # columns<br>            [0, 4, 8], [2, 4, 6]  # diagonals<br>    ]<br>    for condition in win_conditions:<br>        square = condition[0]<br>        if board[square] != 0:<br>            win = True<br>            token = board[square]<br>            for square in condition[1:]:<br>                if board[square] != token:<br>                    win = False<br>                    break<br>            if win == True:<br>                return True<br>    return False<br><br><br>def player_turn(board):<br>    if board.count(1) == board.count(-1):<br>        return 1<br>    elif board.count(1) - 1 == board.count(-1):<br>        return -1  <br><br><br>possible_items = [1, -1, 0]<br>all_boards = list(list(tup) for tup in itertools.product(possible_items, repeat=9))<br><br>valid_boards = [board for board in all_boards if 0 in board]  # Ensure at least 1 empty square<br>valid_boards = [board for board in valid_boards if valid_turns(board)]<br>valid_boards = [board for board in valid_boards if not outcome_1D(board)]<br>boards_with_turn = [(board, player_turn(board)) for board in valid_boards]<br><br># Convert flat boards to Board objects for MCTS to work with<br>boards = []<br>for flat_board, turn in boards_with_turn:<br>    flat_board = [flat_board[i] * turn for i in range(9)]  # Ensure player to move is always represented by &#39;1&#39; token<br>    board = [flat_board[i:i+3] for i in range(0, 9, 3)]<br>    empties = [(x, y) for y in range(3) for x in range(3) if board[y][x] == 0]<br>    board = Board(3, 3, 3, 1, board, empties)<br>    boards.append(board)<br><br># Evaluate boards with MCTS<br>training_data = []<br>iterations = 200<br>for board in tqdm.tqdm(boards, desc=&quot;Game Generation Progress&quot;):<br>    mcts = MCTS(board)<br>    move_probs = mcts.search(iterations, 10)<br>    training_data.append((board, move_probs))<br><br># Save training data<br>with open(f&#39;train_data/mcts{iterations}_iterations.pkl&#39;, &#39;wb&#39;) as f:<br>    pickle.dump(training_data, f)</pre><h4>Training the model</h4><p>To decide the network architecture I just did some Googling to see what others did for similar projects (a great way to decide on architecture). For other elements like the loss function, optimizer, MCTS search strength, and train/test split, I just relied on experimentation to see what worked.</p><p>Here’s short list of things I learned</p><ol><li>SGD requires a much larger learning rate to achieve similar results to Adam (~500X)</li><li>Larger networks require lower learning rates due to having more parameters to adjust</li></ol><pre>import pickle<br>import random<br>import tqdm<br>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>from game_logic import *<br><br><br>class TTTNet(nn.Module):<br>    def __init__(self, input_size=9, hidden_size=36, output_size=9):<br>        super().__init__()<br>        self.fc1 = nn.Linear(input_size, hidden_size)<br>        self.fc2 = nn.Linear(hidden_size, hidden_size)<br>        self.fc3 = nn.Linear(hidden_size, output_size)<br>        <br>    def forward(self, x):<br>        x = self.fc1(x)<br>        x = torch.relu(x)<br><br>        x = self.fc2(x)<br>        x = torch.relu(x)<br><br>        x = self.fc3(x)<br>        x = torch.sigmoid(x)<br>        return x<br><br><br>def calculate_loss(data_set, net, loss_metric, optimizer=None):<br>    total_loss = 0<br>    for board, move_probs in data_set:<br>        output = net(board)<br>        loss = loss_metric(output, move_probs)<br>        if optimizer: # Train the network if an optimizer is provided<br>            optimizer.zero_grad()<br>            loss.backward()<br>            optimizer.step()<br>        total_loss += loss.item()<br>    return total_loss / len(data_set)<br><br><br>def calculate_accuracy(data_set, net, probability_threshold=0.1, return_failed_predictions=False):<br>    &quot;&quot;&quot;<br>    A prediction is considered correct if the network&#39;s highest probability move<br>    is within the probability_threshold of the target&#39;s highest probability move.<br>    &quot;&quot;&quot;<br>    correct = 0<br>    for board, move_probs in data_set:<br>        output = net(board)<br>        best_move = torch.argmax(move_probs)<br>        best_moves = (move_probs &gt;= move_probs[best_move] - probability_threshold).nonzero().flatten()<br>        if torch.argmax(output) in best_moves:<br>            correct += 1<br>    return correct / len(data_set)<br><br><br>def save_model(model, hidden_size, train_test_split):<br>    train_pct = int(train_test_split * 100) # Convert to percentage for model path<br>    model_path = f&#39;saved_models/model_{hidden_size}h_{train_pct}tr.pth&#39;<br>    torch.save(model.state_dict(), model_path)<br>    print(f&quot;Model saved to {model_path}&quot;)<br><br><br>def train_model(train_test_split, network_hidden_size, epochs=20, learn_rate=0.3):<br>    # Prepare training data<br>    with open(&#39;train_data/mcts200_iterations.pkl&#39;, &#39;rb&#39;) as f:<br>        all_data = pickle.load(f)<br>    device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>    tensor_data = [(torch.tensor([board.state[y][x] for y in range(3) for x in range(3)], dtype=torch.float).to(device),<br>                    torch.tensor([move_probs[y][x] for y in range(3) for x in range(3)], dtype=torch.float).to(device))<br>                    for board, move_probs in all_data]<br>    random.shuffle(tensor_data)<br>    split_idx = int(len(tensor_data) * train_test_split)<br>    train_data = tensor_data[:split_idx]<br>    test_data = tensor_data[split_idx:]<br><br>    # Initialize variables for training loop<br>    net = TTTNet(hidden_size=network_hidden_size).to(device)<br>    optimizer = optim.SGD(net.parameters(), lr=learn_rate)<br>    loss_metric = nn.MSELoss()<br>    <br>    # Train the network<br>    for epoch in tqdm.tqdm(range(epochs)):<br>        print(f&quot;========= Epoch {epoch} =========&quot;)<br>        train_loss = calculate_loss(train_data, net, loss_metric, optimizer)<br>        print(f&quot;Train loss: {train_loss}&quot;)<br>        with torch.no_grad():<br>            train_accuracy = calculate_accuracy(train_data, net)<br>            print(f&quot;Train accuracy: {train_accuracy}&quot;)<br>            if train_test_split &lt;1.0:<br>                test_loss = calculate_loss(test_data, net, loss_metric)<br>                print(f&quot;Test loss: {test_loss}&quot;)<br>                test_accuracy = calculate_accuracy(test_data, net)<br>                print(f&quot;Test accuracy: {test_accuracy}&quot;)<br>     <br>    # Save the trained model<br>    save_model(net, network_hidden_size, train_test_split)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    train_model(0.8, 36)</pre><h4>Results</h4><p>First let’s talk about some silly things I did when evaluating my model’s performance:</p><p>At first I penalized the network whenever its top move didn’t match with the top MCTS move. Then I started wondering why the accuracy would always peak at 80%, and it turns out that the network was being penalized in positions where there were multiple equally good moves, and it just happened to choose one other than the top MCTS move.</p><p>To fix this, I counted a prediction as correct if the model’s top move was among the top MCTS moves (moves with a probability score within 0.05 of the “best move” by MCTS).</p><p>With this change, using only 10% of the full dataset for training, the network achieved 80% accuracy when tested on unseen positions from the remaining 90% of the dataset. However when I played against the network myself, it messed up far more often than 1 in 5 moves.</p><p>After some digging, I realized it’s because the opening positions are underrepresented in the training data, so a random sample has a high chance of not including them. This is important because many tic-tac-toe games are decided within the first 1–3 moves!</p><p>Here’s a breakdown of failed predictions by game length. The percentage is calculated as the number of failed predictions divided by the total positions of that length.</p><p>Game length 0: 100.00% failure rate<br>Game length 1: 66.67% failure rate<br>Game length 2: 33.33% failure rate<br>Game length 3: 14.68% failure rate<br>Game length 4: 10.85% failure rate<br>Game length 5: 5.61% failure rate<br>Game length 6: 1.82% failure rate<br>Game length 7: 1.72% failure rate<br>Game length 8: 8.56% failure rate</p><p>As we can see, the network struggles with openings but excels in the middle game. This is because middle game decisions, like winning immediately or blocking threats, are more straightforward. Openings, however, are subtler, and the network can’t apply middle game knowledge to them.</p><p>To fix this, I’d ensure the training data has a balanced number of games across all game lengths. Alternatively, we could train on the full dataset and skip the test set if we’re evaluating by playing against the model.</p><p>After training several models, the highest accuracy I achieved was 99% with a network of 2048 neurons per hidden layer. Adding more neurons didn’t improve accuracy, so I’m unsure if it’s a neural network limitation or if I needed more training epochs or a different learning rate.</p><p>In general, the best models could force wins, get 3 in a row, and block threats. However, they made at least one mistake every 2–3 games.</p><p>That’s it for this project, but I’m curious how to enable a network to achieve perfect play without training on all tic-tac-toe positions. One thing I would try is comparing the linear network’s performance directly to a convolutional neural network, but that’s a topic for another time.</p><p>There is another issue I’d like to mention here though. It’s an issue with the training data itself.</p><p>Monte Carlo Tree Search (MCTS) often converges on a single move, even when multiple best moves exist, which can mislead the network</p><h4>More on MCTS</h4><p>MCTS tends to converge on a single good move, even when several are equally strong. The more iterations it runs, the more one move gets a much higher score (like 0.9) than the others, which can be misleading when multiple moves lead to a forced win or draw.</p><p>Interestingly, the network generalized better, recognizing when moves were equally good, and got penalized for being “inaccurate” when MCTS gave extreme results.</p><p>I could influence the top move by adding a starting bonus to a node, but if the move isn’t one of the best, MCTS always corrects itself. The random playouts heavily impact which move MCTS converges on, so if one move gets a higher score early on, it’s more likely to be selected.</p><p>I added a file called 4_test_mcts.py if you want to experiment with this.</p><p>Now that we’ve covered how MCTS works, let’s move on to testing and experimenting with the model yourself :)</p><h4>Experiment with the model here!</h4><p>Link to the <a href="https://github.com/Programmer484/SL-TicTacToe-NN">code</a>. Just download it as a zip file, extract it, and make sure you open the “SL-TicTacToe-NN” folder in your code editor so the file pathing is correct.</p><ol><li>To experiment with the training process, run 2_train_net.py</li><li>To play against the model, or have different nets play against each other, run 3_test_net.py</li></ol><p>Be curious and have fun!</p><p>If you’re interested in an interactive tutorial on building a model like this from scratch, check <a href="https://colab.research.google.com/drive/12G5C9Bqm6aclkmQ1Q4rg2mPmia-0LPRr">this</a> out :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5456254970ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An intuitive explanation of how computers play chess (MCTS algorithm)]]></title>
            <link>https://ryan-leong.medium.com/an-intuitive-explanation-of-how-computers-play-chess-mcts-algorithm-e327ae6bea60?source=rss-51b3afa34f08------2</link>
            <guid isPermaLink="false">https://medium.com/p/e327ae6bea60</guid>
            <category><![CDATA[intuition]]></category>
            <category><![CDATA[monte-carlo-tree-search]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[chess]]></category>
            <dc:creator><![CDATA[Ryan Leong]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 21:30:32 GMT</pubDate>
            <atom:updated>2024-12-27T02:50:37.534Z</atom:updated>
            <content:encoded><![CDATA[<h3>An intuitive explanation of how computers play board games (MCTS algorithm)</h3><p>First, a note to the different audiences that may read this article.</p><ol><li>If you don’t have a background in coding, or just want a high level overview, the first section “A human analogy for search algorithms” is all you need to read.</li><li>If you know how to code and want to get technical, keep going after that :)</li><li>If you just want to start with the demo and work your way backward, go <a href="https://colab.research.google.com/drive/16QiwN7baHeEatbe5Udvt4T4J8kmqyve8#scrollTo=H_0ajS9TNSnz">here</a> and hit “Runtime” &gt; “Run all”. <br>* The demo allows you to play against a tic-tac-toe bot on any board size with any win length (very slow beyond 6x6 board size though).</li></ol><h3>A human analogy for search algorithms</h3><p>How do computers determine the best move in a board game like chess? Well, there a few main methods. One of these methods is a search algorithm known as minimax. To give you a rough intuition of how minimax works, imagine the minimax algorithm as a human player called Max, with a certain play style.</p><p>Every time it is Max&#39;s turn, they will consider <em>every</em> single move they can make on the board, even if it&#39;s as crazy as putting their queen up for easy grabs. You see, Max never jumps to conclusions. In their mind, you never know when that seemingly dubious queen move is actually a brilliant sacrifice.</p><figure><img alt="All possible moves" src="https://cdn-images-1.medium.com/max/497/1*EDHjf6CaWd2azvP3xDQsLA.png" /><figcaption>I didn’t draw the arrows for all the other circled pieces but imagine considering each move they have possible</figcaption></figure><p>For every move Max is considering, they&#39;ll check every single response that their opponent can make. Max likes to be very thorough in their analysis. They never dismiss <em>any</em> move when calculating variations.</p><p>At some point, after Max has calculated to a certain depth, they&#39;ll stop and just use their general knowledge of chess to determine roughly how good the position is.</p><p>For example, if Max calculates a variation where there is a forced combination to win a queen, then they&#39;ll assume that variation is likely very good for them. Even though being up a queen doesn&#39;t guarantee a win, it significantly increases one&#39;s chances of winning.</p><p>Finally, when Max is calculating, they assume that their opponent always plays the best move. Therefore, Max never tries to set up traps that they <em>hope</em> their opponent will fall for, or try to set up risky checkmate because they <em>hope</em> their opponent will miss it.</p><p>Max is very good at playing open positions (for those not into chess, think of open positions as positions with many opportunities for big sacrifices and forced combinations that lead to gaining material or checkmate) because they thoroughly look at every single possibility without missing anything.</p><p>However, they are less good at playing closed positions where each move is about making a tiny improvement to one&#39;s own position. Of course this depends on how good Max&#39;s existing knowledge of chess positions is, but it&#39;s generally harder for Max to find good moves when their calculations do not lead to clear outcomes like checkmate or obvious positional or material advantages.</p><p>If you&#39;re wondering what &quot;existing chess knowledge&quot; is equivalent to for a computer, it&#39;s the static evaluation of a position. In other words, the computer uses a set of rules to give a score to any given position. These rules can include who has more material, whose pieces have more mobility, and other things that give a rough indicator of who is winning in a given position is.</p><p>As you noticed, Max has some weaknesses, so let me introduce you to another chess player called Carlo, whose play style is resembles the Monte Carlo Tree Search (MCTS) search algorithm.</p><p>Just like Max, Carlo always assumes their opponent plays the best move.</p><p>However, when it comes to how they spend their time, Carlo likes to consider a handful of moves that seem promising given their general knowledge of chess, and explore those moves further. Carlo doesn&#39;t bother calculating what happens from crazy looking moves like queen sacrifices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*0TkN5Jyx6x_QvNshNlYEww.png" /><figcaption>Carlo only looks into a few possible moves, represented by the arrows</figcaption></figure><p>As a result, Carlo doesn&#39;t do great in open positions with very specific combinations that win material, especially against players like Max. This is because the way Carlo dismisses moves, they&#39;ll often miss that <em>one</em> opponent response which punishes Carlo&#39;s move, when all the other opponent responses would&#39;ve let to Carlo having a better position.</p><p>On the other hand, because Carlo chooses a few promising moves to look into, they do better than Max in closed positions, because they have more time to explore the variations they&#39;ve chosen deeper, so they can be more confident in whichever move they&#39;ve chosen out of the few promising moves.</p><p>But did you know, Carlo&#39;s play style is actually on a spectrum! On one end of the spectrum (maximum exploitation), Carlo will choose very few promising moves (top 1-2 moves) to explore, and when exploring each of these moves, they&#39;ll only look at what they believe are the top 1-2 opponent responses. This only tends to work out if Carlo&#39;s general chess knowledge is VERY strong. On the other end of the spectrum (maximum exploration), Carlo looks at all possible moves, and calculates all possible variants exactly like Max. Usually Carlo plays best somewhere in between these extremes.</p><p>Today, we&#39;ll be focusing on MCTS, since it has some applications in machine learning that standard Minimax not well suited for. We&#39;ll be using tic-tac-toe as the test medium, because chess has too many possibilities for MCTS to work well in a short amount of time.</p><h3>Evaluating tic-tac-toe board positions</h3><p>Let’s start by figuring out how to evaluate different game positions. For a simple game like tic-tac-toe, we could use a minimax algorithm to explore every possible move until the game ends. However, for more complex games like chess, that’s not practical because there are too many possible moves (a high “branching factor”). In these cases, minimax needs to assign a score to each <em>leaf position</em> — in simpler terms, these are positions where a player might stop thinking ahead and decide, “This looks like a good outcome to me.” You can think of them as end points in a tree diagram of possible moves. In chess, we might evaluate these positions based on things like material advantage or piece activity.</p><p>However, there is actually another way to evaluate positions which doesn’t require us to come up with a rule set specific to the game! It’s called using random playouts, and it’s commonly used for MCTS. More on that later!</p><p>Now would be a good time to open up a code editor and start following along :) The rest of the code in this tutorial can <em>also</em> be found in <a href="https://colab.research.google.com/drive/16QiwN7baHeEatbe5Udvt4T4J8kmqyve8#scrollTo=xApVmblTiba7">this Google colab</a> if you prefer to work with the colab rather than a code editor. The explanations are also included.</p><p>First off, we need a way to represent our tic-tac-toe board. Here’s a Board class for convenience.</p><p>Don’t worry about the details of the implementation. Instructions on how to use it are after the code block.</p><pre>&quot;&quot;&quot;Board&quot;&quot;&quot;<br>class Board():<br>    def __init__(self, board_width, board_height, win_length, turn, state=None, empties=None):<br>        self.board_width = board_width<br>        self.board_height = board_height<br>        self.win_length = win_length<br>        self.turn = turn<br>        if state == None:<br>            self.state = tuple([0. for _ in range (board_width)] for _ in range(board_height))<br>            self.empties = [(x, y) for y in range (board_height) for x in range(board_width)]<br>        else:<br>            self.state = tuple([x for x in y] for y in state)<br>            self.empties = [e for e in empties]<br>    def __str__(self):<br>        board_state_as_str = &quot;&quot;<br>        board_state = [row.copy() for row in self.state]<br>        for row in board_state:<br>            for i, token in enumerate(row):<br>                if token == 1.0:<br>                    row[i] = &quot;X&quot;<br>                elif token == -1.0:<br>                    row[i] = &quot;O&quot;<br>                elif token == 0.0:<br>                    row[i] = &quot;_&quot;<br>            board_state_as_str += str(row) + &quot;\n&quot;<br>        return board_state_as_str<br>    def deepcopy(self):<br>        board = Board(self.board_width, self.board_height, self.win_length, self.turn, self.state, self.empties)<br>        return board<br>    def out_of_bounds(self, square):<br>        return (square[0] &lt; 0 or square[1] &lt; 0 or square[0] &gt;= self.board_width or square[1] &gt;= self.board_height)<br>    def outcome(self, updated_square):<br>        player_num = self.state[updated_square[1]][updated_square[0]]<br>        vectors = []<br>        for x in [-1, 0, 1]:<br>            for y in [-1, 0, 1]:<br>                if x == 0 and y == 0:<br>                    continue<br>                if updated_square[0] - 1 &lt; 0 and x == -1:  # past left edge<br>                    continue<br>                if updated_square[0] + 1 &gt; self.board_width - 1 and x == 1:  # past right edge<br>                    continue<br>                if updated_square[1] - 1 &lt; 0 and y == -1:  # past top edge<br>                    continue<br>                if updated_square[1] + 1 &gt; self.board_height - 1 and y == 1:  # past bottom edge<br>                    continue<br>                neighbour_x, neighbour_y = updated_square[0] + x, updated_square[1] + y<br>                if self.state[neighbour_y][neighbour_x] == player_num:<br>                    vector = (neighbour_x - updated_square[0], neighbour_y - updated_square[1])<br>                    if vector not in [(v[0]*-1, v[1]*-1) for v in vectors]:<br>                        vectors.append(vector)<br>        for vector in vectors:<br>            line_length = 1<br>            reversing = False<br>            i = 1<br>            while i &lt; self.win_length:<br>                if not reversing:<br>                    x = updated_square[0] + i * vector[0]<br>                    y = updated_square[1] + i * vector[1]<br>                    next_square = x, y<br>                else:<br>                    x = updated_square[0] + i * -vector[0]<br>                    y = updated_square[1] + i * -vector[1]<br>                    next_square = x, y<br>                if self.out_of_bounds(next_square) \<br>                or self.state[next_square[1]][next_square[0]] != player_num:<br>                    if not reversing:<br>                        reversing = True<br>                        i = 0<br>                    else:<br>                        break<br>                else:<br>                    line_length += 1<br>                    if line_length &gt;= self.win_length:<br>                        return player_num<br>                i += 1<br>        if len(self.empties) == 0:<br>            return 0<br>        return None<br>    def make_move(self, move_coords: tuple):<br>        self.empties.remove(move_coords)<br>        self.state[move_coords[1]][move_coords[0]] = self.turn<br>        self.turn *= -1<br>def grid_print(grid, space=0, decimals=0, title=&quot;&quot;):  # Prints the board neatly.<br>    print(title)<br>    if grid != None:<br>      for row in grid:<br>          print(&quot;[&quot;, end=&quot;&quot;)<br>          for col in row:<br>              print(&quot; &quot;, end=&quot;&quot;)<br>              exec(&quot;&quot;&quot;print(&quot;{:%s.%sf},&quot;.format(col), end=&quot; &quot;)&quot;&quot;&quot; % (space, decimals))<br>          print(&quot;]&quot;)<br>      print()<br>    else:<br>      print(&quot;No output\n&quot;)</pre><p>Player tokens are represented with -1s and 1s, empty spaces are represented by 0s.</p><p>Create a board for tic-tac-toe with this code. The 1 for the 4th parameter indicates that the 1s player will move first.</p><pre>board = Board(3, 3, 3, 1)</pre><p>Make moves by passing a tuple with (x, y) coordinates of the square you want to place a token on. The Board class automatically ensures the players alternate turns.</p><pre>board.make_move((0, 0))  # Places a token in the top-left corner</pre><p>Cool! Back to random playouts. Here’s the general idea:</p><p>Imagine there is a chess position where White has one move that captures Black’s queen for free, and the rest of their moves don’t. What MCTS does with random playouts is: for every single move White has in that position, it simulates a bunch of random continuations from that move until the game is over. Given enough simulations, we should find that the move where White captured their opponent’s queen leads to an overall higher win rate compared to the moves where it didn’t.</p><p>I encourage you to try coding this yourself! The exercise is below.</p><p>For the exercise, we’d like the MCTS function to return a 2D list where every move is assigned a value between -1 and 1, where -1 indicates the move is very likely to lead to a win for the -1s player. Same idea for the 1s player. 0 indicates a likely draw.</p><p>For example, in this position where it is the -1s player’s turn to move:</p><pre>[[-1,-1, 1],<br> [ 1,-1, 0],<br> [ 1, 0, 1]]</pre><p>The MCTS function should return the following grid, since placing on the bottom row results in a win for the -1s player while placing on the right column allows the 1s player to win by going on the bottom row the next turn</p><pre>[[ 0.0, 0.0, 0.0],<br> [ 0.0, 0.0, 1.0],<br> [ 0.0,-1.0, 0.0]]</pre><pre># Exercise<br>class MCTS:<br>    def __init__(self, board):<br>        self.board = board<br><br>    def search(self):<br>        for move in self.board.empties:<br>            pass  # give the move a score based on several random games from that move onward<br><br># Test cases<br>board1 = Board(3, 3, 3, 1)<br>board1.make_move((0, 0))<br>board1.make_move((1, 1))<br>board1.make_move((0, 1))<br>board1.make_move((0, 2))<br><br>board2 = Board(3, 3, 3, 1)<br>board2.make_move((0, 0))<br><br>board3 = Board(3, 3, 3, 1)<br>board3.make_move((0, 0))<br>board3.make_move((1, 1))<br>board3.make_move((2, 2))<br><br># Your final scores should roughly resemble the scores in the grids below.<br>grid_print(board1.state, 2, 0, &quot;Board 1&quot;)<br>mcts_searcher1 = MCTS(board1)<br>grid_print(mcts_searcher1.search(), 5, 2, &quot;Value grid&quot;)<br># [[0.00, -0.17,  0.17],<br>#  [0.00,  0.00, -0.83],<br>#  [0.00, -0.33, -0.50]]<br><br>grid_print(board2.state, 2, 0, &quot;Board 2&quot;)<br>mcts_searcher2 = MCTS(board2)<br>grid_print(mcts_searcher2.search(), 5, 2, &quot;Value grid&quot;)<br># [[0.00, 0.45, 0.29],<br>#  [0.45, 0.12, 0.45],<br>#  [0.29, 0.45, 0.29]]<br><br>grid_print(board3.state, 2, 0, &quot;Board 3&quot;)<br>mcts_searcher3 = MCTS(board3)<br>grid_print(mcts_searcher3.search(), 5, 2, &quot;Value grid&quot;)<br># [[ 0.00, -0.10, -0.17],<br>#  [-0.10,  0.00, -0.10],<br>#  [-0.17, -0.10,  0.00]]<br></pre><p>Great work!</p><p>Short summary of my solution:</p><ol><li>For each potential move, we first check if it immediately ends the game, and return the corresponding value (-1 for a -1s player win, 0 for a draw, and 1 for a 1s player win) if it does. Otherwise, we move on to simulating games to get an estimate for how good the move is.</li><li>In the simulate function, we play a set number of random games and take the average outcome of all the random games played to give us our final expected outcome.</li><li>The play_random_game function keeps making random moves for each side until the game ends. It returns a value of -1 for a -1s player win, 0 for a draw, and 1 for a 1s player win.</li></ol><pre># Solution<br>import random<br><br><br>class MCTS:<br>    def __init__(self, board):<br>        self.board = board<br><br>    def simulate(self, board, reps):<br>        total_value = 0<br>        for _ in range (reps):<br>            total_value += self.play_random_game(board.deepcopy())<br>        return total_value / reps<br><br>    def play_random_game(self, board):<br>        game_on = True<br>        while game_on:<br>            move = random.choice(board.empties)<br>            board.make_move(move)<br>            value = board.outcome()<br>            if value != None:<br>                return value<br><br>    def search(self):<br>        move_probability_grid = [[0.0 for x in range(3)] for y in range(3)]<br>        for move in self.board.empties:<br>            new_board = self.board.deepcopy()<br>            new_board.make_move(move)<br>            value = new_board.outcome()<br>            if new_board.outcome() == None:<br>                value = self.simulate(new_board, 5000)<br>            move_probability_grid[move[1]][move[0]] = value<br>        return move_probability_grid<br><br># Test cases<br>board1 = Board(3, 3, 3, 1)<br>board1.make_move((0, 0))<br>board1.make_move((1, 1))<br>board1.make_move((0, 1))<br>board1.make_move((0, 2))<br><br>board2 = Board(3, 3, 3, 1)<br>board2.make_move((0, 0))<br><br>board3 = Board(3, 3, 3, 1)<br>board3.make_move((0, 0))<br>board3.make_move((1, 1))<br>board3.make_move((2, 2))<br><br><br># Your final scores should roughly resemble the scores in the grids below.<br>grid_print(board1.state, 2, 0, &quot;Board 1&quot;)<br>mcts_searcher1 = MCTS(board1)<br>grid_print(mcts_searcher1.search(), 5, 2, &quot;Value grid&quot;)<br># [[0.00, -0.17,  0.17],<br>#  [0.00,  0.00, -0.83],<br>#  [0.00, -0.33, -0.50]]<br><br>grid_print(board2.state, 2, 0, &quot;Board 2&quot;)<br>mcts_searcher2 = MCTS(board2)<br>grid_print(mcts_searcher2.search(), 5, 2, &quot;Value grid&quot;)<br># [[0.00, 0.45, 0.29],<br>#  [0.45, 0.12, 0.45],<br>#  [0.29, 0.45, 0.29]]<br><br>grid_print(board3.state, 2, 0, &quot;Board 3&quot;)<br>mcts_searcher3 = MCTS(board3)<br>grid_print(mcts_searcher3.search(), 5, 2, &quot;Value grid&quot;)<br># [[ 0.00, -0.10, -0.17],<br>#  [-0.10,  0.00, -0.10],<br>#  [-0.17, -0.10,  0.00]]</pre><p>After we run the cell, we can see our algorithm performs quite well in the first two examples.</p><p>In the 1st example, it is the 1s player’s turn. The algorithm indicates that playing in the top-right corner gives the 1s player the best chance of winning. In other words, it has correctly recognized that the best move is for the 1s player to block their opponent’s win threat.</p><p>In the 2nd example it is it is the -1s player’s turn. Our MCTS algorithm was able to recognize that playing in the center gives the -1 player the best chance of winning, as seen by the assignment of the lowest value to the center square. In fact, any other move results allows the 1s player to force a win. You can verify this for yourself.</p><p>However, in the 3rd position, where it is the -1s player’s turn to move, the two moves it thinks give the -1s player the best chance at winning are actually the only two moves that allow the 1s player to force a win!</p><p>So random playouts are a pretty good way of evaluating a position, but it clearly isn’t perfect. That’s why we need to implement the rest of the search tree so the MCTS algorithm can also operate under the assumption that each player will choose the best move for themselves</p><p>Back to our analogy with Carlo, what we’d like to do is have our algorithm choose a few interesting moves and explore them deeper, while keeping the assumption that their opponent will always choose the best move as well.</p><h3>The 4 steps of MCTS</h3><p>The actual implementation of MCTS is little different from how I’ve described Carlo, our human player analogy for MCTS. MCTS has four main phases: Selection, Expansion, Evaluation, and Backpropagation. These 4 steps are repeated in a cycle for a fixed number of times. The more times we repeat this cycle, the more parts of the game tree we get to explore, and the stronger the final suggested move will be.</p><h3>Selection</h3><p>Selection is about deciding which moves to explore deeper. The way we score a move is:</p><p>score = value + exploration bonus</p><p>For a given position, a value of -1.0 means our evaluation predicts the -1s player is highly likely to win, and 1.0 means it predicts the 1s player is highly likely to win. Just like we did with random playouts.</p><p>For now, think of exploration bonus as 1/# times a move has been explored. Essentially, we want to go more in depth and further evaluate moves that our initial evaluation suggests are good, but we also want to explore moves that we haven’t looked at as thoroughly in case they are actually good moves. It’s a balancing act between exploitation (keep exploring good moves) and exploration (checking out more alternatives).</p><p>How much our algorithm explores is actually determined by an exploration/exploitation parameter which we’ll call “c”, which we can use assign different weight to the value and exploration bonus. So our final score formula looks more like:</p><p>score = value + c * exploration_bonus</p><p>Finally, when deciding on the “value” for a move, we choose the move based on which player’s turn it is.</p><p>In the following image, each box represents a position, with “Root” indicating our starting position. The numbers in each box indicate our evaluations of which player is most likely to win in each position. Each arrow represents a move. Assume in the root position it is the 1s player’s turn to move.</p><p>For simplicity, let’s ignore the exploration bonus for now. When we choose our first move, we choose from the 1s player’s perspective, meaning we want to take move that leads to the position with the highest value. However, on the next layer, we choose from the -1s player’s perspective because it is now their turn. This time, we want to take a move leading to the position with the lowest value. We repeat this process until we reach a leaf node, which is a node where none of the child positions have been explored yet, either because the MCTS algorithm hasn’t had a chance to yet, or the node is a final game state (win/loss/draw).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*A8cljBbEbIKdHwZyf8hE0w.png" /></figure><p>Now here’s how the exploration bonus might come into play:</p><p>When we first run the MCTS algorithm, both exploration bonuses (E) are equal, so it’ll keep selecting the node on the right since it has a significantly higher initial evaluation. However, eventually, as the node gets explored more and more, the exploration bonus for exploring the node on the left grows until the overall score for choosing the move that leads to that position is higher than the score for the right side position. At this point we choose to select the node on the left instead, as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkZEydI0jt8yhA7uaCtD0g.png" /></figure><p>Why? Remember that our initial evaluation of any position is far from perfect, so the move on the left might not be as bad for the 1s player as it seems.</p><p>Maybe upon exploring the left position more, it turns out there is actually a brilliant queen sacrifice that gives the 1s player a huge positional advantage!</p><p>In that case, we will update the value of the left position to be much more favourable, and start exploring that more instead.</p><p>At this point you may be asking, how do we explore positions or update our evaluations of each position based on new information? We’ll answer both in the next few sections.</p><h3>Expansion &amp; Evaluation</h3><p>Whenever we reach a leaf node, if it is a terminal node (win/loss/draw), we immediately skip to the backpropagation step. More on that later</p><p>If it is not a terminal node, there are two possibilities:</p><p>If it has not been evaluated yet, then we skip expansion and evaluate it with random playouts.</p><p>Otherwise, we <em>expand</em> the node by creating nodes to represent each of its child positions. Then we randomly choose one of the child positions to evaluate with a random playout. This way we ensure there is always an evaluation step in each cycle of MCTS. For the rest of the unexplored child nodes, we leave their exploration value at infinity, so if the MCTS algorithm ever selects their parent node again, it’ll then select one of the completely unexplored child nodes instead of an already explored child node.</p><p>When leaf node <em>has not</em> been evaluated: skip node expansion and evaluate the given leaf node instead</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*IJjo0jh-Le83q1CXre17mg.png" /></figure><p>When leaf node is already evaluated: expand the node by creating children &amp; evaluate a random child node</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*H8NwQmyUIU6YHjfHQspkJw.png" /></figure><p>How do we evaluate? For tic-tac-toe we can reliably use random playouts, which give a pretty good estimate of how good a position is. Remember, the evaluation function we use doesn’t have to be perfect, because our algorithm will update the initial evaluations to be more accurate as it explores deeper!</p><p>Finally, how does each new cycle of exploration affect our final conclusion of what the best move is? That’s where backpropagation comes in!</p><h3>Backpropagation</h3><p>The core idea behind backpropagation is how we use our new information from each new evaluation to update the rest of the nodes in our search tree.</p><p>I’ve updated the nodes from our previous representation of the search tree to include a total value and visit count. The value of a node is calucated by value = total_value/visit_count. The node in orange has just been evaluated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*FNVhYC-4Rwpj0HS8GiUadg.png" /></figure><p>Below are the 3 steps of backpropagation. What we do is, starting from the parent of the updated node:</p><ol><li>We increase the visit count by 1</li><li>We add the child node’s evaluation to the total value</li><li>We calculate the new value using the formula: value = total_value/visit_count</li></ol><p>Repeat for the next parent node until we reach the root node</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*f3ZpL3Kfq_Jcg_DWj6Qo5w.png" /></figure><p>Calculating value with total_value/visit_count ensures that nodes which don&#39;t have many evaluations contributing to their end value are updated more heavily than nodes which we are already confident about the values of, since they have a lot more evaluations supporting their end value.</p><p>And there you have it! The essence of MCTS!</p><h3>Implementing MCTS with code</h3><p>What’s next? Well the best way to learn something is to try and build it yourself :D</p><p>I encourage you to try implementing the MCTS algorithm based on the steps I’ve given you. If you get stuck, feel free to use Google or take a peek at the part of the solution code that you’re stuck on.</p><p>Before you start, here is the actual formula (it’s called UCT) used to calculate the score of a child node when deciding which positions to explore further during the selection phase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*u7_TYGsipW8nHAZw9HwsOQ.png" /></figure><p>value = evaluation of the child node’s position</p><p>c = exploration/exploitation parameter (the greater c is, the more weight we give to exploration over exploitation, and vice versa)</p><p>Vp = visit count of the parent node (we take the natural log of this in our calculation)</p><p>Vc = visit count of the child node</p><p>We plug all these values into the formula for each child node, then select the child node with the highest score!</p><p>Okay you have all the tools you need to code MCTS now. Here’s some starter code too. You might need to modify it depending on what approach you use. Good luck😁</p><p>Your final output should be a nested list representing move probabilities for each move from 0 to 1. The sum of the probabilities for all moves should add up to 1.</p><p>Example:</p><pre>[[-1, 0, 0],<br> [ 0, 1, 0],<br> [ 0, 0,-1]]</pre><p>In the above position where it is the 1 player’s turn to move, your MCTS algorithm’s output should approach the probabilities in the grid below as you increase the number of cycles. Around 200 cycles you can see the algorithm clearly starting to favour the 4 edge squares over the top-right and bottom-left corners.</p><pre>[[0.00, 0.25, 0.00],<br> [0.00, 0.00, 0.25],<br> [0.00, 0.25, 0.00]]</pre><p>Hint: Remember that selection favours visiting good nodes more often, so the best moves will be visited the most times by the time the algorithm finishes.</p><pre>import math<br><br><br>class Node:<br>    def __init__(self, parent, board, move):<br>        self.parent = parent<br>        self.children = []<br>        self.visit_count = 1<br>        self.total_value = 0<br>        self.board = board<br>        self.move = move  # Used as a parameter for the board outcome check since it requires knowing the last move played<br><br>    def is_terminal(self):<br>        return self.board.outcome() != None<br><br>    def is_leaf(self):<br>        return self.children == []<br><br>class MCTS:<br>    def __init__(self, board):<br>        self.root_node = Node(None, board, (-2, -2))<br>        self.c = 1.4142  # Exploration/exploitation parameter. Increase to explore more.<br><br>    if node.visit_count == 0:  # Prioritize selecting nodes that haven&#39;t been explored<br>            return 1000000<br>        else: <br>            return (player_num * node.total_value/node.visit_count) + self.c * math.sqrt(math.log(parent.visit_count) / node.visit_count)<br><br>    def select(self):<br>        pass<br><br>    def expand(self):<br>        pass<br><br>    def evaluate(self):<br>        pass<br><br>    def backpropagate(self):<br>        pass<br><br>    def search(self, reps):<br>        pass</pre><p>Here’s my implementation. It’s just the coded version of what we talked about in the article. Feel free to reference it whenever you get stuck!</p><pre># Solution<br>import math<br>import random<br><br><br>&quot;&quot;&quot;MCTS&quot;&quot;&quot;<br>class Node:<br>    def __init__(self, parent, board, move):<br>        self.parent = parent<br>        self.children = []<br>        self.visit_count = 0<br>        self.total_value = 0<br>        self.board = board<br>        self.move = move  # Used as a parameter for the board outcome check since it requires knowing the last move played<br><br>    def is_terminal(self):<br>        return self.board.outcome(self.move) != None<br><br>    def is_leaf(self):<br>        return self.children == []<br><br>class MCTS:<br>    def __init__(self, board):<br>        self.root_node = Node(None, board, (-2, -2))<br>        self.c = 1.4142<br><br>    if node.visit_count == 0:<br>            return 1000000<br>        else: <br>            return (player_num * node.total_value/node.visit_count) + self.c * math.sqrt(math.log(parent.visit_count) / node.visit_count)<br><br>    def select(self, node):<br>        if node.is_leaf():<br>            return node<br>        else:<br>            max_value = -1000000<br>            chosen_node = None<br>            for child_node in node.children:<br>                value = self.uct(node, child_node, node.board.turn)<br>                if value &gt; max_value:<br>                    max_value = value<br>                    chosen_node = child_node<br>            return self.select(chosen_node)<br><br>    def expand(self, node):<br>        legal_moves = node.board.empties<br>        for m in legal_moves:<br>            child_board = node.board.deepcopy()<br>            child_board.make_move(m)<br>            child_node = Node(node, child_board, m)<br>            node.children.append(child_node)<br><br><br>    def evaluate(self, node, playouts):<br>        outcome = node.board.outcome(node.move)<br>        if outcome != None:<br>            return outcome<br>        else:<br>            total_value = 0<br>            for _ in range (playouts):<br>                total_value += self.play_random_game(node.board.deepcopy())<br>            return total_value / playouts<br><br>    def play_random_game(self, board):<br>        game_on = True<br>        while game_on:<br>            move = random.choice(board.empties)<br>            board.make_move(move)<br>            value = board.outcome(move)<br>            if value != None:<br>                return value<br><br>    def backpropagate(self, node, evaluation):<br>        node.visit_count += 1<br>        node.total_value += evaluation<br>        if node.parent != None:<br>            self.backpropagate(node.parent, evaluation)<br><br>    def search(self, iterations, playouts=10):<br>        for _ in range(iterations):<br>            node = self.select(self.root_node)<br>            if node.visit_count == 0 or node.is_terminal():<br>                node_eval = self.evaluate(node, playouts)<br>                self.backpropagate(node, node_eval)<br>            else:<br>                self.expand(node)<br>                child_node = random.choice(node.children)<br>                child_node_eval = self.evaluate(child_node, playouts)<br>                self.backpropagate(child_node, child_node_eval)<br>        move_probs = [[0 for _ in range(self.root_node.board.board_width)] for _ in range(self.root_node.board.board_height)]  # -1 ensures illegal moves are never chosen<br>        for child_node in self.root_node.children:<br>            prob = child_node.visit_count / self.root_node.visit_count<br>            move_probs[child_node.move[1]][child_node.move[0]] = prob<br>        return move_probs</pre><p>Time to test your algorithm :D</p><pre>from tabulate import tabulate  # prints mcts output in a nice grid<br><br><br>def mcts_vs_human(board, mcts_iterations):<br>    game_on = True<br>    while game_on:<br>        if board.turn == 1:<br>            mcts_searcher = MCTS(board)<br>            mcts_move_probs = mcts_searcher.search(mcts_iterations)<br>            max_prob = -1<br>            for y in range(board.board_height):<br>                for x in range(board.board_width):<br>                    if mcts_move_probs[y][x] &gt; max_prob:<br>                        max_prob = mcts_move_probs[y][x]<br>                        chosen_move = (x, y)<br>            print(&quot;Move probabilities:&quot;)<br>            print(tabulate(mcts_move_probs, tablefmt=&quot;simple_grid&quot;))<br>            board.make_move(chosen_move)<br>        else:<br>            try:<br>                x = input(&quot;x: &quot;)<br>                y = input(&quot;y: &quot;)<br>                chosen_move = (int(x), int(y))<br>                board.make_move(chosen_move)<br>            except Exception:<br>                print(&quot;Invalid move, please try again&quot;)<br>                continue<br>        print(&quot;Board&quot;)<br>        print(board)<br>        value = board.outcome(chosen_move)<br>        if value != None:<br>            break</pre><p>Note that the mcts algorithm always plays as the Xs (internally represented in the Board class as the 1s player). The 4th parameter to the Board class specifies with player goes first.</p><p>A ‘1’ means the algorithm goes first, ‘-1’ means you go first. You can also manually make moves like shown below to test your algorithm on specific positions.</p><p>Have fun experimenting!</p><pre>b = Board(3, 3, 3, -1)<br>b.make_move((0, 0))<br>b.make_move((1, 1))<br>b.make_move((2, 2))<br><br>mcts_vs_human(b, 200)</pre><p>Congrats🎉 You’ve successfully taught a computer how to play tic-tac-toe! In fact, the same approach can easily be generalized to any game.</p><p>We can even do a bit of that here! Remember the first 3 parameters of the board class? They actually allow us to set the board height, board width, and win length of our game! Let’s try experimenting with that!</p><pre>b = Board(6, 6, 4, -1)<br>mcts_vs_human(b, 5000) # Increased # iterations to allow for better performance</pre><p>It works pretty well! The algorithm knows to play in the center and try to get forks (making a move which results in two win threats at the same time, meaning your opponent can only block one)</p><p>However, it takes quite a while! What if we wanted to extend this to a game with more possibilities like Gomoku (objective: 5 in a row on a 15x15 board)? It would take a looooooooooong time to come up with ideal moves. Think about why…</p><p>If you thought about our evaluation function, you are correct! Since we use random playouts to evaluate games, the larger the board, the more moves involved in each random playout. Furthermore, we need A LOT more random playouts to get a better evaluation of a leaf node.</p><p>The second part is that we need more iterations of MCTS to expand our search tree enough to get a better sense of the different possible moves in our game.</p><p>So does that mean MCTS just takes forever for more complex games?</p><p>No! There’s a few things we can do. Firstly, we can replace the random playouts in our evaluation function with a neural network!</p><p>If you’ve never worked with neural networks, think of it as an analogy for a human’s intuition.</p><p>In the context of chess, most players who play regularly develop an intuition/natural instinct of what pieces they should consider moving in a given situation. For example, if an experienced chess player sees a bunch of enemy pieces near their exposed king, they’ll likely focus on protect their king, instead of some useless pawn move on the other side of the board.</p><p>Of course this intuition isn’t always perfect. In fact, when a player first starts out, they DO often consider every single possibility. However, eventually they learn from experience that it is not good to send their king to center of the board, because it always results in them getting checkmated. So gradually, they learn what’s important to focus on and what’s not.</p><p>Another more widly relatable analogy would be when someone first learns to drive, they’re bombarded by information from all around them (cars, signs, checking mirrors, pedestrains, etc)</p><p>However, over time they good at automating several behaviours essential to driving, becoming better drivers in the process.</p><p>A neural network is capable of improving in a similar fashion.</p><p>In the context of tic-tac-toe type games, given enough games, our neural network will learn things like how to easily spot an opponent win threat instead of having to evaluate <em>every single move</em> on a large board with random playouts.</p><p>It can also be used to guide the MCTS algorithm’s search. For example, it can tell the MCTS algorithm to focus on the centre because moves in the centre are generally better than moves on the edges.</p><p>If you want to learn more about neural networks and implement one that enables us to use MCTS for a larger board, stay tuned! Another article just for that is coming in a week!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e327ae6bea60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cuprotein: A novel source of sustainable protein]]></title>
            <link>https://ryan-leong.medium.com/cuprotein-a-novel-source-of-sustainable-protein-acd84d409c7a?source=rss-51b3afa34f08------2</link>
            <guid isPermaLink="false">https://medium.com/p/acd84d409c7a</guid>
            <dc:creator><![CDATA[Ryan Leong]]></dc:creator>
            <pubDate>Fri, 10 May 2024 03:22:08 GMT</pubDate>
            <atom:updated>2024-05-10T03:36:58.532Z</atom:updated>
            <content:encoded><![CDATA[<p>Did you know that by 2050, it’s predicted that we won’t have enough arable farmland to feed the world’s population? Even though with agricultural technology is slowly growing in efficiency per acre of farmland, tiny incremental improvements won’t be enough. We need a solution 10X better. That’s where Cuprotein comes in.</p><p>Cuprotein is based off the concept of single cell proteins (SCP), which are proteins derived from microorganisms like algae, fungi, yeast, and bacteria. The basic idea is that we grow microorganisms in a bioreactor (imagine a large tank filled with the right food and living conditions for the microorganism to thrive), and then put the microorganisms through a process which extracts the protein and other nutrients like vitamins.</p><p>The SCP production process follows four main steps:</p><ol><li>Choosing a microorganism and species</li><li>Preparing the substrate (food the microorganism needs to thrive)</li><li>Creating ideal growth conditions</li><li>Processing the microorganism into edible protein</li></ol><h3>1. Choosing a microorganism and species</h3><p>There are a huge variety of microorganisms that can be used for single cell proteins, but a particular one that holds great promise is the bacteria <em>Cupriavidus Necator.</em></p><p><em>Cupriavidus necator</em> has been experimentally found to contain 63% protein and 6% carbohydrate content making it one of the best bacteria species for SCP production</p><p>Furthermore, all essential amino acids (histidine, isoleucine, leucine, lysine, methionine, phenylalanine, threonine, tryptophan and valine) are present in <em>Cupriavidus Necator</em>, which means it suffices as a singular protein source in one’s diet.</p><p>The nutrients required to feed <em>Cupriavidus Necator</em> are easily gathered as well, which we will explore in the next section</p><h3>2. Preparation of the substrate</h3><p><em>Cupriavidus Necator </em>thrives off of four main ingredients: CO2, a nitrogen source, H2, and O2.</p><p>CO2 is primarily used by <em>Cupriavidus Necator </em>in the CBB cycle to fix CO2, which simply means turning carbon dioxide into organic matter that the cell can use for growth. Since fixing CO2 requires energy, <em>Cupriavidus Necator </em>gets this energy by reacting H2 and O2 in an oxidation reaction. Finally, a source of nitrogen is crucial for the assembly of amino acids, the building block of proteins.</p><p>There are reliable and fairly cost efficient methods of collecting all 4 of these ingredients.</p><p><strong>CO2</strong>: Since atmospheric CO2 is not concentrated enough to allow for fast growth of bacteria, it will either have to be directly captured from an industrial process with high CO2 emissions, or by using carbon capture methods to absorb a high volume of carbon from the atmosphere. Utilizing industry emissions will be the first choice, but when there are no factories nearby then carbon capture from the atmosphere serves as a good alternative.</p><p><strong>H2 and O2: </strong>Currently the most reliable way to produce H2 and O2 is splitting water through electrolysis. New techs may make this more energy efficient or offer a better alternative for H2 and O2 production in the future.</p><p><strong>N2: </strong><em>Cupriavidus Necator </em>is actually capable of utilizing several sources of nitrogen such as ammonia, nitrate, and even urea, a compound found in urine. However, a <a href="http://dx.doi.org/10.1021/es505432w">study has shown</a> that ammonia is the most efficient source of nitrogen. It can be sourced from nearby industrial waste streams with high ammonia concentrations or produced from atmospheric N2 and hydrogen via the commercially available Haber-Bosch process if no industrial waste streams are available.</p><h3>3. Growth conditions</h3><p>Once the bacteria and substrate are chosen, they are put into a bioreactor to grow. In its simplest form, a bioreactor can be thought of as a cylindrical tank with an environment customized to meet the bacteria’s temperature, pressure, pH, and substrate concentration needs</p><p>CO2, H2, and O2 are fed into the bioreactor through a single sparger. <a href="http://dx.doi.org/10.1016/j.bej.2019.107369">According to one study</a>, the maximum growth rate can be obtained with H2:O2:CO2 equaling 7:2:1 in the gas phase at 30 degrees C. Ammonia is added as a water solution to the growth medium.</p><p>We will be using submerged fermentation for our bacteria, which basically means that the cells of the bacteria are submerged in a liquid medium, as opposed to being grown on solid materials like in semi-solid or solid fermentation.</p><p>In terms of other specific bioreactor design details, research is still being done to determine what works best. One key consideration for bioreactor design should be maximizing the transfer of hydrogen and oxygen gas to the liquid phase, so the bacteria cells has enough H2 and O2 to sustain the necessary chemical reactions for rapid growth. Other considerations include how to efficiently maintain elements like pressure, temperature and pH.</p><p>Once the initial bacteria is placed in the bioreactor, new nutrients are continuously fed into the bioreactor while bacterial cell mass is withdrawn. This allows for maximum efficiency.</p><h3>4. Processing</h3><p>Since bacteria taken out of the bioreactor come in a diluted form, they must be separated from the growth medium and further concentrated before it is suitable for consumption.</p><p>This can be done using a centrifugal separator, then drying out the cell mass slurry to preserve them and reduce their volume, making them easier to store and transport. The dried cells can then be processed to remove impurities, improve their nutritional content, and enhance their flavor and texture.</p><p>The final result is a protein powder that can be added as an extra ingredient to fortify protein deficient foods, or consumed on its own.</p><h3>Impact</h3><p>Using <em>Cupriavidus Necator </em>to produce single cell proteins for human consumption will allow us to use 200X less land than beef, ensuring we have a way to reliably produce enough food to feed our rapidly growing population. Furthermore, production of <em>Cupriavidus Necator </em>is estimated to use 600X less water than beef, and also releases 200X less CO2 than beef production. Isn’t that amazing? Not only can we ensure we stop the world won’t starve by 2050, but we also drastically reduce the 30% of carbon emissions that the agriculture industry is responsible for.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acd84d409c7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Basics of Neural Networks for Chess nerds (and anyone interested in AI)]]></title>
            <link>https://ryan-leong.medium.com/the-basics-of-neural-networks-for-chess-nerds-and-anyone-interested-in-ai-e76e03124867?source=rss-51b3afa34f08------2</link>
            <guid isPermaLink="false">https://medium.com/p/e76e03124867</guid>
            <category><![CDATA[intelligent-agent]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[future-of-games]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[chess-ai]]></category>
            <dc:creator><![CDATA[Ryan Leong]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 18:24:40 GMT</pubDate>
            <atom:updated>2025-09-17T03:50:14.277Z</atom:updated>
            <content:encoded><![CDATA[<p>Maybe you’ve heard of AlphaZero, the chess AI that defeated Stockfish, then the world’s strongest engine — but neural networks have powered far more surprising feats. They’ve placed AI in the <a href="https://deepmind.google/discover/blog/alphastar-grandmaster-level-in-starcraft-ii-using-multi-agent-reinforcement-learning/">top 0.2% of Starcraft players</a>, enabled <a href="https://deepmind.google/discover/blog/mastering-stratego-the-classic-game-of-imperfect-information/">wins against experts in Stratego</a> (a game with bluffing and hidden information), and even let <a href="https://ai.meta.com/research/cicero/diplomacy/">AI score double the average human in Diplomacy</a>, a game built on negotiation.</p><p>The common thread in all these breakthroughs is the neural network — the tool that allows AI to learn complex associations and make decisions beyond what traditional code can handle. Today, I’ll go over the basics using chess as an example.</p><p>Below is a diagram of a neural network that outputs a static evaluation of a chess position — without performing any move analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*c2AdbOlPnjPMprwC" /></figure><p>Each of these circles is called a neuron. The input layer consists of several neurons which receive the position of the board and other game information like castling rights and who’s turn to move it is. The output layer consists of one neuron, which returns the evaluation as a number. And the hidden layers are responsible for working together to learn complex associations that any linear function would fail to make. We’ll go more in depth on this later.</p><p>The lines between neurons are known as weights. They are the primary way that neurons from one layer are able to influence the neurons in the next.</p><p>In the next image, I’ve singled out the weights connecting one neuron in the second layer to all the neurons in the previous layer. Each neuron acts like a function which outputs a value based on the input from all the neurons in the previous layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*W1GjgivZRvyPCTUJ" /></figure><p>The actual function used for a neuron is called its <strong>activation function</strong>. To keep this demonstration simple and intuitive, we’ll have our neurons use the sigmoid function, which ensures that all outputs are between 0 and 1, regardless of the input value. As you can see in the diagram, large negative inputs result in an output around 0, while large positive values converge around an output of 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X17CAleyPKsCIAJm" /></figure><p>In case you’re wondering, the purpose of the activation function is to introduce non-linearity to the model. Without an activation function, the entire neural network would just be a linear regression model, because adding linear functions produces a linear function. A model without activation functions would not be able to make any complex associations. I’ll give a simple example below. Feel free to skim this part if it already makes sense to you.</p><p>A linear activation function can be represented in the form of y = mx + b, where ‘y’ represents the output of the neuron, ‘x’ represents the input, ‘b’ represents the bias, and ‘m’ represents the weight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*3D6R2cjhqdPkTKgQFGPS2Q.png" /></figure><p>Let’s start by calling input to our network ‘x₀’. The equations of neurons 1 and 2 are respectively:</p><p>y₁ = m₁x₁ + b₁ || y₂ = m₂x₂ + b₂.</p><p>If we substitute the x values for with the input, ‘x’, our two equations become:</p><p>y₁ = m₁x₀ + b₁ || y₂ = m₂x₀ + b₂.</p><p>Next, the equation for neuron 3 can be represented as:</p><p>y₃ = m₃₁x₃₁ + b₃₁ + m₃₂x₃₂ + b₃₂</p><p>(The underscores have been omitted due to formatting issues)</p><p>If we substitute the equations from neurons 1 and 2 into the equation for the third neuron we get:</p><p>y₃ = m₃₁(m₁x₀ + b₁) + b₃₁ + m₃₂(m₂x₀ + b₂) + b₃₂</p><p>y₃ = m₃₁m₁x₀ + m₃₁b₁ + b₃₁ + m₃₂m₂x₀ + m₃₂b₂ + b₃₂</p><p>This looks like a mess right now, but remember since all the weights and biases, ‘m’ and ‘b’, are constants, they can simply be combined into one constant.</p><p>y₃ = (m₃₁m₁ + m₃₂m₂)x₀ + (m₃₂b₂ + m₃₁b₁ + b₃₁ + b₃₂ )</p><p>y₃ = mx₀ + b</p><p>When using linear activation functions, everything will collapse into one linear function regardless of how many layers or neurons there are. As you can see, it’d be much easier to just use a linear function to begin with.</p><p>Moving on, we have weights. Weights act as a multiplier for the previous neuron’s output value before they are added to the next neuron’s input. Blue weights represent positive multipliers, while red weights represent negative multipliers. A thicker line represents a heavier weight, or in other words, a larger multiplier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/0*mCFpE68y9F8S7k98" /></figure><p>The weights are multiplied by the output values for each neuron, and all of them are added together and passed into the neuron in the next layer.</p><p>Mathematically, the input for this neuron can be represented as: (w₁a₁ + w₂a₂ + w₃a₃ + … + wₙaₙ), where “a” represents the activation/output value of the neuron in the previous layer, and “w” represents the weight connecting it to the neuron in the next layer. This is also known as the weighted sum.</p><p>Here’s an example which assumes the input layer only consists of 6 neurons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*Drl-RVXEmFUCjEyb" /></figure><p>If we assume that a thicker line represents a x2 multiplier while a thinner line represents a x0.5 multiplier, then the weighted sum would be:</p><p>[(0.1 * -0.5) + (0.8* 2) + (0.6 * 2) + (0.8 * -0.5) + (1.0 * 0.5) + (0.9 * -2)] = 1.05</p><p>If we passed this value into the sigmoid activation function of the second layer neuron, we’d get an output value around 0.75.</p><p>At this point, you may be wondering what each output value of the first layer neurons even represent. Hang tight, we’ll get there soon!</p><p>Before we move on, there’s one more factor that influences the output value of a neuron. It’s bias, which is a constant that is added to the weighted sum of a neuron’s input before it’s processed.</p><p>With this new information, our weighted sum can be modelled as: (w₁a₁ + w₂a₂ + w₃a₃ + … + wₙaₙ + b), where “b” represents the bias.</p><p>You can think of bias as a neural network’s way of making adjustments that can’t be achieved by modifying the weights in a network. By modifying its weights and biases, a neural network is able to learn complex associations! We’ll go into the details of how it decides which weights and biases to increase or decrease later.</p><p>First, let’s go through an intuitive example of what each part of a trained neural network might do. Keep in mind that the function of neurons in a trained neural network is usually much more abstract than the examples we’ll be going into here.</p><p>For the purposes of our introductory article, we won’t be going into exactly what part of the chess board each input neuron represents, but usually, a chess position is fed into a neural network in the form of bitboards. I’ll represent the first layer as a board position since it’s much easier than trying to draw and explain a huge number of weights between the first and second layer neurons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*cPaEklwVScSa6VYk" /></figure><p>In our example, the second layer of the network might have neurons that are trained to fire for things like pawn islands, doubled pawns, how close the King is to the center of the board, or how many squares a Bishop has available to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*-IYpuIzUm8gXv6Oq" /></figure><p>In a position like the image above, the neuron responsible for determining the quantity of pawn islands for white would output a value of 1, if we imagine an output of 0 indicating there are no pawn islands while an output of 1 corresponds to the maximum number of pawn islands possible (4 pawn islands)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*KHCi5Jt86Iii0tUE" /></figure><p>Meanwhile the neuron responsible for determining how close black’s King is to the center would output a value of 1, since it is as close to the center as possible, while the neuron responsible for determining white’s distance to the center would output a value closer to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*OvAHbvfb_yRbJecc" /></figure><p>Finally, the neuron responsible for determining the quantity of bishop moves would give an output close to 0, where 0 is no possible bishop moves, and 1 is the maximum possible number of bishop moves (It can cover a maximum of 13 squares at once)</p><p>Keep in mind that neurons can only output a scalar quantity, so all individual neurons must represent quantifiable values.</p><p>The next layer might have a neuron which combines information about pawn islands, doubled pawns, and passed pawns to give an evaluation for pawn structure. In this case, the weights for the passed pawn would likely be positive meaning it is good for the pawn structure, while the weights for the doubled pawns and pawn islands would likely be negative, since those features are bad for pawn structure. In our example, the outputs from the other neurons in the previous layer would have little to no impact on the pawn structure, therefore they are omitted from the illustration. This is rarely the case in real neural networks much more abstract connections</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*mNfw5FG2fvmabV2n" /></figure><p>Another neuron in the second layer might combine information about how many legal moves each piece has to give an evaluation of piece mobility. If you’re knowledgeable about chess you’ll know there are many more factors that go into pawn structure and piece mobility than mentioned, but this is simplified for those who aren’t so into chess, so hush :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/0*EvSLznpXsGv1i-pu" /></figure><p>In the third layer, a neuron might determine King safety by combining information such as the total number of opponent’s pieces left on the board and the mobility of those pieces, and how close the King is to the center of the board. Finally, the final neuron takes the outputs from all the third layer neurons and gives us a single number as the static evaluation for the board position.</p><p>The basic idea is that each layer builds on information from the previous layer, forming more complex concepts as we move through the network. In a way, each of the aspects we covered here form the basis for how a traditional chess engine works. Traditional chess engines are preprogrammed to recognize aspects of a position like piece development, king safety, and pawn structure, which help it provide a static evaluation of a position. These are known as heuristics.</p><p>Before the introduction of self learning AI to the chess community, these heuristics were designed and constantly tweaked by grandmasters to improve an engine’s performance. In a neural network evaluation, the network is able to get an intuitive feel of the evaluation based on similar past positions it has seen before, much like a human would.</p><p>In a way, the hidden layers create their own set of heuristics, and in the process, maybe come up with new heuristics that human grandmasters weren’t aware of. This is what gives neural networks more potential than traditional engines.</p><p>If you’d like to know how an engine uses its static evaluation function to determine what moves to make, be sure to stay tuned for my upcoming article on coding a chess engine using neural networks :)</p><p>The next big question is, how does a computer learn to make all these associations in the first place? After all, that’s at the core of what makes machine learning so powerful.</p><p>Here’s how it works.</p><p>A neural network is initialized with random weights and biases. So initially, when fed an position like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/0*8lXzb1z-GMAtiSHB" /></figure><p>The output would be completely random.</p><p>In essence, what happens next is we tell the neural network how close its answer was to a “correct” evaluation, and the network then adjusts its weights and biases so that the next time it encounters the same position its output would be closer to the desired output.</p><p>There’s actually a few ways to tell a neural network the “correct” output. One way is to collect original data through self-play, and seeing which positions lead to wins or losses, like AlphaZero. The other way is to use existing game databases. Another approach uses the end result of games from a game database to get a rough idea whether a position was good or bad (the assumption is that, especially at the higher levels, a good position for one color generally leads to a win for that color). Alternatively, we can compare the board evaluation from a trusted engine to train our network. We’ll be using this last method in our example, since it is the most intuitive one to grasp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*fKK0Xne6QF6Viqwg" /></figure><p>Back to our example. Imagine the neural network randomly decides that the position is -10 favouring black. Meanwhile, the Stockfish evaluation shows that in reality it is +4.5 in favour of white.</p><p>How far off the neural network is from the actual evaluation is represented in something called the <strong>cost function</strong>, where the difference between the desired and actual output are squared.</p><p>(4.5 — (-10))2 = 210.25</p><p>Squaring the difference places a much larger emphasis on big differences over small differences. This means if the neural network outputs a +2 instead of a +1, the network will be adjusted much less than if the network outputs a -10 instead of +4.5.</p><p>After determining the value of the cost function, the neural network will figure out a list of adjustments it needs to make to its weights and biases through a process known as backpropagation.</p><p>I’ll give a quick summary, but if anything’s unclear, feel free to dive deeper on your own.</p><p>There are three ways to adjust the output of this final evaluation neuron: Adjusting the biases, weights, and outputs of previous neurons</p><p>We only need to focus on the second to last layer for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/0*qllQBCXhNOAEZtYq" /></figure><p>Before we go on, I want to clarify that when I say “increase”, I mean making a number more positive, while “decrease” means to make a number more negative.</p><p>First, let’s cover the bias. This one’s pretty simple. Since we want the output to be more positive, we increase the value of the bias for the final neuron. This means a greater weighted sum which leads to a greater output value.</p><p>Next, let’s take a look at the weights. In this example, our output was too negative, we want to make all weights more negative. However, what’s important to notice is that the weights connected to greater output values (like this one with an output of 1.0), have a much greater impact than weights that are connected to neurons that barely fired (the ones with values close to 0). To maximize effectiveness, we want to focus more on changing the weights that are connected to neurons with greater outputs.</p><p>In this case, the weights connected to these neurons would be increased the most.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/0*pHXolq2oOVLLN7ax" /></figure><p>Finally, we have the outputs of the previous layer. Similar to how we changed the weights, we want to maximize effectiveness by focusing on the outputs that are weighted most heavily more than the ones connected to the final neuron by lighter weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*mFpJSm1fFgnQi1-V" /></figure><p>However, we can’t change their outputs directly, so what do we do?</p><p>We modify the weights and biases of the previous layer! Using the list of desired changes we want to make to the second last layer (L-1), we can adjust the weights and biases linked to each of these neurons just like we did for the output layer. For the L-1 layer, instead of just accounting for the one neuron like the evaluation neuron, we want to repeat this process for every single neuron in the L-1 layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MjvHgtK_qWBPq_vk" /></figure><p>As you can see, each neuron in the L-1 layer wants the outputs in the previous layer to be changed in a different way, so the way we determine the final desired change for each neuron in the L-2 layer is to sum up all the desired changes.</p><p>The changes desired by neurons that require larger changes (the neurons with output values of 0.1 and 0.8 in the previous diagram) will have a larger influence than the other neurons.</p><p>We keep doing this for each layer until we propagate back towards the beginning of the neural network. Hence the term, “backpropagation”. We won’t be going into the math behind this, but the oversimplified version is that we use math to find the minimum of the cost function, where the variables of the cost function are all the weights and biases of the neural network. For anyone familiar with functions, that means at least tens of thousands of variables!</p><p>And of course, we can’t forget that all of this is just for a single position. Now, the same process is repeated for the rest of the positions in the training set, with each position nudging the network to make different changes to its weights and biases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ry8WUPcu3nuKBNWW" /></figure><p>Finally, the average change suggested for each weight is applied, leaving us with a better neural network. This process is repeated until the neural network reaches a desired level of performance, or can no longer improve due to limited data or network complexity</p><p>To recap:</p><ul><li>Each layer of the neural network builds on the previous layer, increasing the complexity of concepts each neuron is responsible for as we move closer toward the output.</li><li>During the training process, a neural network compares its output to the correct output, and creates a list of changes required for its weights and biases to try and get its output to be closer to the correct value.</li><li>This process is repeated for each of the training examples/board positions, and the average change of for each weight and bias is applied to the network, leaving us with a better version.</li><li>Training continues until a network reaches a desired level or its performance stagnates due to lack of data or a limited number of neurons and layers.</li></ul><p>Now you know how a neural net-works :D</p><p>Before we reach the end of this article, I’d like to leave you with just a few thoughts on how intelligent game agents can be used in the future.</p><p>Imagine having a game where your AI companions can remember previous interactions and behave how you desire simply by receiving verbal instructions instead of having its behaviours linked to a fixed set of commands. What if the AI could even come up with and suggest its own ideas to you, much like how Meta’s Diplomacy AI suggested better moves to its human allies?</p><p>Maybe there’s a game that you feel like you’re no longer improving at, despite constant practice, and hours spent scrolling through forums searching for new strategy after strategy. If you’re not a professional gamer, chances are you don’t have a coach that has time to watch all your games and give reliable advice. However, a game agent that actually understood the game could play that role. It’d be able to analyze <em>all</em> of your gameplay and identify which changes you’d need to make to your gameplay to get the greatest return.</p><p>Another benefit of game agents is the speed at which they’d be able to playtest a game, since they could play many iterations in the time that a human could. All the balance issues and bugs would be discovered way before they started upsetting the gaming community.</p><p>Finally, we’d have intelligent companions or adversaries to play any game with, whether cooperative or competitive! No longer will there be an easy winning strategy like the ones that bug out hard coded AI. Nor will you have to worry about playing with friends who are too good or too bad for you when an AI can customize its level to give you the best experience possible. Wouldn’t that be amazing?</p><h3>Sources</h3><p>Neural networks (Amazing explanations!) <a href="https://www.3blue1brown.com/lessons/neural-networks">https://www.3blue1brown.com/lessons/neural-networks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e76e03124867" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>