<?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 Yuki Minai on Medium]]></title>
        <description><![CDATA[Stories by Yuki Minai on Medium]]></description>
        <link>https://medium.com/@ym1942?source=rss-2bd5bc0e2538------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EYq0oAJtZu5-VZ5tM_lpZw.jpeg</url>
            <title>Stories by Yuki Minai on Medium</title>
            <link>https://medium.com/@ym1942?source=rss-2bd5bc0e2538------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:46:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ym1942/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[Model-based methods to choose brain stimulation parameters based on prediction]]></title>
            <link>https://medium.com/@ym1942/model-based-methods-to-choose-brain-stimulation-parameters-based-on-prediction-39fd30f3cdbe?source=rss-2bd5bc0e2538------2</link>
            <guid isPermaLink="false">https://medium.com/p/39fd30f3cdbe</guid>
            <category><![CDATA[neurotechnology]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[brain]]></category>
            <category><![CDATA[control-theory]]></category>
            <category><![CDATA[dynamical-systems]]></category>
            <dc:creator><![CDATA[Yuki Minai]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 07:51:22 GMT</pubDate>
            <atom:updated>2026-11-16T07:51:22.536Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the third blog post in the series to provide an overview of the computational techniques used in closed-loop stimulation.</p><ul><li>First post: <a href="https://medium.com/@ym1942/computational-approaches-to-updating-stimulation-parameters-in-closed-loop-brain-stimulation-eca799c8ba0a">Computational approaches to updating stimulation parameters in closed-loop brain stimulation</a></li><li>Second post: <a href="https://medium.com/@ym1942/model-free-methods-for-prioritizing-the-brain-stimulation-parameter-space-in-a-smart-way-ff2b3826eee0">Model-free methods for prioritizing the brain stimulation parameter space in a smart way</a></li></ul><p><a href="https://medium.com/@ym1942/model-free-methods-for-prioritizing-the-brain-stimulation-parameter-space-in-a-smart-way-ff2b3826eee0">In the last post</a>, we discussed model-free methods for choosing stimulation parameters in a smarter way than random exploration, by introducing two example methods, evolutionary algorithms (EA) and Bayesian optimization (BO). Both work in a trial-and-error manner by testing a stimulation configuration, observing the brain’s response, and using that observation to select the next configuration to test. While they are relatively easy to implement and easy to interpret, they have two main limitations. First, they scale poorly, since as the number of stimulation parameters grows, the number of configurations we have to test before identifying an effective one grows very quickly. Second, they generalize poorly, since they rely on learning the direct stimulation-response relationship from the current subject’s observations, rather than learning the principles of how brain activity evolves and how the brain responds to stimulation, which might generalize across different subjects and setups.</p><p>In this blog, we discuss how the model-based methods try to address these limitations by training a dynamical model of how brain activity evolves and responds to stimulation. These methods first collect the training data to train such a model. Then the trained model is used to choose the stimulation configuration afterwards during closed-loop brain stimulation. We will discuss each of these steps in more detail, with a conceptual introduction and practical examples to build intuition.</p><h3>Overview of the model-based methods</h3><p>Model-based methods generally consist of two steps, training the model and using the predictions from the model to choose a stimulation configuration. There are many possible input-output designs of models, but in this blog, we consider a specific type of model that predicts the brain’s dynamics. In other words, we train a model to predict how brain activity evolves over time. This kind of dynamical model is particularly useful for closed-loop stimulation because it allows us to predict how the brain responds to given external inputs when the brain is currently in a certain state. This prediction then allows us to decide how to stimulate to induce a desired future brain state.</p><p>In the first step, we train this model. Specifically, the model we consider here takes two things as input, the brain’s current state and a stimulation input (for example, a stimulation amplitude and frequency), and predicts the brain’s future state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zi_OkF0jLMDWEvFJwZxEZg.png" /></figure><p>In the second step, for the brain state we want to reach, we leverage the trained model to find the stimulation configuration that gets us closest to it, for example by comparing the predictions for different configurations with the target. We will discuss several strategies for this in later sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8hwo8LlEvg1uMsr6_uedw.png" /></figure><p>There is one note before we move on. In practice, it is possible to start using a model that is not fully trained to choose a stimulation configuration during closed-loop stimulation, so the two steps do not have to be completely separate. In other words, while the model gets more training data and gets smarter, we can already use its predictions to guide the stimulation configuration selection. Even a not-fully trained model may provide more useful information than just randomly exploring different configurations. For simplicity of explanation and to build intuition, this post treats them as separate. We go through each step individually, covering the key considerations and some example studies.</p><h3>Step 1. Train the model</h3><p>Our goal in this step is to train a model that can accurately predict the brain activity dynamics. However, in many clinical setups or even research experimental setups, there is no time to collect a large dataset from one subject. So our goal becomes to do this using only a small amount of training data from the current subject.</p><p>Of course, one could try to focus on the data from the current subject and design the model architecture and training strategy to maximally leverage it. But in this blog, we would like to discuss the types of datasets we could use to address this challenge. People have recently started to leverage a pre-training approach using a wide range of datasets (across recording types, subjects, tasks, and more), and then fine-tune the model with the data from the current subject. To see why this approach can work, it helps to think of the training data as a pyramid. We start with a more intuitive example and then discuss the example more relevant to closed-loop stimulation.</p><p>Imagine we want to train a robot to perform a specific brain surgery and we don’t have much data (e.g., video recording of that specific surgery). We could try to teach everything needed for that task only from recordings of one surgeon doing that specific surgery, but that is the scarcest data we have. Instead, we can start with a larger amount of data on general arm and hand movements (bottom of the pyramid, general pre-training), then add a smaller amount of data on general surgery techniques (middle of the pyramid, fine-tuning), and further tune the model with a little data on the specific surgeon’s technique (top of the pyramid, few-shot adaptation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pemBCOeQYt4MUCBecMPCFA.png" /></figure><p>The key for this to work is that what is learned from the lower layers will be helpful for the tasks in the upper layers. In this example, we can intuitively imagine that learning how to move the arm and hand would be helpful general knowledge for the surgery robot before it starts learning more specific techniques. Similarly, learning general surgery techniques on top of the understanding of how to move the arm and hand in general would be helpful to learn specific surgery techniques for the target application. In other words, the model starts by learning general knowledge and transfers it to more specific applications using gradually smaller amounts of data.</p><p>While making sure the transferability of knowledge across layers is the most important takeaway here, there is another point I want to mention. If we already have enough data for the exact application (or from the current subject), we can skip the lower layers. Using all layers is not a requirement. Rather, we should start thinking from the top layer, and if we don’t have enough data for it, think about whether there are other datasets we can transfer knowledge from.</p><p>Now, the same pyramid for a task more relevant to closed-loop stimulation. Let’s say our task is to predict the change in local field potential (LFP) recorded with a deep brain stimulation (DBS) device that is induced by different combinations of stimulation amplitude and frequency in the target brain area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwh-3R-uTx-BnTZQBXARag.png" /></figure><p>At the bottom, we have LFP changes in other brain areas over time without stimulation. In the middle, we have LFP changes in other brain areas induced by different combinations of amplitude and frequency. At the top, we have LFP changes in the target brain area, induced by different combinations of amplitude and frequency. In this case, it is less obvious whether what is learned in the lower layers is helpful for the upper layers. This is still an open question we need to address empirically. Does learning how LFP changes over time without stimulation help predict the response to stimulation? Does the response to stimulation in other brain areas help us predict the response in the target area? These are the kinds of questions we need to ask when designing the training data collection strategy for the model used during closed-loop brain stimulation.</p><h4>Examples of learning shared representations across species, tasks, and recording modalities</h4><p>While there are many ways to design such a data pyramid for neuroscience applications, it helps to get intuition from some practical examples of what kinds of pyramid designs are possible. We discuss two recent studies that pre-train a predictive model on a wide variety of datasets. One caveat is that neither of them uses brain stimulation. Neither was on predicting stimulation responses, and there is not much work yet showing this kind of transfer with stimulation (as far as we know in Nov 2026). But learning the idea from the no-stimulation case helps us consider where transfer might be possible for the case with stimulation.</p><p><strong>Example 1. Transfer across species and tasks (Zhang et al. [1])</strong></p><p>In this study, the authors trained a model using cross-species and cross-task datasets for decoding speech from brain activity. They first pre-trained a neural network that receives spiking activity recorded with Utah arrays (small grids of electrodes implanted in the cortex) and outputs it as a compact summary of the recorded activity (i.e., an embedding of brain activity). The network was trained without anyone labeling the data, by hiding parts of the recording and asking the model to fill them in (i.e., self-supervised learning). The pre-training data had about 367 hours of recordings, roughly 98 hours from humans (speech and handwriting tasks) and about 269 hours from monkeys (reaching, grasping, and finger tasks). This may be akin to many scenarios where we can get larger datasets from monkeys than from humans (but it is not clear whether anything can be transferred between them). The pre-trained network was then fine-tuned to decode speech from the recorded spiking activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAYpsAktC1ylkU13Zg-XsQ.png" /><figcaption><em>Adapted from Zhang et al. [1].</em></figcaption></figure><p>By training this model, they tested whether pre-training a large neural network on many recordings gives a stable, shared description of the neural activity, which a new subject or a new task can then build on with less data. For example, what is learned from attempted speech and other motor tasks may help when data are scarce, such as imagined speech in their case.</p><p>They found that this is actually the case. On a standard speech decoding benchmark, the pre-trained model achieved a lower word error rate than the model without pre-training. This suggests that cross-subject datasets can improve the decoding performance for the current target subject by fine-tuning the model with a small amount of data. Interestingly, pre-training on human and monkey data together gave the best model. This suggests that cross-species and cross-task transfer is possible (although the authors noted that adding human data helped more than adding monkey data, which makes sense since the human data include tasks closer to speech tasks).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*IXtHHcP_dHO0HJ_4lnVDrA.png" /><figcaption><em>Adapted from Zhang et al. [1].</em></figcaption></figure><p>What can we learn from this study for closed-loop stimulation? This study shows that cross-species and cross-subject recordings could fill the lower layers of the pyramid. If transfer across species also holds for stimulation, we could run stimulation experiments in monkeys, exploring a wide range of parameters, to help predict the human brain’s responses without testing all of those configurations in people. I think this is a very interesting and important direction to advance model-based methods in closed-loop stimulation.</p><p><strong>Example 2. Transfer across recording modalities (Ferrante et al. [2])</strong></p><p>Now, let’s discuss another study. In this study, the authors mapped EEG, MEG and fMRI recordings into embeddings (numerical descriptions of the recordings) that line up with the embedding of the viewed image, so that recordings with the same (or similar) image end up close together across recording modalities. Each recording type captures the brain differently and may have only a limited amount of data, so the authors aimed to find a common description of the activity across modalities where what is learned from one type can help the others.</p><p>In their model architecture, each recording modality (EEG, MEG, fMRI) has its own network, which takes the activity recorded with that modality and projects it into an embedding space for brain activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPJ0DBqy9Xgf3RVvrj3lIw.png" /><figcaption><em>Adapted from Ferrante et al. [2].</em></figcaption></figure><p>Each network is trained on a separate public dataset, so the recordings are not from the same people. To relate the activity across recording modalities, the authors used the viewed image as an anchor. An existing image model (called CLIP) transforms each image shown to a participant into a numerical embedding of its content, which lives in its own embedding space, separate from the brain recordings. Each network is then trained so that its embedding of the brain activity ends up close to the embedding of the image the participant was viewing. In this way, the brain embedding space is aligned with the image embedding space. As a result, brain activity induced by similar visual images ends up close together in the brain embedding space across recording modalities, even though the recording types are not directly paired with each other. The aligned embeddings can then be used to decode (identify the image from brain activity), encode (identify the brain activity from the image), and convert activity between recording modalities.</p><p>They found that this works, at least as a proof of concept. Decoding the viewed image was well above chance for each recording type and comparable to previous methods trained on a single recording type. Converting between recording types also worked above chance, although there was no baseline to compare it with. However, the authors did not test whether training across recording types helps decoding or encoding compared with training on one recording type alone, so that benefit is still to be shown. Because each network saw different people, what is being aligned is shared structure across populations, not a direct mapping from one patient’s EEG to the same patient’s fMRI.</p><p>What can we learn from this study for closed-loop stimulation? By learning a common description across recording types, a stimulation model might be trained on data from one recording type and carry over to another. This raises a possibility that cheaper or more widely available recordings could help fill the lower layers of the pyramid, with only a little data from the current subject on top.</p><h4><strong>A note on model architecture</strong></h4><p>One thing to note is that while a good model architecture also helps this kind of transfer, the field in neuroscience (or more generally machine learning) has recently been learning that a large, flexible and expressive model, such as the transformers behind modern language models, can learn the structure from the data without strong assumptions built into the architecture. The high-level point is that with an expressive enough model and enough data, the model can learn the structure, which is why more and more cross-subject, cross-task and cross-modality brain foundation models use transformer-based architectures trained on a wide range of datasets. For this reason, we focus on the data in this post, but we might come back to the discussion around architecture in a future post.</p><h3>Step 2. Use the model to choose the stimulation configuration</h3><p>Once the model is trained, we want to use it to choose the stimulation configuration during a closed-loop brain stimulation experiment. <a href="https://medium.com/@ym1942/computational-approaches-to-updating-stimulation-parameters-in-closed-loop-brain-stimulation-eca799c8ba0a">In the first post of this series</a>, I introduced two example approaches: inverting a linear model and exhaustive search with a nonlinear model. Here we go through each in a bit more detail. For each approach, we first explain the high-level concept and then look at an example study.</p><h4>Approach 1. A linear dynamical system and control theory</h4><p>Let’s start by thinking about a simple linear model, a straight line. If we fit a straight line to some data, we can use it in two directions. Given an input x, we predict the output y. Or, given a specific output y we want, we solve the line equation backwards for the x that produces it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*R4XUF8WvYHBtg69hRTUVmg.png" /></figure><p>A similar concept applies to a linear dynamical system, a model in which the brain’s next state is a linear function of its current state and the stimulation input, as in the equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*hfHaPwSiUto3kdtdRmt1CQ.png" /></figure><p>Here, x is the brain state, u is the stimulation input, matrix A describes how the brain state evolves on its own, and matrix B describes how stimulation affects it. Following control theory, there is a closed-form solution for calculating the input needed to drive the system to a specified state (we don’t discuss the mathematical detail of this in this post). In other words, given the current brain state and the target brain state, we can calculate the optimal stimulation input directly in closed form, without testing many configurations.</p><p>As an example, we look at Yang et al. [3]. In this study, the authors modeled how stimulation changes the brain activity using a linear dynamical system model, and used the model to control brain activity toward a target state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XGw3h0LbBNdElC3242DJLg.png" /><figcaption><em>Adapted from Yang et al. [3].</em></figcaption></figure><p>They first trained a linear dynamical system model of how the brain’s activity evolves, using the brain’s responses to stimulation collected with various combinations of stimulation amplitude and frequency. During a closed-loop control experiment (on simulation), they estimated the brain’s current state from the recorded activity (using a method called a Kalman filter). Then they used a method from control theory called the Linear Quadratic Regulator (LQR) to find the amplitude and frequency that move the brain from its current state toward the target state. This method not only inverts the dynamical model but also lets us add constraints on the stimulation input, for example, to keep the amplitude and frequency within the ranges used in the experiments.</p><p>They showed that, in a simulated brain, the model-based controller (green) brought the brain state to the target and kept it there, while no stimulation (brown) and closed-loop control without a model of the brain’s response to stimulation (purple) left the state away from the target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*sz_5KW-WoNT5I1cWOuvnbA.png" /><figcaption><em>Adapted from Yang et al. [3].</em></figcaption></figure><p>What can we learn from this study for closed-loop stimulation? When using a linear dynamical system model, we can calculate the optimal stimulation input directly with control theory instead of testing many configurations through trial-and-error. This is a big difference from the model-free methods, where the methods have to learn everything through many trial-and-error.</p><h4>Approach 2. A nonlinear model and exhaustive search</h4><p>While the linear dynamical system model is proven to be useful in many neuroscience applications, we also know that the brain’s response to stimulation is not linear. This may motivate us to use a nonlinear model, such as a deep neural network, instead of a linear model. However, inverting a nonlinear model is often not straightforward. There is typically no closed-form solution to find the best input. One approach for this kind of nonlinear model is to use it to predict the responses to all candidate stimulation configurations, and then pick the configuration whose prediction is closest to the target.</p><p>This works because without testing every configuration on the brain, we can use the predicted responses to learn which ones are promising, unlike the model-free methods, where we actually had to test each stimulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*YAXfrostVw2yBVXc5Sqxog.png" /></figure><p>Our work, MiSO [4], is one example of this approach, in which the stimulation configurations are combinations of electrodes on a Utah array in the macaque prefrontal cortex and the model is a neural network (specifically a convolutional neural network, or CNN). First, we use the trained model to predict the response to every stimulation configuration (every possible pair of electrodes for stimulation in our experiment), and store the predictions in a look-up table (one row per configuration).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDY66clLg_j4STiOMMlZqQ.png" /></figure><p>Then we find the stimulation configuration whose predicted response is closest to the target activity state (i.e., the error is lowest), and test that stimulation configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5O07ZGrKm3wMEoNDdIw6w.png" /></figure><p>We observe the brain’s actual response and compare it with the predicted one, and the difference is the error. Finally, we update that row of the table based on the new observation and repeat the search for the configuration minimizing the error based on the predicted responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1VDY48-w59l-y8dM456dqg.png" /></figure><p>Note that the numbers in the images above are made up to illustrate the steps.</p><p>We found that this approach works well. In closed-loop experiments with electrical microstimulation in the macaque prefrontal cortex, guided by the CNN’s predictions, MiSO searched among thousands of stimulation configurations and drove neural activity toward specified target states.</p><p>What can we learn from this study for closed-loop stimulation? Again, this approach scales better to a larger parameter space than model-free search because the model’s predictions guide the stimulation configuration selection without testing all of them. Also, this opens up a possibility of integrating the non-linear model (such as a deep learning model and transformer) into a closed-loop brain stimulation framework. More work will be needed to explore how the integration of more expressive models can further improve the closed-loop control performance.</p><h4>Practical considerations in Step 2</h4><p>Before we conclude, I want to briefly mention two other questions that come up in closed-loop systems when thinking about the stimulation configuration selection strategy. The first is how much computation time we have. This is limited by the available resources, in both software and hardware. Depending on the available resources and the specific application, we need to think about how much time we have to decide a stimulation configuration, which guides the configuration selection strategy. The second is how fast the model should adapt. The brain state changes over time, so we want the model’s predictions to adapt to the current state of the brain, and a model that never updates could drift out of date. But if we update the model too quickly, it can forget the critical knowledge learned during model training. This is the stability versus plasticity tradeoff. Finding a good balance, and the hyperparameters that achieve it, is a key empirical question we need to answer when designing closed-loop stimulation methods.</p><h3>Summary</h3><p>To summarize, model-based methods consist of two steps. In Step 1, we train a model that predicts the brain’s response to stimulation, ideally from a small amount of data from the current subject. We discussed that one way to do this is to leverage a wide range of datasets that allow us to pre-train the model and transfer the knowledge across different subjects, tasks and modalities, and then fine-tune the pre-trained model using a small amount of data from the current subject. In Step 2, we use the model’s predictions to choose the stimulation configuration. We discussed two example approaches to do this, one using a linear dynamical system model and control theory and the other using a nonlinear model with exhaustive search over the predicted brain responses.</p><p>Compared with model-free methods, the main differences are that the model can provide brain response predictions to guide the configuration selection and it could also learn general principles transferable across different setups. Therefore, it has the potential to handle a large parameter space and carry knowledge across subjects, tasks or recordings, and its predictions guide us toward promising configurations without testing them all. The main limitations are that the model needs training data, which might add some extra data collection burden initially, and that relying on the model’s predictions means poor predictions can lead to poor control performance during a closed-loop stimulation experiment. Despite these limitations, I think this model-based approach is getting more attention as many large-scale datasets become available and the techniques for pre-training and fine-tuning advance.</p><p>In the last post of this series, we will discuss another way to frame closed-loop brain stimulation, based on reinforcement learning (RL). RL is not a completely distinct method. There is a lot of overlap with model-free and model-based methods. But this view provides a different way to think about closed-loop stimulation. Stay tuned!</p><h3>References</h3><ol><li>Zhang, Y., He, L., Fan, C., Liu, T., Yu, H., Le, T., Li, J., Linderman, S., Duncker, L., Willett, F., Mesgarani, N., Paninski, L. A cross-species neural foundation model for end-to-end speech decoding. ICLR 2026.</li><li>Ferrante, M., Boccato, T., Rashkov, G., Toschi, N. Towards neural foundation models for vision: aligning EEG, MEG, and fMRI representations for decoding, encoding, and modality conversion. Information Fusion, 2026.</li><li>Yang, Y., Qiao, S., Sani, O. G., Sedillo, J. I., Ferrentino, B., Pesaran, B., Shanechi, M. M. Modelling and prediction of the dynamic responses of large-scale brain networks during direct electrical stimulation. Nature Biomedical Engineering, 2021.</li><li>Minai, Y., Soldado-Magraner, J., Smith, M. A., Yu, B. M. MiSO: Optimizing brain stimulation to create neural population activity states. NeurIPS 2024.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39fd30f3cdbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model-free methods for prioritizing the brain stimulation parameter space in a smart way]]></title>
            <link>https://medium.com/@ym1942/model-free-methods-for-prioritizing-the-brain-stimulation-parameter-space-in-a-smart-way-ff2b3826eee0?source=rss-2bd5bc0e2538------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff2b3826eee0</guid>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[evolutionary-algorithms]]></category>
            <category><![CDATA[bayesian-optimization]]></category>
            <category><![CDATA[neurotechnology]]></category>
            <category><![CDATA[brain]]></category>
            <dc:creator><![CDATA[Yuki Minai]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 06:54:15 GMT</pubDate>
            <atom:updated>2026-11-01T07:02:05.073Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@ym1942/computational-approaches-to-updating-stimulation-parameters-in-closed-loop-brain-stimulation-eca799c8ba0a">In the first post of this series</a>, we reviewed three broad approaches for updating stimulation parameters over time, model-free methods, model-based methods, and reinforcement learning. This post focuses on the first of those, model-free methods. In the first post, we called these methods model-free because they do not use any explicit model of the brain. These methods search for stimulation configurations that can induce our desired brain state, through trial and error.</p><p>In this post, we will use one running example throughout: a simple two-knob parameter search problem. We will then look at one real paper for each of the two model-free methods introduced in the first post, evolutionary algorithms and bayesian optimization. The first study optimizes electrical stimulation to induce a target activity pattern in neurons in a mouse’s visual cortex. The second study tunes deep brain stimulation parameters in a computational model of Parkinson’s disease.</p><h3>A running example: tuning amplitude and frequency for maximizing coherence</h3><p>Here is the running example we will use throughout this post. Our goal in this example is to increase coherence, how synchronized the activity of two brain regions is, by tuning the two stimulation parameters, stimulation amplitude and frequency. We won’t get into how coherence itself is measured here. It is simply a one dimensional target value we are trying to maximize, and you can swap in whatever measurement matters most for your own application, or think of it as minimizing that measurement instead by just flipping the sign. The figure below shows the true relationship between amplitude, frequency, and the resulting coherence, which is unknown to us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sH_2JDWF3LPjXCAYrisibQ.png" /></figure><p>Within this landscape, there is a best combination of amplitude and frequency (black triangle) maximizing the coherence and our goal is to identify this combination by testing different combinations and learning through trial and error.</p><p>Notice the second, smaller bump in the bottom left corner. This is a locally optimal configuration. It looks promising relative to many other configurations, but it is not the globally best configuration available. A good search strategy needs to be able to avoid this kind of locally optimal configuration as much as possible and find the globally optimal configuration.</p><h4>The naive strategy of random search</h4><p>How can we identify the best combination of the amplitude and frequency through trial and error to maximize the coherence? The naive strategy, as we discussed in the first post as well, is to just randomly explore this space and find the best configuration identified through that exploration. The dots in the figure below show the combinations of amplitude and frequency tested by some random exploration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XnaQFNo7UDZBfQspJ1OKQ.png" /></figure><p>While this strategy might work if we are lucky enough to randomly hit the globally best combination, this is not a very efficient strategy. This is because it tests many non-effective combinations due to the random nature of the exploration. Model-free methods give us a smarter way to prioritize and search this parameter space. Instead of trying configurations at random, they use their own strategy to prioritize which configurations to test next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXsEyQ5qHrSh6kZuortWSg.png" /></figure><h3>Evolutionary algorithm: keep what works, mutate it, repeat</h3><p>The first strategy we discuss is the evolutionary algorithm. This algorithm first tests a few randomly generated configurations. Then, it evaluates how well each configuration worked. It then keeps whichever one worked best, and generates new candidates by perturbing it slightly. The method repeats this cycle of testing, finding the best one, and mutating it, to find the best configuration. The figures below show this using our running example.</p><p>It first tested five randomly selected pairs of amplitude and frequency (dots) and identified the best combination so far (red dot).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m57aaoyDLf3diw8UmlAF5A.png" /></figure><p>Once we have a best so far, the algorithm next generates five new candidates around the best one (gray dots, figure below), by adding small random perturbations in amplitude and frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8qtU7mYhM8MaLQMqqN3OQ.png" /></figure><p>Whichever of those new candidates worked best becomes the new best so far, and the cycle repeats. Mutate around it, test the results, keep the best combination. Across a few generations like this, the best configuration so far (hopefully) moves toward the optimal combination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i24yMq_M6IsWxgU4142-ZQ.png" /></figure><h4>An evolutionary algorithm inspired method to induce the target brain state in mouse V1</h4><p>Now, we will discuss a more concrete neuroscience example using the method related to this evolutionary algorithm. Tafazoli et al. [1] developed a method to drive neurons in a mouse’s visual cortex toward a target activity pattern, using multi-site electrical stimulation. Although the authors do not call it an evolutionary algorithm, their method works in a similar way to the evolutionary algorithm we just walked through.</p><p><strong>Method overview</strong></p><p>The goal of this study was to drive the activity of a population of neurons in mouse visual cortex, V1, toward a target activity pattern, using multi-electrode electrical stimulation. The authors recorded from V1 with a multi-site electrode array in nine awake mice, while stimulating through multiple independent electrode sites. At a high level, the algorithm works like this.</p><ol><li>Generate a single random stimulation configuration (different amplitude configurations for each electrode)</li><li>Add Gaussian noise to generate a new set of candidate configurations</li><li>Test each candidate configuration multiple times</li><li>Evaluate each candidate by computing its average response</li><li>Repeat steps 2 through 4 until time runs out, keeping the best configuration found so far to generate the next candidates</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*fAxVrVsyBENQcLicgiQcqg.png" /><figcaption><em>Adapted from Tafazoli et al., 2020, Fig. 1E.</em></figcaption></figure><p>One key addition the authors made to the basic evolutionary algorithm is to expand or shrink the amount of noise added in step 2 over time. When the best configuration did not change from the last generation, it shrinks the noise to exploit the current best more precisely. When the best configuration did change from the last generation, it expands the noise to explore more broadly.</p><p><strong>Results</strong></p><p>The target activity pattern was defined from real visual responses in the same animal. Using this method, the error between the stimulation evoked response and the target reduced over time, approaching the noise floor, the natural trial to trial variability even for the exact same stimulation (see figure below for a more detailed description).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*faCfcpJNJTwP89JxHqdWWA.png" /><figcaption><em>Adapted from Tafazoli et al., 2020, Fig. 4G and H.</em></figcaption></figure><p>Across many runs in multiple mice, this method reduced the error and successfully induced the desired brain state set by the experimenter, by optimizing the amplitudes for multi-electrode electrical stimulation. This is a very exciting application of the model-free closed-loop stimulation methods!</p><p><strong>Key hyperparameters</strong></p><p>There are two hyperparameters that are important for getting this to work: how many new candidates are tested per generation, and how many repeated trials each one gets. Together, these trade off how much of the space is covered each generation against how reliable assessment of each configuration is. The paper used 5 to 10 new configurations with 3 to 5 repetitions each. Unlike typical hyperparameter tuning in machine learning work, these choices cannot be easily tuned by running many experiments, since time with a real animal is limited and cannot be extended the way computational resources can. Tuning these kinds of hyperparameters is, I think, still the big challenge to make this kind of closed-loop stimulation framework work in real neuroscience applications.</p><p><strong>Limitations</strong></p><p>One limitation of the evolutionary algorithm is the dependency on initialization. While this paper mitigates this limitation by introducing the noise expansion and shrinking term, this method still depends somewhat on where the search starts, especially as the parameter space grows larger.</p><p>An evolutionary algorithm based approach is also typically subject specific. Each new animal, or each new target, starts the search from scratch, with no knowledge carried over.</p><p>Finally, the method generally forgets the best configuration found in the past. The current best is overwritten as the search continues, so a good solution, which worked before, may need to be rediscovered later.</p><h3>Bayesian optimization: explore promising and uncertain areas</h3><p>Now, let’s discuss another popular model-free method, Bayesian optimization. We will again start by discussing an overview of this method using the running example, identifying the best combination of amplitude and frequency to maximize the coherence.</p><p>Unlike the evolutionary algorithm, which only keeps track of the best configuration so far, bayesian optimization, or BO, trains a running statistical model of the entire landscape from every point it has tried so far. This kind of predictive model is often called a surrogate model, since it stands in for the true landscape we cannot observe directly. As the surrogate model, people often use a Gaussian process, or GP. A GP is a common choice because, in addition to predicting a value at every untested combination, it also gives an estimate of how uncertain that prediction is, in closed form. Other probabilistic predictive models are possible too, but this built-in uncertainty estimate is what makes a GP especially suitable for use in BO.</p><p>The figure below shows a concrete example. Uisng the initially tested three combinations (three dots on the right panel), BO generates the predicted landscape by fitting the GP model (predicted landscape on the right panel).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6N4XdWd73QXfmbfuaz1AVQ.png" /></figure><p>By using the fitted GP model, we can find not only the promising area (red dashed circle in the figure below) but also the area with high uncertainty in our knowledge or prediction (gray dashed circle in the figure below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipiaZbqIZ8asGJJVH9OKtA.png" /></figure><p>Combining this information, the promising and uncertain areas, the next combination of amplitude and frequency BO tests is chosen by something called an acquisition function. This is an equation that scores every candidate point by combining its predicted value and its uncertainty, and the point with the highest score is tested next. There are several variations in the acquisition function, such as expected improvement, probability of improvement, and upper confidence bound. Depending on which acquisition function is used, it can choose a point because it looks promising, because it is highly uncertain, or because it offers a reasonable balance of both.</p><p>The newly observed sample is then used to update the GP model prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHm75VIoxggXiWRCTUcSdg.png" /></figure><p>Repeating this cycle, testing a configuration, updating the prediction, scoring candidates, and choosing the next configuration, enough times lets the model’s prediction converge on the true landscape. Uncertainty shrinks everywhere it has looked, and the promising region homes in on the real peak as it learns the true landscape. Unlike the evolutionary algorithm, BO does not forget what it learned from the previous data. Every point, good or bad, sharpens the prediction and the next parameter selection.</p><h4>A Bayesian optimization method for identifying the best DBS configuration</h4><p>Now let’s look into a concrete example in neuroscience using BO. Grado et al. [2] used Bayesian optimization to tune deep brain stimulation parameters for Parkinson’s disease, in a computational model of the basal ganglia and thalamocortical circuit. The goal was to reduce beta band power, a signal known to be associated with Parkinson’s motor symptoms.</p><p><strong>Method overview</strong></p><p>At a high level, the algorithm works like this.</p><ol><li>Test an initial stimulation configuration and build a GP model using the observed neural activity</li><li>Use the prediction from the GP for each stimulation configuration to score candidate configurations with an acquisition function</li><li>Test the configuration with the highest score</li><li>Update the GP model with the new observation</li><li>Repeat steps 2 through 4</li></ol><p><strong>Results</strong></p><p>Their BO-based approach found a stimulation configuration that reduced beta power in the simulation. The figure below shows one example, searching over a single parameter, the beta frequency phase at which stimulation is triggered. The top panel shows BO’s surrogate model of beta power as a function of phase. We can see that the model’s uncertainty is low around the area already tested. Also, configurations with predicted low beta power are explored more often (around pi/2 to pi). The bottom panel shows beta power dropping across iterations as the search converges on a good phase value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*TP6R-CptPxrNlnTnmoYZKg.png" /><figcaption><em>Adapted from Grado et al., 2018.</em></figcaption></figure><p><strong>Key decisions</strong></p><p>There are a few important things to tune for this method, or for typical BO based approaches in general. The GP model needs a kernel, a rule for how similar/smooth two configurations are assumed to be, chosen to match the structure of the parameters. And different acquisition functions have different ways of balancing exploration and exploitation. These choices need to be made based on the objective or goal of each application, or based on the available time or resources.</p><p><strong>Limitations</strong></p><p>Bayesian optimization has a few general limitations worth keeping in mind. The Gaussian process model’s computational cost grows as O(n³) with the number of observations. This makes BO expensive to scale to a very large number of trials. It is also more difficult to extend traditional BO to discrete or categorical parameters, since the GP assumes a smooth relationship between nearby points in a continuous space, which breaks down for choices like which electrode contact or waveform shape to use.</p><h3>Summary</h3><p>Both studies show that model-free methods can find good stimulation configurations without using explicit models of the brain. The evolutionary algorithm inspired method reliably drove real neural activity toward a target pattern in mice. Bayesian optimization reliably found stimulation settings that reduced a disease related biomarker in simulation, using a few tested points along the way.</p><p>More generally, model-free methods like these are easy to implement and easy to interpret. But they tend to scale poorly, needing more and more samples as the parameter space grows larger. And they tend to generalize poorly, since they learn a direct relationship between stimulation and outcome rather than anything about the underlying brain dynamics, so little carries over from one target, patient, or condition to the next.</p><p>One way to address both of these limits is to train a prediction model of the brain’s response and use that model to guide the search, rather than searching from scratch every time. That is what model-based methods are built to do. We will look at an example of this approach in the next post.</p><h3>References</h3><p>[1] Tafazoli S, MacDowell CJ, Che Z, Letai KC, Steinhardt CR, Buschman TJ (2020). Learning to control the brain through adaptive closed-loop patterned stimulation. Journal of Neural Engineering 17: 056007.</p><p>[2] Grado LL, Johnson MD, Netoff TI (2018). Bayesian adaptive dual control of deep brain stimulation in a computational model of Parkinson’s disease. PLOS Computational Biology 14(12): e1006606.</p><h3>Links</h3><p>First post: <a href="https://medium.com/@ym1942/computational-approaches-to-updating-stimulation-parameters-in-closed-loop-brain-stimulation-eca799c8ba0a?postPublishedType=repub">Computational approaches to updating stimulation parameters in closed-loop brain stimulation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff2b3826eee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why controlling the brain is not like controlling a robot]]></title>
            <link>https://medium.com/@ym1942/why-controlling-the-brain-is-not-like-controlling-a-robot-1693d3aba7c0?source=rss-2bd5bc0e2538------2</link>
            <guid isPermaLink="false">https://medium.com/p/1693d3aba7c0</guid>
            <category><![CDATA[control-theory]]></category>
            <category><![CDATA[bci]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[brain-computer-interface]]></category>
            <category><![CDATA[neuroscience]]></category>
            <dc:creator><![CDATA[Yuki Minai]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 06:36:10 GMT</pubDate>
            <atom:updated>2026-09-16T06:36:10.726Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern robotics has made many control problems look solved. Reinforcement learning (RL) trains a humanoid to walk over rubble. Model predictive control lands a drone through a moving gap and a manipulator learns to fold laundry. None of this is trivial engineering, but the toolkit (e.g., model based control, RL, and state estimation) has become reliable enough to solve a wide range of control problems in robotics.</p><p>But I think that brain control has no such story yet. By brain control I mean changing brain state in a desired manner through some form of external perturbation such as electrical, magnetic, and optical stimulation, or even sensory input. There are many ways to perturb a brain, and I have spent years working on the development of methods to use such perturbation tools to control brain activity in a desired manner. More specifically, I explored a way to apply the control theory and reinforcement learning based approach to control brain activity using electrical stimulation. This kind of brain control problem is very important because there are many patients with brain disorders that are resistant to other kinds of treatments such as drug treatment and for them, changing brain activity directly using brain perturbation is often one of the few levers we have left. Getting good at brain control isn’t just an academic exercise. It has a huge potential to treat conditions that have resisted almost everything else health care providers can offer. And yet, it is still very rare to see the use of control theory or reinforcement learning based approach, which has been very successful in solving control problems in robotics, in the brain stimulation treatment. For example, deep brain stimulation for Parkinson’s, which is one of the leading clinical applications of brain stimulation, still runs largely open loop, tuned manually over months of clinic visits. Closed loop brain stimulation remains an active research problem. Brain computer interface (BCI) fields have made good progress on the use of ML driven approaches recently, but it is still far from the technology we see in robotics. Given this, the question that has stuck with me for years was why the same control and RL toolkit that works in robotics so effectively hasn’t done the same for the brain. It isn’t that neuroscience lacks sophisticated algorithms because we have a wide range of tools we can learn from other fields. But the challenges are that there are several unique aspects in brain control problems, which makes it difficult to directly apply the control theory/RL approaches to solve the brain control problem. In this post, I want to lay out my own view of what those challenges are and what we need to fill in the gaps to advance the field.</p><h3>Key components of a control problem</h3><p>To see where the gap and challenge are, it helps to break a control problem into its basic components rather than jump straight into our discussion. I think there are five key components that make up a control problem.</p><ol><li>A <strong>sensor</strong> lets you observe the state of a system we try to control.</li><li>An <strong>actuator</strong> lets you act on the system, giving you the ability to change its state.</li><li>A <strong>model</strong> predicts how the state will evolve, including how it will respond to a given action, and is what lets you decide which action to take.</li><li>A <strong>target state</strong> is the state you are trying to reach.</li><li>And <strong>a model update</strong> is the process of refining the model as new observations come in, so it stays accurate as you keep controlling the system.</li></ol><p>To apply control theory and RL approaches, ideally, the sensor would let us see everything about the state we care about. The actuator would let us push that state in any direction we need. The model would predict, with high accuracy, what the state will do next and how it will respond to our action. The target would tell us which state we are trying to reach. And the model update would let us correct and adapt our model whenever the system changes in some ways. Robotics gets close to this ideal in many settings, which is why control theory and RL work so well there. Brain control, as we’ll see, falls short of this ideal at almost every step.</p><h3>Example in robotics</h3><p>Let’s see what these five components look like with a four legged walking robot. Its sensors, small devices on its legs and body that sense tilt, speed, and the angle of each joint, tell it how it is positioned at every moment, the same way our own sense of balance and joint position tells us where our limbs are. Its motors at each joint let it push, straighten, or bend each leg with precision, the way our muscles let us move a joint as much as we intend. A physics simulator, or a model learned from many real practice runs, lets the robot predict what will happen next. If I push this leg this hard, I’ll end up in this position. The target state is whatever the task specifies, such as standing still, walking to a particular point, or holding a certain pose. And updating the model is mostly a minor correction, a bit of retraining, for example, as the robot’s joints age or the ground condition changes.</p><p>Good sensors mean the robot always accurately knows where it is. Good actuators mean that whatever the robot decides to do, it can do it. A good model means the robot can accurately predict the consequences of an action before taking it, instead of learning by crashing. And a clear target means there is no question about what counts as success. Robotics gets to build control systems on top of all of this being roughly true, which is a big part of why RL and control theory work so well there.</p><h3>Example in brain control</h3><p>Brain control has the same five pieces, conceptually, but each one falls far short of the robotics ideal above. Take electrical stimulation of the brain using electrodes as a concrete example. The sensor is whatever we can record from the brain, often just a handful of electrodes reading electrical activity from a small number of neurons among billions of neurons, which is nowhere near the complete position and speed picture the robot’s sensors give it. The actuator is often the same electrodes, now delivering current to the tissue nearby, a much less precise tool than a motor that moves one joint. The model is our best prediction of how the small number of neurons responds to stimulation and how that response relates to a person’s behavior, a prediction built mostly based on the limited previous observations. The target state is a healthier pattern of brain activity that we associate with healthy behavior, but unlike “stand here, walk to that point,” we don’t have a precise description of what that state looks like. And updating the model is not a minor correction because the brain, our target system of control itself, could dynamically change in response to our perturbation.</p><p>At a high level, the difference between the two examples is that in robotics, each of the five components is well defined, so control theory and RL mostly just need to solve the one piece left, deciding what to do. In brain control, none of the five components are very well defined or established, which is a big part of why simply importing a control algorithm from robotics doesn’t get you very far. On top of that, two more challenges sit outside any single piece. One is the hardware we are physically and legally allowed to use, and the other is how much data and experimentation we are able to collect with real brains. That gives seven challenges in total (one for each of the five components, plus the two additions introduced here), which the rest of this post walks through one at a time: what the idea looks like in robotics, what its counterpart looks like in the brain, and what the fundamental gap between them is.</p><h3>1. Limited observation (the sensor problem)</h3><p>This challenge comes down to a simple question. Can you tell what state a system is in, using only what you’re able to measure? A four legged robot’s sensors answer this almost completely. Together, they tell the robot, at every moment, where its body is, how fast it’s moving, and which way it’s tilted, the same complete picture you’d get if you could watch the whole robot from the outside.</p><p>Neural recordings typically offer nothing like this. For example, a Utah array implanted in the cortex might pick up spikes from something like a hundred or so neurons, out of the billions of neurons in the brain. Every recording method, whether it’s spikes, LFP, EEG, calcium imaging, or fMRI, ends up making a tradeoff. We can record from a small number of neurons with high precision, or from activity spread across the whole brain with much less precision, but not both at once. Even with a perfectly clean large-scale recording, getting an accurate estimate of the brain state we care about, such as a movement intention, a mood state, or a disease state, may still remain hard.</p><p>So there are two problems unique to brain control. There’s a raw sensing problem, whether we can record the relevant activity at all, and there is an inference problem, whether we can construct the state we care about from what we did record. In other words, brain control means constantly trying to infer the brain’s current state from observations that are often limited and indirect, which makes it difficult to apply control theory and RL, since both rely on knowing the current state accurately.</p><h3>2. Limited control (the actuator problem)</h3><p>The next problem is related to the actuator. Can the actuators push the system to any state we want? Our four legged robot’s motors, the same ones from the walking example, each move one joint and only that joint. Want the front left leg bent to a precise angle? Just drive that one motor. Every other joint stays where it was.</p><p>Brain stimulators run into the similar tradeoff sensing does. We have billions of neurons, but we can only directly influence a small number of them at once with the tools available today. Implanted electrodes can be fairly precise, reaching a small, specific group of neurons, but only a few hundred neurons at a time. Stimulating from outside the skull, for example with magnetic or electrical pulses on the scalp, reaches much more of the brain at once, but at the cost of precision. We end up affecting many neurons together rather than specifically designing which ones to affect. Either way, we don’t have anything like a robot’s motor, many independent knobs that reliably move one and only one piece of the system.</p><h3>3. Unknown dynamics (the model’s prediction problem)</h3><p>Physics gives robotics an enormous head start here. We understand how a solid object moves when you push it, the same equations that have held up for centuries. Physics simulators use those equations to accurately predict what a given push or motor command will do to a robot before it’s ever tried in the real world. That is what makes it possible to train a robot a large part in simulation.</p><p>Neuroscience doesn’t have anything close to this. We don’t have a complete dynamical model of the brain, one that can predict how brain activity evolves moment to moment or how it will respond to an external perturbation like stimulation. Building even a partial model, one that can predict the activity of a single brain region, is a challenging, ongoing area of research, not a tool we can simply take off the shelf. Because neurons are connected to each other, stimulating one part of the brain can produce effects in downstream areas that make predicting the dynamics even harder. In practice, researchers and clinicians learn what a given stimulation setting does mostly by trying it and observing what happens, through trial and error, rather than by predicting it ahead of time from an accurate brain’s dynamical model. Without a good dynamics model, we have to use less efficient approaches that learn purely from trial and error, in a setting where the amount of exploration allowed is often constrained (see challenge 7).</p><h3>4. Unknown control target (the target state problem)</h3><p>Robotic control usually gets its goal for free, whether that’s a waypoint, a force, or a trajectory, specified directly in the same variables the controller already works with. In brain control, for many of the outcomes we want (e.g., relieving depression, restoring a lost motor or sensory function, inducing a specific cognitive state), we often do not have a well understood neural target state.</p><p>A natural question here is why we don’t just skip targeting the neural state and use behavior itself as the target, since behavior is, after all, what we care about. In some cases we do that, and it works well. This typically works when the behavior can be measured moment to moment in a real time manner. However, for a target like depression, it isn’t. Mood, for example, is typically assessed with a questionnaire daily or weekly. That is too slow and too coarse to guide a stimulation system that needs to adjust from one moment to the next. In other words, we cannot get the feedback by trying different stimulation configurations in real time and we cannot easily tell which configuration causally affected the mood. What we want instead may be a neural signal that changes quickly but still reliably tracks that slow, hard to measure outcome. If we can find one, it lets us get fast feedback and update our stimulation in real time, even though the outcome we care about only becomes visible weeks later. Finding a neural signal like that, and confirming it really does track the outcome we care about, is still an open problem. And as the next section shows, this problem is even more challenging than it first looks, because the target we are aiming for does not necessarily hold still.</p><h3>5. Nonstationary dynamics (the model update problem)</h3><p>An environment a robot works in can change. The terrain shifts, an object gets knocked over, even the robot’s own actions rearrange the world around it. But the underlying physics never changes. The same equations that predicted how the robot would move yesterday still predict it today. Once you’ve identified the rules, they stay identified, so a model built once stays useful going forward, and updating it is a minor correction.</p><p>This does not hold for the brain, because the brain itself changes over time in response to our perturbation. How a given neuron responds to a given stimulation can change over time, potentially because of our own intervention. Synaptic connections strengthen or weaken, and the brain actively adapts to whatever we’re doing to it, sometimes even in ways that work against our intervention. A stimulation setting that helped a patient last month can lose its effect this month, not because anything outside changed, but because the brain itself learned to compensate. That is a different, and much harder, situation than a robot whose rules of physics hold steady no matter what happens around it, and it’s one of the reasons defining a target state, which discussed in the last section, is so hard to pin down.</p><h3>6. Resource and hardware constraints (a constraint on every component)</h3><p>Robotics can treat compute, power, sensors, and actuators as engineering choices that scale with budget. A research robot arm can just be plugged into the wall and connected to a room full of powerful computers, and adding more sensors is usually just a matter of paying for them.</p><p>Brain stimulation devices don’t get that freedom. An implant has to fit inside the skull or under the skin, run for years on a battery not much bigger than a coin, avoid generating enough heat to damage tissue, and send data over a wireless link with very little bandwidth. Even non-invasive tools, like external stimulators or wearable devices that avoid surgery entirely, still have to meet strict safety limits on how much energy they can deliver to a person, and every device has to clear a lengthy regulatory and safety approval process that a lab robot does not have to face. Today’s hardware and regulatory limits sit far below what the software itself would otherwise be capable of.</p><h3>7. Limited data and exploration (a constraint on every component)</h3><p>Challenge 6 was about the constraints on hardware. This one is about the constraints on data/experience we could obtain using the hardware. Robotics can run millions of exploration trials in simulation, allowing a robot to learn from failure. If hardware breaks, simply repair or replace it. On the other hand, brain control usually has only a small number of human subjects to work with, each one different from the others, under limits on stimulation set tightly by safety, ethics, and regulatory oversight. We cannot push a person’s brain into a bad state just to find out where the boundary is. And unlike a robot, we can’t reset a patient: there is no way to erase the effects of one stimulation session and put the brain back to an identical starting point before trying a different setting, the way you would reset a simulation to try a new strategy from scratch. This limits the amount of data we could collect for brain control to use the control theory and RL driven approaches.</p><h3>What would close the gap?</h3><p>None of this means brain control is hopeless, or that control theory and RL have nothing to offer neuroscience. Rather, laying out this way tells us what’s missing. Closing the sensor gap needs recording technology that is large scale and high resolution enough to make the relevant brain state observable. Closing the actuator gap needs stimulation that can be precise and selective control input. Closing the model’s prediction gap needs dynamical models of brain activity, and of how stimulation changes that activity. Closing the target gap needs a deeper, more mechanistic understanding of specific disorders and behaviors, so a target neural state is grounded based on our understanding of the brain. Closing the model update gap needs control methods built to adapt to a system that is itself changing and reacting. Closing the hardware gap needs continued device development, together with regulatory and clinical paths to deploy it. And closing the data gap needs large scale, standardized data collected across many subjects, so the field can learn across people and studies instead of starting over each time.</p><p>Note that these are the advancements we might want if we tried to follow robotics’ path. I’m not fully convinced that is exactly the path neuroscience will take. We may end up inventing our own techniques, built specifically around the neural data and tools we have, and around the regulatory and safety constraints that are unique to working with a human brain, rather than simply imitating robotics’ solutions. But it’s still worth learning from robotics and other related fields, even though we can’t just take their tools and apply them to neuroscience as they are today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1693d3aba7c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computational approaches to updating stimulation parameters in closed-loop brain stimulation]]></title>
            <link>https://medium.com/@ym1942/computational-approaches-to-updating-stimulation-parameters-in-closed-loop-brain-stimulation-eca799c8ba0a?source=rss-2bd5bc0e2538------2</link>
            <guid isPermaLink="false">https://medium.com/p/eca799c8ba0a</guid>
            <category><![CDATA[neurotechnology]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[brain]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[control-theory]]></category>
            <dc:creator><![CDATA[Yuki Minai]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 05:47:43 GMT</pubDate>
            <atom:updated>2026-11-01T07:01:11.580Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been working on the development of closed-loop brain stimulation technology for years, with a particular focus on identifying stimulation configurations that can induce a desired brain state by exploring a large stimulation parameter space. Throughout this work, I have learned and tried various techniques, ranging from simple model-free approaches to reinforcement learning-based approaches. While I mostly focused on reinforcement learning-based approaches during my PhD, one of the most important things I learned was that there is no single method that is always the best choice. To me, closed-loop stimulation is less about developing the most sophisticated algorithm and more about understanding the problem we are trying to solve, the assumptions we can reasonably make, and the tradeoffs we need to handle. Once we understand these things, we can choose the computational tools that are most appropriate for the application.</p><p>But I feel that there is relatively little introductory material that explains these choices from an intuitive perspective. In this series, I want to share my personal overview of the computational techniques used in closed-loop stimulation, with a particular focus on the differences between techniques and when to use which technique. The goal is not to provide a comprehensive technical explanation of each method. Instead, I want to provide intuition about the differences between the approaches and the tradeoffs involved. These days, implementing many of these methods has become much more accessible. With AI coding tools, it is becoming much easier to turn an algorithmic idea into working code. This makes conceptual understanding even more important. My hope is that researchers and clinicians can develop enough intuition about these methods to recognize when they might be useful and then explore their implementation with the help of existing software and AI tools.</p><h3>Ideal scenario vs real scenario</h3><p>I want to start our discussion by thinking about why we need closed-loop brain stimulation, and when it actually helps. Imagine a world where two things are true. First, brain responses induced by stimulation have no variance. The same stimulation configuration always produces exactly the same brain response, every time. Second, we already know the mapping between stimulation and its effect on the brain well enough to know, for any brain state we care about, which stimulation configuration would move us toward it. In that world, there is nothing to learn. We observe the brain activity, find the stimulation that moves it toward the desired state, apply it, and we are done.</p><p>That is not the world we live in. The effect of stimulation varies from trial to trial, even when we repeat the exact same stimulation configuration, for example, because of the difference in the pre-stimulation brain state. And for many brain states we would like to induce, we do not know the mapping between different stimulation configurations and their effects well enough to know which configuration to apply. Under this real-world scenario, how can we find and apply the stimulation configuration that induces our desired brain state? That gap, between wanting to induce a particular brain state and not knowing how, is the challenge we want to think about through this blog series.</p><h3>What is closed-loop brain stimulation?</h3><p>In this blog, I define a closed-loop brain stimulation system as a system that adaptively <strong>learns</strong> and <strong>updates</strong> the stimulation parameters over time to induce a desired brain state. In other words, the question the system tries to solve is “How can we adaptively learn and update the stimulation parameters needed to induce a desired brain state?”</p><p>There are two different timescales in a closed-loop system. The first is <strong>short-term updating</strong>. Given what we currently know, the system decides and updates the stimulation configuration to apply. This is the fast, moment-to-moment parameter updating. The second is <strong>long-term learning</strong>. The system uses the observations obtained by testing different stimulation configurations over time to improve its knowledge, so it gets better at identifying which stimulation configuration will move the brain toward the state we want. This is the slow, gradual learning over time. What we learn over time will guide our strategy for moment-to-moment parameter updating.</p><h3>aDBS for Parkinson’s disease as an example of closed-loop brain stimulation</h3><p>Let’s now look at an example of a closed-loop brain stimulation system, to see how the two timescales introduced above show up in an actual application. Adaptive deep brain stimulation, or aDBS, for Parkinson’s disease is an example of a closed-loop brain stimulation system already used in clinical practice today, and it is a good place to see the two timescales in action.</p><p>In Parkinson’s disease, beta-band power in the local field potential recorded from the subthalamic nucleus (STN) and the globus pallidus internus (GPi) is associated with motor symptoms. It is also well known that increasing the stimulation amplitude of deep brain stimulation suppresses this beta power, along with the associated symptoms.</p><p>Because that relationship is already well understood, we can write down a simple rule to update the stimulation parameters in real time. When beta power rises above some threshold (i.e., disease state), increase the stimulation amplitude. When it falls below another threshold (i.e., healthy state), decrease it. The device runs this rule continuously, reacting to moment-to-moment fluctuations in brain activity. This is the short-term parameter update in this closed-loop brain stimulation system, and it is feasible as a clinical application because, as a field, we have accumulated the knowledge of how to stimulate (i.e., how to change the stimulation current amplitude) to move the brain state in a desired way (i.e., to reduce beta-band power).</p><p>Is there a long-term learning component involved in this aDBS application? Yes. The long-term part is handled by a physician. During clinical visits, the physician looks at how the patient has been doing and adjusts the beta power threshold and the allowed range of stimulation amplitudes. Over time, the physician is doing the learning, accumulating experience about this particular patient and updating the rule to improve the outcome of the treatment.</p><p>This is a rule-based, human-driven (or human-in-the-loop) brain stimulation system, and it works well because we already know a great deal about Parkinson’s disease. We know the biomarker, we know how stimulation affects it, and the useful stimulation parameter space is small enough to tune manually. Both short-term updating and long-term learning can therefore be handled by a physician.</p><h3>The challenge of human-driven closed-loop brain stimulation</h3><p>Human-driven closed-loop brain stimulation is certainly an exciting direction we can continue to explore, for example by developing useful tools to help physicians make decisions. But this approach faces a challenge when our understanding of the target disorder or brain state is limited. While the approach above works well for Parkinson’s disease, there are many other brain disorders for which we do not yet know the underlying mechanisms, or how to stimulate to treat them. Even if we have a desired brain state we want to induce, we often do not know how to induce it. Unlike the Parkinson’s example, we do not yet know which stimulation configuration would actually produce that change. The relationship between stimulation and this target state is unknown, and it may be quite complex.</p><p>Without that knowledge, there is no obvious short-term parameter update rule we can define, because we do not know how stimulation affects the brain state. And there is no easy way for a person to learn the stimulation-response relationship over a handful of clinical visits either, unlike the way a physician could with the well-studied Parkinson’s biomarker. In the Parkinson’s case, learning is possible within a few visits because we already know which parameters are promising to tune and what the rule should focus on learning over time (i.e., the LFP power threshold and the stimulation current amplitude). But for other brain disorders, the relationship could be too complex, or the stimulation parameter space we could explore too large, to piece together manually.</p><p>Note that throughout this series, I am going to assume that we already know what to observe, meaning the target brain state, or biomarker, is given, for the sake of simplicity. Figuring out what to observe (or identifying a biomarker) is itself a hard problem and a topic for another day. Here I only want to focus on the question of how to find the right stimulation to induce the known desired brain state.</p><h3>Autonomous closed-loop brain stimulation to close the gap</h3><p>In the Parkinson’s example, a physician designed the short-term parameter update rule and learned, over time, how to tune it. What we will discuss in the following sections are autonomous approaches that perform both short-term updating and long-term learning without a person directly designing the rule or tracking the trend manually. These approaches have the potential to fill the gap we face today, building closed-loop stimulation systems that can work even for brain disorders we understand poorly or that can handle a complex stimulation parameter space. They also have the potential to further improve closed-loop brain stimulation therapies that are already available by making it more efficient.</p><p>Before jumping into those approaches, let’s briefly consider the naive way to choose stimulation parameters autonomously. The naive approach is to try different stimulation configurations at random and learn the mapping between stimulation configurations and the brain states they induce. Given an infinite amount of time, this approach might eventually reveal the best stimulation configuration for inducing our target brain state. In practice, though, it is too time-consuming and impractical. Every stimulation experiment on a real brain, in a real clinical setting, costs time, and we typically cannot afford more than a handful before we need a working stimulation configuration. In the following sections, I will introduce three main categories of autonomous closed-loop brain stimulation techniques that learn and construct stimulation parameter update rules in a smarter way.</p><h3>Prioritizing the stimulation parameter space in a smart way</h3><p>The first group of methods uses a smart strategy to prioritize stimulation configurations as we learn more about the relationship between stimulation and the induced brain state. Instead of trying configurations at random, these methods use their own strategies to focus exploration on the parts of the parameter space worth learning about, while minimizing time spent on less promising regions. Here, I will briefly introduce two methods in this category, Bayesian optimization and evolutionary algorithms.</p><p>Bayesian optimization, or BO, provides one way to make the stimulation parameter search more efficient by balancing exploration and exploitation. At a high level, BO prioritizes stimulation configurations that are likely to induce our target brain state, as well as configurations we know little about and are therefore uncertain about, since those uncertain configurations may include the best one, even though it has not yet been observed. Imagine that we have tested several configurations and observed how they affected the brain state. From these observations, BO builds an initial prediction of how different stimulation configurations are likely to affect the brain state, along with a sense of how uncertain we are about that prediction. BO then uses both pieces of information, the predicted response and the uncertainty of that prediction, to update the parameter choice from one trial to the next. More specifically, on some trials, BO chooses the configuration predicted to best induce the target brain state (this is called exploitation). But on other trials, BO instead tries configurations with high prediction uncertainty, to learn more about the relationship between stimulation and the induced response (this is called exploration). By testing both the best and the most uncertain configurations in this probabilistic fashion, and continually refining its predictions and uncertainty estimates, BO gradually learns to identify the most promising configurations for inducing the target brain state. BO typically explores more at the beginning, when its knowledge is still limited, and shifts toward exploitation later, as it becomes more confident in its predictions. With BO, the short-term update corresponds to the choice between exploration and exploitation on each trial, and the long-term learning corresponds to updating the prediction and its uncertainty over time.</p><p>Evolutionary algorithms take a different approach to the same problem. Instead of building an explicit prediction for responses induced by different configurations, an evolutionary algorithm shifts the search priority over time. It first tests a small number of randomly selected configurations. Then it keeps the ones that perform well, and generates new configurations by slightly varying those well-performing configurations. Repeating this process over many generations tends to push the parameter selection toward configurations that work well, without requiring an explicit prediction of the brain responses induced by different stimulation configurations. With evolutionary algorithms, the short-term update corresponds to testing the current generation of configurations, and the long-term learning corresponds to the mutation and selection process that generates new configurations from the well-performing ones.</p><p>Notice that both of these strategies can perform this search without requiring us to build a detailed model of how the brain itself works. They can therefore provide an algorithmic way to narrow down a large stimulation parameter space and prioritize a limited number of configurations, even when we have little prior knowledge about the brain circuit or the underlying brain mechanisms. Both simply learn the best configuration through trial and error, without any model of the brain. This is why these approaches are often called <strong>model-free</strong>. They do not use any explicit model of the brain.</p><h3>Incorporating knowledge about the brain through a model</h3><p>The model-free methods above do not use an explicit model of the brain. But if we already know something about how the brain behaves, it might be useful to incorporate that knowledge directly, through a model. This motivates model-based methods. Instead of learning only a direct relationship between stimulation and its outcome, we can try to learn how the brain itself evolves over time, treating stimulation as an input that drives that evolution. At a high level, model-based methods describe how the current state of the brain and the stimulation we apply together shape the brain’s next state. Instead of thinking only about stimulation → response, we now think about current brain state + stimulation → future brain state.</p><p>What does this change give us? It means the system can choose different stimulation configurations depending on the current state of the brain. For example, suppose two different brain states respond very differently to the same stimulation. A model that explicitly represents the brain state can capture this difference and choose different stimulation configurations for the two situations.</p><p>As a model of the brain, a common starting point is a relatively simple model, such as a linear dynamical model. This assumes that the relationship between the current state, stimulation, and future state can be approximated as a linear relationship. We know the brain is not truly linear, but linear approximations can still be useful in various neuroscience applications. This field of linear dynamical systems has a long history, particularly through control theory. One reason classical control methods based on linear dynamical models have been so influential is that, once we have identified the system dynamics, we can derive an analytical or closed-form solution for the control problem. Rather than repeatedly searching through many possible stimulation configurations, we can calculate the best stimulation configuration to induce our target brain state directly from the model. For this method, the short-term update corresponds to inverting the linear model, which then outputs the optimal stimulation configuration to apply. The long-term learning corresponds to updating this linear model itself, using the newly observed data. These days, nonlinear models such as recurrent neural networks, or RNNs, have also become popular for representing the brain’s dynamics.</p><p>Model-based approaches come with a different tradeoff than the model-free approaches above. Model-free methods make relatively few assumptions about how the brain works, making them easy to use. But because they also have less information about how the brain responds to different stimulation, they might require more data to find a good configuration. Model-based methods give us much more structure and allow us to use predictions about the brain, but those predictions are only useful if the model captures the relevant dynamics well enough. Making the wrong assumptions in the model could guide the closed-loop stimulation system inefficiently, taking a long time to find a good configuration.</p><h3>Reinforcement learning as another way to frame the problem</h3><p>So far, we have seen two different approaches to running closed-loop brain stimulation autonomously. Model-free approaches, such as Bayesian optimization and evolutionary algorithms, search directly for stimulation configurations that work, without assuming anything about how the brain produces its response. Model-based approaches, such as linear dynamical systems, use an explicit model of the brain’s dynamics to identify the best configuration. I would also like to introduce a third way to frame the closed-loop brain stimulation problem. It is called reinforcement learning. Rather than being a specific technique, I consider reinforcement learning, or RL, as a general framing. It starts by defining what good looks like, in the form of a reward, and lets the system learn a strategy that maximizes that reward over time.</p><p>How is RL conceptually different from the approaches above? The methods above are each built around a fairly specific problem, for example, searching a parameter space efficiently, or solving a control problem using a dynamical model. RL instead starts from a more general question. Given some objective, expressed as a reward, how should the system choose stimulation configurations over time to maximize it? Because this is a very flexible framework, it can incorporate both model-free and model-based versions of these approaches. This flexibility also makes it easy to incorporate various machine learning modeling and search techniques as they are developed. I think this is too high-level an introduction, so I will come back to this topic in a future blog with a more concrete example.</p><p>With RL, the short-term update means using the system’s current strategy, its best current guess at which stimulation to try given the brain’s state, to decide what to apply right now. The long-term learning means using the rewards received from past decisions to improve that strategy over time, so the system’s choices keep getting better with experience.</p><h3>So which approach is best?</h3><p>None of them, universally. The right choice depends on factors such as the knowledge we already have about the brain disorder, how much data or time we can afford to spend, and how large or small the stimulation parameter space of interest is.</p><p>A rule-based, human-driven closed-loop system is attractive when we already understand the relationship between the observed state and the appropriate stimulation. If a simple rule works, there is often little reason to use a more complicated method.</p><p>A model-free closed-loop system is attractive when the stimulation-response relationship is unknown, but we can experimentally evaluate candidate stimulation parameters within a reasonably well-defined space.</p><p>Model-based closed-loop control approaches become attractive when temporal dynamics matter and we can identify a useful model of those dynamics. If the system can be reasonably approximated by a model for which efficient analytical or numerical control methods exist, this can be a very powerful approach.</p><p>A reinforcement-learning-based approach becomes attractive when we want more flexibility in the objective, or in how we represent the relationship between brain state, stimulation, and outcome.</p><p>The more sophisticated method is not always the better method. A more complicated model may require much more data. A more flexible algorithm may require much more computation. This is why I think method selection should be driven by the problem rather than by the sophistication of the algorithm.</p><h3>Why hasn’t this reached the clinic yet?</h3><p>If autonomous closed-loop brain stimulation is promising, why don’t we see it more widely used in clinical practice today? A few reasons stand out to me.</p><ul><li><strong>We rarely have enough time or data.</strong> Real experiments on real brains, in real clinical settings, are expensive, and data is limited. We usually cannot afford to run more than a handful before we need a working stimulation configuration, which is exactly the situation these data-driven autonomous methods are least suited to.</li><li><strong>The tools available today are not built for this yet.</strong> Many stimulation devices only expose a limited set of adjustable parameters, and there is currently no clinically approved device built to run this kind of fully autonomous, data-driven closed loop.</li><li><strong>We do not always know what to observe.</strong> This whole framework assumes we already have a good biomarker to track. For many conditions and targets, that biomarker itself is still an open scientific question.</li></ul><p>In short, this field is still in its early stages. It will need to evolve alongside advances in hardware, devices, regulation, and the protocols needed to protect patient safety, among other things.</p><h3>Summary</h3><p>In this blog, I introduced closed-loop brain stimulation as a general computational problem, one of adaptively learning and updating stimulation parameters, over two different timescales, to induce a desired brain state. I walked through why this is hard when we do not already know the relationship between stimulation and its effect, using aDBS for Parkinson’s disease as an example of the easier case, where that relationship is well understood and both timescales can be handled by a person.</p><p>I then gave a high-level overview of three categories of autonomous approaches that can close this gap when our understanding is more limited. Model-free methods, such as Bayesian optimization and evolutionary algorithms, search directly for stimulation configurations that work well, without building any explicit model of the brain. Model-based methods, such as linear dynamical systems, build an explicit model of how the brain evolves in response to stimulation and use that model to choose the right stimulation configuration. Reinforcement learning offers a more general framing that can incorporate either strategy at a high level, learning a decision strategy that improves at achieving a defined objective over time. There is no universally best approach among these three. The right choice depends on each application.</p><p>In the next three posts, I plan to go deeper into each of these three categories with concrete examples of how each one actually works.</p><h3>Links</h3><p>Second post: <a href="https://medium.com/@ym1942/computational-approaches-to-updating-stimulation-parameters-in-closed-loop-brain-stimulation-eca799c8ba0a">Computational approaches to updating stimulation parameters in closed-loop brain stimulation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eca799c8ba0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Train RED with RL to create Wartortle(Part 3)]]></title>
            <link>https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-3-2055fad42d0d?source=rss-2bd5bc0e2538------2</link>
            <guid isPermaLink="false">https://medium.com/p/2055fad42d0d</guid>
            <category><![CDATA[q-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[pokémon]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Yuki Minai]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 13:48:37 GMT</pubDate>
            <atom:updated>2024-10-13T14:11:01.180Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog series, I aim to evolve Squirtle into Wartortle by teaching RED to earn experience through battles with wild Pokemon without fainting!</p><ul><li><a href="https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-1-0a87a35a9a65">Part 1: Teach to stay in grass area</a></li><li><a href="https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-2-954973f77fde">Part 2: Teach to walk around in grass area</a></li><li>Part 3: Teach how to heal Pokemon (This blog)</li></ul><p>In the previous blog, I trained RED using combined rewards to move around in the grass area (in grass reward + different location reward). While this approach encouraged RED to walk around the grass area, it didn’t teach him how to heal his Pokemon — a crucial step in evolving Wartortle. In this post, we’ll introduce a new reward to address this.</p><h4>Our goal</h4><p>Let’s first define our goal. The nearest place to heal Pokemon is RED’s house, where he can heal them by talking to his mother. Thus, we want to teach RED to visit his mom when Squirtle’s HP is low — but not at other times. To guide RED home, we can implement a reward that increases as he gets closer to the house. Here’s a summary of our reward design:</p><ul><li>Provide a larger reward as RED gets closer to his house</li><li>Apply this reward only when Squirtle’s HP is low</li></ul><h4>Distance based reward function</h4><p>To fulfill the first requirement, we’ll implement a distance-based reward function. The reward will increase as the distance between RED’s current location and his house decreases. One simple way to measure distance is by calculating the Manhattan distance between two points, defined mathematically as:</p><p>d = |x_red - x_house| + |y_red — y_house|</p><p>Her, x_red and y_red are RED’s current coordinates while x_house and y_house are his house coordinates. Since Pokemon Red uses a map ID system, we’ll need to adjust for different map offsets to calculate the distance between locations. We will see the code to do this in a minute.</p><h4>Low hp state</h4><p>As mentioned earlier, we only want to apply the distance-based reward when Squirtle’s HP is low. Pokemon Red stores HP values in memory, which allows us to identify Squirtle’s HP state. When in a low HP state, we want RED to prioritize going home, so we’ll disable the in-grass and different location rewards in a low HP state.</p><p>Here’s the implementation of the distance-based reward based on HP state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01ded6c0b5355331bdff369d2737f996/href">https://medium.com/media/01ded6c0b5355331bdff369d2737f996/href</a></iframe><p>In this code, we retrieve Squirtle’s HP at each step. If it falls below a certain threshold (eg., 10 hp), we consider the HP state to be low.</p><p>We have two different target locations, one is for RED’s house door and another is for RED’s mom location. They are needed because of the map design of Pokemon RED. Below is the part of the map of Pokemon RED.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dND5-xaTfYZXaRKrw-WQQ.png" /></figure><p>Below is the zoom-up version of the above image focusing on the related area for this project. Pallet town and route 1 are continued in the same image. Thus, after adjusting the offset based on map_id, we can simply use the manhattan distance between the current coordinate and the coordinate of the door to calculate the distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*zsBy6N34FQA7kGqxECbY8g.png" /></figure><p>However, RED’s house is represented in a separate image (Two left squares of the below image) so we cannot simply get the coordinate on this image to get the distance.</p><p>To address this, the above implementation changes the target depending on where RED is. When RED is in either pallet town or route 1, it gets a higher reward as it gets closer to RED’s house door. When RED is in his house, he gets a higher reward as it gets closer to his mom’s location.</p><h4>Train RED with distance based reward</h4><p>Let’s train RED using this new reward. The reward is now a combination of in-grass reward, different location reward, and distance based reward in the low HP state. The behavior we expect from RED is that he walks around the grass area when Squirtle’s HP is high but heads home when HP is low. Below are figures showing the learned values for each high HP and low HP state respectively.</p><p>High HP state</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8DX7Rlz74XEP3aIS7RnDcg.png" /></figure><p>Low HP state</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*expHhWoWh4fU-70BzFlyZQ.png" /></figure><p>RED learns different kinds of value functions between two states. In non-low_hp state, the learned value is similar to the one learned in the previous blog. In the low HP state, however, RED learns a value gradient from the grass area to his house.</p><h4>N-step look ahead Q-learning</h4><p>While this result is promising, there’s one more issue: after healing, RED needs to return to the grass to continue encountering wild Pokemon. How can we teach him this? One idea is to introduce another distance-based reward when Squirtle’s HP is high, targeting a location within the grass. However, this approach can be tricky — RED might learn to stay at the target location (where he can earn a max reward) without walking around the grass area. (Maybe this still works by very carefully tuning the reward value setting for each reward type.)</p><p>Instead, we’ll try Q-learning with longer look ahead time steps, specifically, taking into account 20 steps of rewards. So far, RED’s learning has been limited to immediate rewards and the value estimate of the next state, focusing on short-term outcomes. This approach made RED difficult to have a long term view. It mostly focuses on the actions leading to almost immediate reward. But if we see the learned value function above, we can notice that RED can expect a high reward in the grass area if it can properly make 15–20 movements in high HP state. By using Q-learning with 20 steps, we may help RED learn this longer-term strategy.</p><p>Compared to our previous Q-learning, our new Q-learning algorithm takes into account a longer sequence of future outcomes, allowing the agent to develop a more long-term view. It helps RED understand that certain actions might not give immediate rewards but lead to better outcomes in the longer term.</p><p>Here is the implementation of the new Q-learning. In our implementation, N=20.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4295e4e10d068fc7b3e0aa8dfd49f71/href">https://medium.com/media/d4295e4e10d068fc7b3e0aa8dfd49f71/href</a></iframe><p>Let’s train RED with this algorithm. Below are the learned values with 20 step look ahead Q-learning.</p><p>High HP state</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwjVn9MppopMp7zmMAPNog.png" /></figure><p>Low HP state</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TaTd3tEBtxSQhntooVlEA.png" /></figure><p>Now, RED learned the gradient of value toward a grass area to return to that region in high HP state. In other words, RED understood the value of returning to the grass area after healing. The behavior he learned can be summarized as follows:</p><ul><li><strong>Low HP</strong>: Head to RED’s mom to heal.</li><li><strong>High HP</strong>: Return to the grass, where rewards are higher due to grass and location rewards.</li></ul><p>Finally, below is a video of RED’s successful run :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8RQJYupAbPc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8RQJYupAbPc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8RQJYupAbPc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba921533a536e5de25670eea8976d91c/href">https://medium.com/media/ba921533a536e5de25670eea8976d91c/href</a></iframe><p>One last note I would like to share is that this method does not always succeed. To get this successful run, I had to run multiple simulations. There are various directions to improve this. For example, I noticed that after reaching 14–15 level, Squirtle becomes very strong compared to the wild Pokemons in this area, leading to a minimum HP loss but losing a lot of power points (i.e. the number of times a Pokemon can use a certain move like Tackle). This caused a problem because I implemented a code to keep pressing A during a battle. In many runs, RED got stuck selecting Tackle although there is no power point left. Future work, for example, can add power points into consideration to heal Pokemon.</p><h4>Summary</h4><p>In this series, I introduced how to use the Pokemon Red environment and reward design to train RED to evolve Squirtle into Wartortle. As we’ve seen, reward design is crucial in shaping an agent’s behavior, acting as the signal that guides its learning. In fact, I experimented with several other reward designs (such as battle_win reward and novel_state reward), each leading to different behaviors. It is very interesting to see how different reward design leads to a different kind of behavior.</p><p>I only used Q-learning in this series as a learning algorithm but the future step is of course to train RED with a more advanced algorithm. Stay tuned for future blog posts where I’ll explore these! Thanks for reading.</p><p><a href="https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-1-0a87a35a9a65">Part 1: Teach to stay in grass area</a></p><p><a href="https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-2-954973f77fde">Part 2: Teach to walk around in grass area</a></p><h4>Code</h4><p><a href="https://github.com/yuumii-san/RL_tutorial_notebook/tree/main/pokemon/create_wartortle">https://github.com/yuumii-san/RL_tutorial_notebook/tree/main/pokemon/create_wartortle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2055fad42d0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Train RED with RL to create Wartortle(Part 2)]]></title>
            <link>https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-2-954973f77fde?source=rss-2bd5bc0e2538------2</link>
            <guid isPermaLink="false">https://medium.com/p/954973f77fde</guid>
            <category><![CDATA[q-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[pokémon]]></category>
            <dc:creator><![CDATA[Yuki Minai]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 13:48:11 GMT</pubDate>
            <atom:updated>2024-10-13T14:10:18.288Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog series, my goal is to create a Wartortle by teaching RED to gain experience through battles with wild Pokemon without fainting!</p><ul><li><a href="https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-1-0a87a35a9a65">Part 1: Teach to stay in grass area</a></li><li>Part 2: Teach to walk around in grass area (This blog)</li><li><a href="https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-3-2055fad42d0d">Part 3: Teach how to heal Pokemon</a></li></ul><p>In the previous post, I trained RED by rewarding it for staying in the grass, which led to encounters with wild Pokemon. While this approach encouraged RED to stay in the grass, the problem was that sometimes RED learned to stay in the same spot, pressing A or B without moving. This isn&#39;t ideal since it doesn’t allow RED to encounter wild Pokemon. In this post, we’ll adjust the reward function to fix this issue.</p><h4>Define the state</h4><p>A straightforward solution is to reward RED for moving from one location to another (or penalize staying in the same spot). To do this, we need to store both the current and previous states and compare them. In Pokemon RED, RED’s location can be identified using the x-coordinate, y-coordinate, and map ID. Let’s define a state as {x}_{y}_{map_id}. Each town or road section has a unique map ID. For example, Pallet Town has a map ID of 0. Within each map section, the top-left corner is represented as [x, y] = [0, 0].</p><p>Here’s the code that shows how to get and define the state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/884f848acf4fc78d968aec3b14065668/href">https://medium.com/media/884f848acf4fc78d968aec3b14065668/href</a></iframe><h4>Different location reward</h4><p>Next, we’ll implement a code that tracks the previous state and compares it to the current state to assign different location rewards. The code below initializes the last_state variable within reset function. At each step, it checks the current state and compares it to last_state. If RED remains in the same location, it receives a negative reward (-0.5). If RED moves to a new location, it gets a positive reward (+0.5). The final reward is the sum of the in-grass reward (+1 in the example below) and the different location reward.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71e4aa8fa8e4d3c772c0ccf3f82eb8dc/href">https://medium.com/media/71e4aa8fa8e4d3c772c0ccf3f82eb8dc/href</a></iframe><p>Note that during battles, the state doesn’t change. But since RED cannot avoid this, no penalty is given for staying in the same spot during a battle. Another important consideration is that we only assign different location rewards or penalties while RED is in the grass. Otherwise, RED could earn positive rewards just by moving around in non-grass areas. This design encourages RED to stay in the grass, which yields higher rewards. In summary, our reward structure looks like this:</p><ul><li>RED is in the grass and moving around: Big reward (+1.5)</li><li>RED is in the grass but not moving: Small reward (+0.5)</li><li>RED is outside the grass: No reward (0)</li></ul><h4>Train RED</h4><p>Now, let’s train RED using the combination of in-grass rewards and different location rewards. Below are the learned best actions for each state and the corresponding state values. Red arrows correspond to high-value states, while blue arrows correspond to low-value states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*KV8whJyWwKu9-oNYYUhdzw.png" /></figure><p>RED learned a strategy of moving left and right within the grass area. This strategy is something I might do myself if I had to create Wartortle just by exploring this area. The additional reward for changing locations properly encouraged RED to move around within the grass and encounter wild Pokemon, so it is working well.</p><h4>Effect of Changing Reward Values</h4><p>While this reward design works, it would be interesting to explore how different reward values affect RED’s behavior.</p><p>Here is the value function learned when the in-grass reward is set to 0.1 and the different location reward is set to 1. I also applied different location rewards in non-grass areas for this experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*fiD5e0WS3VpyTWOCoETZVw.png" /></figure><p>With this setting, the best strategy is still to move around in the grass (+1.1), but RED can also earn large rewards in non-grass areas by moving around (+1). In fact, RED can earn more rewards in changing states in non-grass areas (+1) than in staying within the grass (+0.1), and thus, the learned value function assigned higher values to non-grass regions than previous example due to the increased different location rewards.</p><p>This experiment shows that reward value setting directly influences the agent’s behavior, so it’s important to carefully consider whether the reward structure supports the behavior we want RED to learn.</p><h4>Problem toward the next blog</h4><p>So, can RED trained with the combined rewards (in-grass reward + different location reward) create Wartortle? Maybe not yet. RED still hasn’t learned how to heal HP. To evolve Squirtle into Wartortle at level 16, RED needs to heal his Squirtle when its HP gets low. In the next (and final) post of this series, we’ll design a reward system to teach RED how to heal.</p><p><a href="https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-1-0a87a35a9a65">Part 1: Teach to stay in grass area</a></p><p><a href="https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-3-2055fad42d0d">Part 3: Teach how to heal Pokemon</a></p><h4>Code</h4><p><a href="https://github.com/yuumii-san/RL_tutorial_notebook/tree/main/pokemon/create_wartortle">https://github.com/yuumii-san/RL_tutorial_notebook/tree/main/pokemon/create_wartortle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=954973f77fde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Train RED with RL to create Wartortle(Part 1)]]></title>
            <link>https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-1-0a87a35a9a65?source=rss-2bd5bc0e2538------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a87a35a9a65</guid>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[q-learning]]></category>
            <dc:creator><![CDATA[Yuki Minai]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 13:47:36 GMT</pubDate>
            <atom:updated>2024-10-13T14:09:20.461Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@ym1942/create-a-gymnasium-custom-environment-part-2-1026b96dba69">previous blog</a>, I introduced how to create a custom Gymnasium environment using Pokemon RED as an example.</p><ul><li>Part 1: Teach to stay in grass area (This blog)</li><li><a href="https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-2-954973f77fde">Part 2: Teach to walk around in grass area</a></li><li><a href="https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-3-2055fad42d0d">Part 3: Teach how to heal Pokemon</a></li></ul><p>The video below shows RED taking 30 random steps using the Gymnasium framework.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkX_hQjFWqs4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkX_hQjFWqs4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkX_hQjFWqs4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b265f37804ccef93da82f820a2d4357/href">https://medium.com/media/9b265f37804ccef93da82f820a2d4357/href</a></iframe><p>This pokemon gym environment is a fun and engaging way to explore various RL concepts. In this series of blog posts, my goal is to teach RED to evolve Squirtle into Wartortle without fainting by earning experience through battles with wild Pokemon! The video below shows the result of the final RED agent I trained using the methods I’ll introduce in this series.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8RQJYupAbPc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8RQJYupAbPc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8RQJYupAbPc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba921533a536e5de25670eea8976d91c/href">https://medium.com/media/ba921533a536e5de25670eea8976d91c/href</a></iframe><h4>Random agent</h4><p>Let’s start by developing an agent that takes random actions and observes how it behaves. In this series, we’ll be building on the RedGymEnv class that I introduced in the previous blog, so I recommend checking it out before continuing.</p><p><a href="https://medium.com/@ym1942/create-a-gymnasium-custom-environment-part-2-1026b96dba69">Create a gymnasium custom environment (Part 2)</a></p><p>In the video above, RED initialized in Oak&#39;s lab, having selected Squirtle as its starter Pokemon. To evolve Squirtle into Wartortle, RED must go to a grass area to encounter wild Pokemon. However, the first grass area is quite far from Oak&#39;s lab (for a simple RL agent…), which makes it difficult for RED to learn how to get there. To simplify the problem, let’s change the initial state to start directly in the grass area.</p><p>To achieve this, I manually moved RED to the grass area and saved the game state to a file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*fuPmu2XhAUa3obXB8DPLzg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ef2008cbdaee5fd1f57709892169fe4/href">https://medium.com/media/3ef2008cbdaee5fd1f57709892169fe4/href</a></iframe><p>In the reset function of the RedGymEnv class, we then load this saved state, ensuring that each episode begins in the grass area.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b6e0a804c75d895a0f8b7a19a3036ea/href">https://medium.com/media/4b6e0a804c75d895a0f8b7a19a3036ea/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80681db4b7dc4277bd93829f6429c515/href">https://medium.com/media/80681db4b7dc4277bd93829f6429c515/href</a></iframe><p>With this setup, when the environment is initialized, RED starts in the grass. Starting from this initial state, I tested how RED behaves when it takes random actions as a baseline. There are six possible actions RED can take: move up, down, left, right, or press the A and B buttons. At each step, one of these actions is randomly chosen. For now, no rewards are assigned, so none of the states or actions provide any rewards. Specifically, the step function of RedGymEnv class always returns a reward of zero.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d05049af653738fccc016423c7eb972d/href">https://medium.com/media/d05049af653738fccc016423c7eb972d/href</a></iframe><p>The code below performs 100 random actions starting from this initial state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ce7077ae50fb8ee83c4a6269e7ab25e/href">https://medium.com/media/8ce7077ae50fb8ee83c4a6269e7ab25e/href</a></iframe><p>The figure below shows the best actions and values that RED learned (with ties broken randomly). The arrows represent the selected actions, and the colors indicate the corresponding values. I used 45° and 315° angles for buttons A and B, respectively. If there were any value gradients, red represents higher values and blue represents lower values. However, since the actions were random and there were no rewards to guide learning, the learned values remained uniform across all states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*91nmspncg1lmuEQW7fnnAg.png" /></figure><p>As a side note, for this blog series, an episode terminates either when Squirtle loses a battle (i.e., its HP reaches zero) or when RED takes the number of steps (I set max step=100 for this example). The code below shows how I implemented the battle loss termination condition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7b238f7914e4ce9657d9ba26ebc09e6/href">https://medium.com/media/a7b238f7914e4ce9657d9ba26ebc09e6/href</a></iframe><p>Another thing to note is that the choice of action becomes more challenging in battles with wild Pokemon. RED needs to learn how to navigate to the “Attack” menu and select “Tackle” to reduce the enemy’s HP. However, there are many other buttons it could press, and once it switches to a different screen, it must navigate back to the battle screen to select Tackle. While teaching RED these steps is a future goal, for now, I’ve simplified things by always having RED press the A button during battles, which ensures that it always selects “Tackle.”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22c9d28d9656c6f329159ba1807e4d96/href">https://medium.com/media/22c9d28d9656c6f329159ba1807e4d96/href</a></iframe><h4>Q-learning agent with grass reward</h4><p>Now the fun part is coming: our goal is to evolve Squirtle into Wartortle without losing a battle! To do that, RED must walk around the grass area to encounter wild Pokemon. Let’s introduce a reward for staying in the grass. The game’s memory provides the current tile state, allowing us to check whether RED is in the grass. The following code checks the tile state at each step and rewards RED with 1 for being in the grass, and 0 otherwise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/010d0065d17db465f7f10bb2bcba5b97/href">https://medium.com/media/010d0065d17db465f7f10bb2bcba5b97/href</a></iframe><p>As a learning algorithm, we use Q-learning. Q-learning is an off-policy learning approach that employs two distinct policies: a behavior policy and a target policy. In my implementation, I used the epsilon greedy algorithm as a behavior policy and the greedy algorithm as a target policy. This means that our behavior policy (action selection process) contains some noise so it does not always choose the actions with the highest value. On the other hand, our target policy (value update process) does not contain any noise so it chooses the most greedy action as the next action to estimate the value. More specifically, below is how Q-learning updates the state action value for state S_t and action A_t:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*4gwKEVhHDi6X7X2nlVjC6A.png" /></figure><p>We can see that it chooses the most greedy value estimate from the max term in the equation. For more details on this algorithm, you can check <a href="https://medium.com/@ym1942/find-an-optimal-policy-with-finite-markov-decision-process-part3-td-learning-557245c9735c">my previous blog</a>.</p><p>With Q-learning and in grass reward, I trained RED over 10 episodes. The figure below shows the best action and value learned at each state. Arrows represent the learned best actions, and colors represent the corresponding values. Again, I used 45° and 315° angles for A and B buttons, respectively. Red arrows correspond to high-value states, while blue arrows correspond to low-value states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*44n9_R3RbCxhaYgR4gmmfA.png" /></figure><p>As expected, RED learned that being in the grass is advantageous, as the learned values in the grass area were higher than in non-grass areas.</p><h4>Q-learning agent with grass reward and different initial values</h4><p>For the training above, I initialized all new states with a value of 0.5. In other words, whenever RED encountered a new state, I assigned a value of 0.5 to all six possible actions. Through experiments, I found that this initial value setting significantly influences RED&#39;s behavior.</p><p>When RED encounters a new state, it has no knowledge of its value. By setting an initial value, we impose a prior belief about the state’s value. For example, if we set the initial value to 0, RED will assume that all new states have no potential rewards. As a result, when faced with a choice between an action leading to the grass (a known state with positive rewards) and an action leading to an unknown state (assumed to have zero value), RED will prefer the known state, thus limiting the exploration of new states.</p><p>It’s important to note that this is a relative evaluation. An initial value of 0 can still be attractive if already-explored states have negative values. Thus, a lower initial value encourages exploitation, while a higher initial value promotes exploration. In RL, setting high initial values to encourage exploration is known as “Optimistic Initial Values.”</p><p>For example, here is the value function learned by RED after 10 episodes with an initial value of 1.5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*B9X0fY3AHHMQabVkwmOUrg.png" /></figure><p>Since new states start with high values, RED explores new states more than in the previous example with an initial value of 0.5.</p><h4>Problem toward the next blog</h4><p>Can RED evolve Squirtle into Wartortle with this reward system without losing a battle? Not yet. We need further improvements to achieve this goal.</p><p>For instance, one problem I found was that RED sometimes learns just to stay at the same grass tile by repeatedly pressing A or B without moving since RED is rewarded for being in the grass. This prevents RED from encountering wild Pokemon. This behavior isn’t what we want RED to learn. In the next blog, I’ll implement a new reward system to encourage RED to move to different tiles and encounter wild Pokemon.</p><p><a href="https://medium.com/@ym1942/train-red-with-rl-to-create-wartortle-part-2-954973f77fde">Part 2: Teach to walk around in grass area</a></p><h4>Code</h4><p><a href="https://github.com/yuumii-san/RL_tutorial_notebook/tree/main/pokemon/create_wartortle">https://github.com/yuumii-san/RL_tutorial_notebook/tree/main/pokemon/create_wartortle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a87a35a9a65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A taxonomy of RL algorithms]]></title>
            <link>https://medium.com/@ym1942/a-taxonomy-of-rl-algorithms-341fd1b4c659?source=rss-2bd5bc0e2538------2</link>
            <guid isPermaLink="false">https://medium.com/p/341fd1b4c659</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[taxonomy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yuki Minai]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 14:04:31 GMT</pubDate>
            <atom:updated>2024-08-04T14:10:13.175Z</atom:updated>
            <content:encoded><![CDATA[<p>In previous blogs, I’ve introduced various reinforcement learning (RL) algorithms such as Deep Q-Learning, Actor-Critic, and Proximal Policy Optimization (PPO). With so many RL approaches available, I often get confused by the differences between them. To solve this problem, in this blog, I would like to try to categorize these RL algorithms to get a clearer picture of the RL landscape.</p><h3>Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWGeUZNNB-KyGeLiSap7ew.png" /></figure><p>To organize the various RL algorithms, I’ve created a taxonomy chart. This chart helps illustrate the relationships and distinctions between different types of RL methods. In the following sections, I will explain each branch of this taxonomy, providing examples of algorithms that fit into each category.</p><h3>Model-free vs Model-based</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nOv2pbsTcLdN30Z3dKjbA.png" /></figure><p>The first major distinction in RL is between model-free and model-based methods. The word “model” has various meanings in machine learning. In RL, a “model” refers to the dynamics of the environment, which help an agent simulate and plan future actions. For example, a model provides information about the next state by taking a certain action at a certain state. It also has information about the immediate reward an agent can receive by moving to a certain state. The goal of both model-free and model-based RL methods is the same, learn an optimal policy to maximize total reward. The difference between them is the use of a model.</p><p><strong>Model-free methods</strong></p><p>Model-free methods do not use a model of the environment. Instead, they learn directly from experience by interacting with the environment. The agent takes actions and observes the results, gradually learning the best actions to take. Examples of model-free algorithms include Q-Learning, Deep Q-Network (DQN), SARSA, and Actor-Critic. These methods are simpler to implement but often require more data to learn effectively.</p><p><strong>Model-based methods</strong></p><p>On the other hands, model-based methods use a model to simulate the environment and plan actions. The model predicts the outcomes of actions without having the actual experience, allowing the agent to plan ahead and learn more efficiently. This mental simulation facilitates optimal policy learning with less experience.</p><p>Note that a model of the world is not always available. In board games such as chess, we know exactly how the board changes with each move (i.e., the dynamics are fully defined and known). However, this kind of model is rarely available in real-life scenarios. For example, with a walking robot, we do not have a perfect model of the surrounding physics, making it difficult to predict how a specific body movement will change the state. Therefore, a significant challenge in model-based methods is learning this model. If we can develop an accurate model, optimal policy learning will be greatly facilitated. However, if the learned model is poor, it may cause more problems than learning without a model.</p><p>Examples in this category include AlphaZero, MuZero, and Dreamer. Model-based methods can be more efficient in terms of data usage but require a good model of the environment, which is not always available.</p><h3>Value-based vs Policy-based</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLlzs8WE-C8Jt29eDiXsjA.png" /></figure><p>Within model-free methods, another key distinction is between value-based and policy-based approaches.</p><p><strong>Value-based methods</strong></p><p>Value-based model-free methods focus on learning a value function that estimates the expected return (total future reward) for each state or state-action pair. In RL, the accumulation of immediate and all future rewards is called “value”. By knowing the value of each state, the agent can choose actions that maximize long-term rewards. Examples include Q-Learning, DQN, and SARSA. These methods are effective but can struggle with high-dimensional state spaces.</p><p><strong>Policy-based methods</strong></p><p>Instead of explicitly learning a value function, policy-based model-free methods learn a policy that directly maps states to actions. These methods parameterizes a policy (often by using a neural network model) and optimizes it to maximize expected returns using gradient-based methods. With gradient ascent, these methods try to learn a policy leading to a higher expected value. Examples include REINFORCE, PPO, and TRPO. Policy-based methods can handle continuous action spaces and stochastic policies better than value-based methods. These methods are also useful when a policy is more straightforward function to approximate compared to the value function.</p><p><strong>Actor-Critic methods (Combination of value and policy based methods)</strong></p><p>I did not include this category in my chart for simplicity but there is another important category of methods combining both value-based and policy-based learning, which are called Actor-Critic methods. Actor-critic methods have two main components: an actor, which proposes actions, and a critic, which evaluates actions using a value estimate obstained from a value function. Neural network is often used as an actor and a critic and they are updated using gradient-based methods. Examples include the Advantage Actor-Critic (A2C) and Asynchronous Advantage Actor-Critic (A3C).</p><h3>Tabular vs Approximation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SceabIDPtuQtgAJSJZoyag.png" /></figure><p>Within value-based methods, there is a further division between tabular and approximation methods depending on how to estimate the value.</p><p><strong>Tabular methods</strong></p><p>Tabular methods use a table to store the value of each state or state-action pair. The value estimates of this approach for all states are based on agent observation. There is no approximation, so if an agent does not visit a certain state, it has no knowledge or expectation of the value at that state. This works fine when the state space is small. However, as the state space increases, it requires progressively more experience and becomes impractical due to the “curse of dimensionality.” Examples include basic Q-Learning and SARSA.</p><p><strong>Approximation methods</strong></p><p>Approximation methods use function approximators, such as neural networks, to estimate values. This makes them scalable to larger state spaces but introduces the complexity of choosing and training a suitable function approximator. A good value function would facilitate learning with less experience because an agent can estimate the value of unvisited states, avoiding low-value states and seeking out high-value states. Examples include DQN. Since the state space that can be represented with tabular methods is limited, most modern reinforcement learning (RL) methods, both model-based and model-free, use approximation techniques.</p><h3>Stateless vs Stateful</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jyCda9Mq-v4CvaQO-N2gIw.png" /></figure><p>Within tabular methods, we can distinguish between Stateless and Stateful methods.</p><p><strong>Stateless methods</strong></p><p>Stateless methods do not consider the current state when making decisions. They are often used in multi-armed bandit problems, where the goal is to maximize rewards without considering the state. In multi-armed bandit problems, we have multiple slot machines (i.e. action to take), and we want to choose which one to play to win. Initially, we might randomly choose machines and then gradually form a hypothesis about which machines have a higher chance of winning. In this process, there is no representation of state. Our focus is on which action can maximize the reward. Examples in this category include the epsilon-greedy algorithm.</p><p><strong>Stateful methods</strong></p><p>On the other hand, stateful methods consider the current state when making decisions. Most RL algorithms fall into this category because they need to account for the state to make informed decisions. Examples include dynamic programming and most model-free methods.</p><h3>Discrete action vs Continuous action</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlNSIg055AgkfzyNYx6-7g.png" /></figure><p>Policy-based methods can be categorized based on the type of action space they handle.</p><p><strong>Discrete action</strong></p><p>These methods work well with environments where actions are discrete choices. Examples include REINFORCE and A3C, which is designed for discrete actions.</p><p><strong>Continuous action</strong></p><p>These methods are suitable for environments with continuous actions. Examples include Deep Deterministic Policy Gradient (DDPG).</p><h3>Given model vs Learned model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXPZWSZ38Df_8vhZN0GYRQ.png" /></figure><p>For model-based methods, one key distinction is whether the model is given or learned.</p><p><strong>Given model</strong></p><p>Given-model model-based methods use a predefined model of the environment, such as in chess or other board games. In other words, there is no learning of the dynamics model happening with these methods. The model is used to plan and make decisions. The predefined models allow for precise planning but are only applicable when the environment’s dynamics are well-understood and deterministic. Examples include AlphaGo.</p><p><strong>Learned model</strong></p><p>Leanred-model model-based methods learn the model of the environment through interactions. The agent learns both the model and the policy, which is more challenging but necessary for complex environments. Learning a model involves approximating the environment’s dynamics, which can be quite complex, especially in high-dimensional or stochastic environments. These methods can adapt to environments where dynamics are not predefined, making them more versatile. Examples include MuZero, and Dreamer.</p><h3>Planning-based vs Gradient-based</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-6NdMsD_rrgumSrKGjE1Q.png" /></figure><p>Lastly, within model-based methods, we can distinguish between planning-based and gradient-based approaches depending on how to learn the optimal policy with a model.</p><p><strong>Planning-base</strong></p><p>Planning-base methods use the model to run simulations and plan actions. Monte Carlo Tree Search (MCTS) is a common planning method used with these methods. These methods use mental simulation using the dynamics model for many iterations. The obtained information such as value during this simulation is then used as the prediction target to update the value abd policy model. Planning-based methods can be computationally expensive but provide a thorough search of possible actions. They leverage the model to explore different scenarios and choose the best actions based on these simulations. Examples include Muzero.</p><p><strong>Gradient-base</strong></p><p>Gradient-based methods aim to optimize a parametric policy or value function by directly computing gradients, which can be more efficient in some contexts. This approach does not require extensive simulations and can be faster but may not explore all possibilities as thoroughly. Examples include Dreamer.</p><h3>Summary</h3><p>In this blog, I covered the taxonomy of RL algorithms. Here’s a quick summary:</p><ul><li><strong>Model-Free vs. Model-Based:</strong> Based on the use of environment models.</li><li><strong>Value-Based vs. Policy-Based:</strong> Based on learning value functions or direct policies.</li><li><strong>Tabular vs. Approximation:</strong> Based on the method of value estimation.</li><li><strong>Stateless vs. Stateful:</strong> Based on consideration of current states.</li><li><strong>Discrete vs. Continuous Action Spaces:</strong> Based on the type of action spaces handled.</li><li><strong>Given Model vs. Learned Model:</strong> Based on whether the model is predefined or learned.</li><li><strong>Planning-Based vs. Gradient-Based:</strong> Based on the approach to optimize policies.</li></ul><h3>Ref</h3><ul><li>Moerland, T. M., Broekens, J., Plaat, A., &amp; Jonker, C. M. (2023). Model-based reinforcement learning: A survey. <em>Foundations and Trends® in Machine Learning</em>, <em>16</em>(1), 1–118.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=341fd1b4c659" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a gymnasium custom environment (Part 2)]]></title>
            <link>https://medium.com/@ym1942/create-a-gymnasium-custom-environment-part-2-1026b96dba69?source=rss-2bd5bc0e2538------2</link>
            <guid isPermaLink="false">https://medium.com/p/1026b96dba69</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[gymnasium]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gym]]></category>
            <dc:creator><![CDATA[Yuki Minai]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 13:46:28 GMT</pubDate>
            <atom:updated>2024-08-08T12:13:12.250Z</atom:updated>
            <content:encoded><![CDATA[<p>gymnasium packages contain a list of environments to test our Reinforcement Learning (RL) algorithm. For example, this previous blog used FrozenLake environment to test a TD-lerning method. While these environments are great testbeds, we often want to customize the provided environment to see how an agent behaves in different environments. It is also a great interest to create our custom environment and test our algorithm.</p><p>gymnasium provides an easy way to do them. In this series of blogs, we will learn</p><ul><li>How to edit an existing environment in gymnasium (<a href="https://medium.com/@ym1942/create-a-gymnasium-custom-environment-part-1-04ccc280eea9">last blog</a>)</li><li>How to create a custom environment with gymnasium (this blog)</li></ul><p>In this blog, we will create a fun environment to play Pokemon Red Game. This is motivated by <a href="https://www.youtube.com/watch?v=DcYLT37ImBY&amp;t=1741s">this cool work</a> by Peter Whidden and <a href="https://github.com/Baekalfen/PyBoy">another work</a> by Asger Anders Lund Hansen, Mads Ynddal, and Troels Ynddal. The code is mainly adapted from <a href="https://github.com/PWhiddy/PokemonRedExperiments">Peter’s git repository</a> but simplified to convey the key points to define a custom environment.</p><h4><strong>4 essential functions to define a custom environment</strong></h4><p>As reviewed in the previous blog, a gymnasium environment has four key functions listed below (obstained from <a href="https://gymnasium.farama.org/api/env/)">official documentation</a>).</p><p>- reset() : Resets the environment to an initial state, required before calling step. Returns the first agent observation for an episode and information, i.e. metrics, debug info.</p><p>- step() : Updates an environment with actions returning the next agent observation, the reward for taking that actions, if the environment has terminated or truncated due to the latest action and information from the environment about the step, i.e. metrics, debug info.</p><p>- render() : Renders the environments to help visualize what the agent see, examples modes are “human”, “rgb_array”, “ansi” for text.</p><p>- close() : Closes the environment, important when external software is used, i.e. pygame for rendering, databases</p><p>When designing a custom environment, we inherit “Env” class of gymnasium. Then, we redefine these four functions based on our needs. Inheriting “Env” class is crucial because it:</p><ul><li>provides access to a rich set of base functionalities and utilities within the Gymnasium library, such as methods for seeding randomness.</li><li>ensures that the custom environment adheres to the Gymnasium framework’s standardized interface, allowing it to be used interchangeably with other Gym environments.</li><li>facilitates the integration with other Gymnasium tools and plugins, enhancing the environment’s capabilities and simplifying the development and testing process.</li></ul><p>By inheriting from the Env class, we can focus on defining the unique aspects of our custom environment such as its observation space, action space, and dynamics, while leveraging the established infrastructure provided by Gymnasium for simulation control, rendering, and interaction with learning algorithms.</p><h4><strong>Pokemon Red Game environment</strong></h4><p>Let’s start defining the pokemon environment.</p><p>To create a Pokemon Red Game environment, we use a python based game boy emulator called <a href="https://github.com/Baekalfen/PyBoy">PyBoy</a>.</p><p>In the Pokemon Red Game environment, there are 7 commands (i.e. action) the agent can use to explore the world:</p><ul><li>Press arrow up</li><li>Press arrow down</li><li>Press arrow right</li><li>Press arrow left</li><li>Press A botton</li><li>Press B botton</li><li>Press start botton</li></ul><p>These are the same commands we can use to play Pokemon Red! The state an agent can be in is defined by the game map. The observed state is a 144x160x3 grid of images (i.e. one 144x160 grid image for RGB). For reward function, we can design it as we want. For this tutorial, let’s define a reward as a sum of levels of all pokemons caught so far for simplicity. (Note that we need a more sophisticated reward function to train an agent to play pokemon red.)</p><h4><strong>Initialize the environment</strong></h4><p>As I mentioned above, we will create our class by inheriting Env class of gymnausium. Then, we will implement four essential functions, reset, step, render, and close for our new custom class. Before defining these functions, we will first learn the implementation of initialization. This initialization process is invoked when the environment is first created. This process establishes the key characteristics of the environment.</p><p>During initialization, we define several critical aspects:</p><ul><li>Action space: A set of all possible actions that an agent can take in the environment. It’s a way to outline what actions are available for the agent to choose from at any given step</li><li>Observation space: A size or shape of the observations that the agent receives from the environment. Essentially, it describes the form and structure of the data the agent uses to make decisions</li><li>Action frequency: A number of frames before a new action is taken. In the context of PyBoy, an action can be applied once every 24 frames. This setting controls the pace at which the agent can act within the game environment</li><li>Pyboy object: An object to interface with the actual game environment provided by PyBoy. It acts as the bridge between our custom gymnausium environment and the Game Boy game we aim to interact with</li><li>Initial state: A starting state of the agent when the environment is initialized. For the purpose of this tutorial, we will set the initial state to be the moment after choosing the first pokemon, as demonstrated in Peter Whidden’s work</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c21a835dd8062388cf04491162b5ad1/href">https://medium.com/media/8c21a835dd8062388cf04491162b5ad1/href</a></iframe><h4><strong>Render the environment</strong></h4><p>Next, we will define a render function. This function returns the pixel values of the game screen at any given moment. By default, the screen pixel size in PyBoy is set to (144, 160, 3), representing the resolution and color depth (RGB) of the Game Boy’s display.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad8f618efa5b7ebc496491b54e3c33cb/href">https://medium.com/media/ad8f618efa5b7ebc496491b54e3c33cb/href</a></iframe><h4><strong>Reset the environment</strong></h4><p>Next, we will define a reset function. When we run multiple episodes of simulation, we call reset function at the beginning of each episode to reset the environment to a predefined initial state. Note that initialization function (<strong>__init__</strong>) is called when the environment is created only once when the environment is first created. After that, at the beginning of each new episode, reset function will be called for initialization of the environment, ensuring that each episode starts from a consistent state.</p><p>Within this function, for our specific case, we will initialize the state and the total reward value as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a6c85024f0768e5d78239d4ffa04a52/href">https://medium.com/media/6a6c85024f0768e5d78239d4ffa04a52/href</a></iframe><h4><strong>Take a step in the environment</strong></h4><p>Next, we will define step function. We pass an action as its argument. This function moves the agent based on the specified action and returns the new state, obtained reward, and whether the episode is terminated/truncated. For simplicity, we don’t consider the termination or truncation condition in this implementation. Thus, the episode is terminated when we stop the execution of this code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37bcd6bfdca0c6b5db95cc029cd86da7/href">https://medium.com/media/37bcd6bfdca0c6b5db95cc029cd86da7/href</a></iframe><h4><strong>Close the environment</strong></h4><p>Lastly, we will define a close function to ensure proper cleanup of any resources used during the simulation. We will inherit and use the close function from the parent class. Additionally, we will include code specifically designed to terminate the PyBoy session.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df6e56173028c881d85aee00ff2c192b/href">https://medium.com/media/df6e56173028c881d85aee00ff2c192b/href</a></iframe><h4><strong>Integrate all functions and define a whole class</strong></h4><p>Let’s integrate all functions, define the whole RedGymEnv class, and test our implementation!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/345764e03cc0ab1dfc490f8cf111af4f/href">https://medium.com/media/345764e03cc0ab1dfc490f8cf111af4f/href</a></iframe><h4><strong>Visualize the current state</strong></h4><p>In the below code, after initializing the environment, we choose random action for 30 steps and visualize the pokemon game screen using render function.</p><p>Since we need to use Pokemon Rom file to run this environment, we cannot run it on kaggle. Here is how you can run the below code.</p><p>1. Download this blog</p><p>2. Legally obtain Pokemon Red ROM file (You can find this using google)</p><p>3. Download has_pokedex_nballs.state file from <a href="https://github.com/PWhiddy/PokemonRedExperiments">this github repository</a></p><p>4. Upload the below two path variables based on where each file is on your machine</p><p>5. Uncomment below cell</p><p>6. Ready to run!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ce098db7da88fd8a9dc0b3354da873d/href">https://medium.com/media/9ce098db7da88fd8a9dc0b3354da873d/href</a></iframe><p>After setting up your environment, you should be able to see something like below video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkX_hQjFWqs4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkX_hQjFWqs4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkX_hQjFWqs4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b265f37804ccef93da82f820a2d4357/href">https://medium.com/media/9b265f37804ccef93da82f820a2d4357/href</a></iframe><p>It is working — RRed is now navigating the game screen in response to the action commands. With gymnasium, we’ve successfully created a custom environment for training RL agents.</p><p>In future blogs, I plan to use this environment for training RL agents. Stay tuned for updates and progress!</p><h4><strong>Reference</strong></h4><ul><li>PokemonRedExperiments github repository by Peter Whidden (https://github.com/PWhiddy/PokemonRedExperiments)</li><li>PyBoy github repository (https://github.com/Baekalfen/PyBoy)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1026b96dba69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a gymnasium custom environment (Part 1)]]></title>
            <link>https://medium.com/@ym1942/create-a-gymnasium-custom-environment-part-1-04ccc280eea9?source=rss-2bd5bc0e2538------2</link>
            <guid isPermaLink="false">https://medium.com/p/04ccc280eea9</guid>
            <category><![CDATA[frozen-lake]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gymnasium]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[gym]]></category>
            <dc:creator><![CDATA[Yuki Minai]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 13:45:09 GMT</pubDate>
            <atom:updated>2024-03-04T13:47:41.863Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>gymnasium packages contain a list of environments to test our Reinforcement Learning (RL) algorithm. For example, <a href="https://medium.com/me/stats/post/557245c9735c">this previous blog</a> used FrozenLake environment to test a TD-lerning method. While these environments are great testbeds, we often want to customize the provided environment to see how an agent behaves in different environments. It is also a great interest to create our custom environment and test our algorithm.</p><p>gymnasium provides an easy way to do them. In this series of blogs, we will learn</p><ul><li>How to edit an existing environment in gymnasium (this blog)</li><li>How to create a custom environment with gymnasium (<a href="https://medium.com/@ym1942/create-a-gymnasium-custom-environment-part-2-1026b96dba69">next blog</a>)</li></ul><h4><strong>Basic structure of gymnasium environment</strong></h4><p>Let’s first explore what defines a gym environment.</p><p>Each gymnasium environment contains 4 main functions listed below (obtained from <a href="https://gymnasium.farama.org/api/env/)">official documentation</a>)</p><ul><li>reset() : Resets the environment to the initial state, required before calling step. Returns the first agent observation for an episode and information, i.e. metrics, debug info.</li><li>step() : Updates an environment with actions returning the next agent observation, the reward for taking that actions, if the environment has terminated or truncated due to the latest action and information from the environment about the step, i.e. metrics, debug info.</li><li>render() : Renders the environments to help visualise what the agent see, examples modes are “human”, “rgb_array”, “ansi” for text.</li><li>close() : Closes the environment, important when external software is used, i.e. pygame for rendering, databases</li></ul><p>These functions define the properties of the environment and how the environment responds to actions taken by the agent. When starting a new episode, reset() is called to initialize the environment. At each time step, when an agent takes an action, step() is called to encode the action and observe its consequences, such as changes in the agent’s state or any rewards received. render() function is used to visualize the current state of the environment when needed. Lastly, when the simulation is complete, close() is called to properly clean up any resources that were used.</p><h4>Example environment: Fronzen Lake</h4><p>Let’s understand these functions more with an example using FrozenLake environment.</p><p>The objective of an agent in this environment is to navigate through a grid world, starting from the initial cell and reaching the goal cell. Here, we are using a 4x4 grid map, and each cell falls into one of four different categories:</p><ul><li><strong>S (Start)</strong>: This cell is where our agent begins its journey.</li><li><strong>F (Frozen)</strong>: These cells are safe for the agent to walk on.</li><li><strong>H (Hole)</strong>: These are hazardous cells, and if the agent falls into one, the episode terminates with a reward of 0.</li><li><strong>G (Goal)</strong>: Reaching this cell yields a reward of +1 for the agent.</li></ul><p>From the starting cell, the agent has the option to move in four directions: up, left, down, or right. The agent’s task is to explore the grid world, making decisions at each time step to eventually reach the goal cell and collect a reward of +1.</p><p>In the below code, we can see an example of the agent randomly exploring this environment over 20 time steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e127dc0cf59131cd45dc3bc2094c9e9/href">https://medium.com/media/7e127dc0cf59131cd45dc3bc2094c9e9/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F51OmVPQoNTU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D51OmVPQoNTU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F51OmVPQoNTU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5817eaeaf650bd6398d006b67f969ff7/href">https://medium.com/media/5817eaeaf650bd6398d006b67f969ff7/href</a></iframe><p>With gymnausium’s predefined environment, it is very easy to run the simulation.</p><p>As you may have observed, the default behavior is for the agent to start from the top-left cell and aim to reach the bottom-right cell.</p><p>Let’s begin by adjusting the initial state of the environment. By default, in this environment, the agent always begins in the top-left corner. Now, let’s experiment with changing both the initial and goal locations. We’ll set our starting position to the bottom-right and our goal position to the top-left. To achieve this, we can utilize the ‘desc’ argument when creating the environment, which specifies the starting position.</p><p>Reference: The original code of FrozenLake is available <a href="https://github.com/Farama-Foundation/Gymnasium/blob/main/gymnasium/envs/toy_text/frozen_lake.py">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba26ea768be910bd05d0e461238a2f52/href">https://medium.com/media/ba26ea768be910bd05d0e461238a2f52/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FODYaCmNj-tI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DODYaCmNj-tI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FODYaCmNj-tI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea0f5079580f0870db02eb72bccc246b/href">https://medium.com/media/ea0f5079580f0870db02eb72bccc246b/href</a></iframe><p>In this scenario, we can adjust our environment without modifying the original class and function simply by passing the appropriate argument. The gymnasium environment provides several options for modifying the environment. When beginning to use the Gymnasium environment, it’s a good idea to check their documentation to explore the kinds of modifications that are already available within the package.</p><h4><strong>Edit an existing environment</strong></h4><p>Next, let’s consider a scenario where the original function doesn’t provide the functionality we need. Here, we aim to modify the reward function. By default, an agent receives +1 reward upon reaching the goal and no other rewards. We will introduce a negative reward -0.1 as a penalty at each step to encourage the agent to reach the goal quickly. To do this, we inherit FrozenLakeEnv class in gymnasium and define a new step function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3168ea09ac9afbcff3d5d654c15bafca/href">https://medium.com/media/3168ea09ac9afbcff3d5d654c15bafca/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBOK1_a3PueU&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBOK1_a3PueU&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FBOK1_a3PueU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5edb22ba15427826c2c2e8417e220c8e/href">https://medium.com/media/5edb22ba15427826c2c2e8417e220c8e/href</a></iframe><p>We can see that the agent received the total reward of -2.0 over 20 steps (i.e. -0.1 penalty at each time step).</p><p>Like this example, we can easily customize the existing environment by inheriting the original gymnasium class. For example, even if we modify a step function within a parent environment class, we can keep using the original reset and render functions without changing anything.</p><h4><strong>Summary</strong></h4><p>In this blog, we learned the basic of gymnasium environment and how to customize them. In the <a href="https://medium.com/@ym1942/create-a-gymnasium-custom-environment-part-2-1026b96dba69">next blog</a>, we will learn how to create own customized environment using gymnasium!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04ccc280eea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>