<?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 Yaroslava Mykhailenko on Medium]]></title>
        <description><![CDATA[Stories by Yaroslava Mykhailenko on Medium]]></description>
        <link>https://medium.com/@yaroslavamihaylenko?source=rss-8bb40242e26d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LVgzaMdeRv2wqhIpLCEz5A.jpeg</url>
            <title>Stories by Yaroslava Mykhailenko on Medium</title>
            <link>https://medium.com/@yaroslavamihaylenko?source=rss-8bb40242e26d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:15:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yaroslavamihaylenko/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[Foreign Object Detection in Estonian Mines: Rethinking the Problem from Classification to Detection]]></title>
            <link>https://medium.com/enefitit/foreign-object-detection-in-estonian-mines-rethinking-the-problem-from-classification-to-detection-28004586244e?source=rss-8bb40242e26d------2</link>
            <guid isPermaLink="false">https://medium.com/p/28004586244e</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[industrial-automation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Yaroslava Mykhailenko]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 18:09:10 GMT</pubDate>
            <atom:updated>2026-04-28T18:09:10.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HcJkk3YDuHl1wqnnzIbAxA.png" /></figure><p>In Estonian mines, conveyor belts move thousands of tons of material every hour - oil shale, crushed rock, and other valuable resources flowing continuously through the production line. But along with this material, foreign objects occasionally appear on the belt: wooden fragments, pieces of timber, even leftover anchor bolts from maintenance work.</p><p>At first glance, they may look harmless. In reality, a single missed object can damage crushers and downstream equipment, stop an entire production line, and lead to repair costs reaching <strong>tens of thousands of euros.</strong></p><p>Traditionally, monitoring has relied on manual inspection, which is both costly and imperfect in harsh mining conditions. This naturally raises a question: can the process be automated? Could we reduce dependency on manual supervision and build a smarter detection system?</p><p>That is how the problem reached our team - the <strong>AI/ML Systems &amp; Prototyping Team at Enefit</strong>, one of the largest electricity providers in the Baltics. We were asked to validate whether a computer vision system could reliably detect wooden foreign objects on conveyor belt images from Estonian oil shale mines.</p><p>In this article, I’ll walk through how we approached the problem using real industrial images from one of the Narva mines. We’ll start with our first attempt - framing the task as a <strong>classification problem</strong>, which initially looked promising but eventually failed due to <strong>shortcut learning</strong>. That discovery forced us to rethink the problem and move toward <strong>object detection </strong>- and that’s when things finally started to work.</p><h3>Data and System Setup</h3><p>Before diving into the models, it’s important to understand the environment where this system operates and the data we had to work with. The project was deployed directly in an active oil shale mine, where conveyor belts continuously transport material through the production line.</p><h4>System Design</h4><p>The setup itself is relatively simple.</p><p>A <a href="https://docs.baslerweb.com/a2a1920-51gcpro"><strong>Basler a2A1920–51gcPRO</strong></a> machine vision camera is installed above the conveyor belt and continuously captures images of the material moving underneath it. The camera streams images through the GigE Vision protocol to a virtual machine running Python, where we handle image acquisition using the Basler Pylon SDK.</p><p>Each frame is then passed to the machine learning model, which analyzes the image and looks for potential foreign objects. If something suspicious is detected, the system can trigger a signal light near the conveyor belt, alerting operators or stopping the line before the object reaches the machinery.</p><p>The hardware - the camera and the signal light - is installed directly in the mine environment. The image processing runs on a virtual machine inside the mine’s internal infrastructure to keep latency low. Detection events and captured images are later transferred to object storage for logging and further analysis.</p><p>The physical setup of the system is shown below.</p><figure><img alt="Physical setup of the system in the mine" src="https://cdn-images-1.medium.com/max/1024/1*vPSDGXF1YW02wfNzIWwtOw.png" /><figcaption>Physical setup of the system in the mine</figcaption></figure><h4>Conveyor Characteristics</h4><p>The conveyor belt is roughly<strong> 1</strong> <strong>meter wide</strong> and moves at about <strong>2 meters per second</strong>, continuously transporting oil shale. Foreign objects appear relatively rarely - typically around <strong>1–2 occurrences per week</strong>, which is great for operations, but not so great when you need training data for a model.😉</p><h4>Data Collection</h4><p>Because real incidents are so rare, the dataset had to be collected in two different ways.</p><p>Images without foreign objects were captured during normal conveyor operation, simply recording the belt as it transported oil shale fragments.</p><p>Images with foreign objects were collected in a controlled setup. We manually placed wooden fragments on the belt in different positions and orientations to simulate how they might appear in real conditions. The belt was stopped during this process, since intentionally placing wood on a moving conveyor would not have been safe - the object could have continued down the line toward the machinery.</p><p>For the pilot dataset we collected:</p><ul><li><strong>1,000</strong> <strong>images without wood</strong></li><li><strong>300 images with wooden pieces</strong></li></ul><p>Here are some examples from the collected dataset. To make them easier to see in the article, we brightened the images slightly. In real mine conditions, the original images are actually darker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYDfLSB3egymz2mUHCJixg.png" /><figcaption>Examples of the training data</figcaption></figure><h3>First Attempt: Image Classification</h3><h4>Setup and Initial Results</h4><p>With the dataset in place, we started by framing the task as a binary image classification problem: given an image, predict whether it contains a wooden foreign object or not. This was the simplest way to begin - it only required image-level labels and allowed us to test the idea quickly before moving to a more complex approach.</p><p>To make the evaluation more reliable, we split the data by sequence rather than by individual images, so that frames from the same time period would not appear in both train and test sets. The final split was <strong>80% for training and 20% for testing</strong>.</p><p>For the model, we used <strong>ResNet18</strong> with pretrained ImageNet weights and replaced the final layer with a two-class output. The model was then fine-tuned for <strong>10 epochs</strong> using cross-entropy loss and the Adam optimizer.</p><p>The initial results looked almost too good to be true: the<strong> </strong>model achieved <strong>close to 100% precision, recall, and accuracy</strong> on both the training and test sets.</p><p>That immediately raised a question - was it actually learning to detect wood?</p><h4>Looking Beyond the Metrics</h4><p>To understand what the model was really using for its predictions, we applied <a href="https://arxiv.org/abs/1610.02391"><strong>Grad-CAM</strong></a>, which highlights the regions of an image that influence the model’s decision. Some examples are shown below. In these heatmaps, red indicates stronger influence on the prediction, while blue indicates weaker influence.</p><figure><img alt="Grad-CAM examples showing where the classifier focuses when making predictions" src="https://cdn-images-1.medium.com/max/768/1*KD5kULGmtpNES0ASfIoAlg.png" /><figcaption>Grad-CAM examples showing where the classifier focuses when making predictions</figcaption></figure><p>Although the model was extremely confident and assigned a wood probability of 0.00 to no-wood images and 1.00 to wood images, the heatmaps told a different story.</p><p>Instead of focusing on the wooden object, the model was mostly reacting to the <strong>edges of the conveyor belt, rollers, and background areas</strong>. It also seemed to rely on more general visual differences such as sharpness and texture, which helped distinguish moving-belt images from stopped-belt images.</p><p>This was a clear case of <strong>shortcut learning - </strong>the model had learned to rely on differences in image acquisition conditions instead of actually detecting wood.</p><h4>Why Classification Wasn’t Enough</h4><p>After identifying shortcut learning, we tried to reduce the visual cues the model was exploiting.</p><p>One of our main assumptions was that the classes might be partially separable based on <strong>image sharpness</strong>. To test this, we used Laplacian variance, a classical CV measure. We found that wood images had a higher average sharpness (283.5) than no-wood images (265.1).</p><p>This meant that the model could already separate the classes to some extent using low-level features alone.</p><p>To reduce this effect, we introduced <strong>Gaussian blur augmentation</strong> during training, applying a light blur to images with a 50% probability. We also tried several other augmentations aimed at breaking the shortcut, including:</p><ul><li>masking small image regions</li><li>applying slight geometric transformations</li><li>varying brightness and color</li></ul><p>But <strong>the outcome did not change much </strong>- the model still focused on the wrong regions. :(</p><p>As a final attempt, we manually created <strong>6 synthetic positive samples</strong> in Adobe Photoshop by placing wooden pieces onto images of the moving conveyor belt (which was about the limit of my patience for manual editing😂). We added these images to the training set alongside the original data. This was a straightforward way to show the model that the wood class could also appear under different background and acquisition conditions.</p><p>And this actually helped.</p><figure><img alt="Grad-CAM visualizations after adding synthetic samples" src="https://cdn-images-1.medium.com/max/993/1*sS_KEmAEpPX1yKnRUKCmiA.png" /><figcaption>Grad-CAM visualizations after adding synthetic samples</figcaption></figure><p>As shown in the Grad-CAM examples above, the model started to focus on the wooden object in at least some cases, rather than only on the belt structure.</p><p>From this, we concluded that classification could potentially work - but only with enough <strong>real production data</strong>. Even a small number of such examples was enough to push the model in the right direction.</p><p>At that stage, however, collecting sufficient real data was not feasible, so we decided to explore a different approach.</p><h3>Second Attempt: Object Detection</h3><p>After the classification experiments, we reframed the task as<strong> object detection</strong>: given an image, predict whether a wooden foreign object is present and, if so, localize it with a bounding box.</p><p>We considered this a better fit because of how the task is optimized. In the classification setup, the model produced a single label for the entire image, and the loss was computed only at the image level:</p><figure><img alt="Cross-entropy loss for image-level classification" src="https://cdn-images-1.medium.com/max/177/1*aokHP0Abh0txVtLl6VPKHA.png" /><figcaption>Cross-entropy loss for image-level classification</figcaption></figure><p>This means the model was penalized only for predicting the wrong class, regardless of which part of the image it relied on.</p><p>In object detection, the training objective is stricter. The model must predict not only what the object is, but also whether an object is present and where it is located. In simplified form, the loss combines classification, objectness, and localization terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*tppD1dRtCDLILrXl6TIowA.png" /><figcaption>Simplified detection loss: classification + objectness + localization</figcaption></figure><p>Here, L_cls measures whether the predicted class is correct, L_obj measures whether the model correctly identifies the presence of an object, and L_box penalizes poor localization.</p><p>This difference was important for our use case. It was not enough for the model to say that wood was somewhere in the image - it also had to identify the actual object. That is why object detection was a much better fit: it aligned the training objective with what we actually needed in practice.</p><h4>Model and Setup</h4><p>For the detection stage, we chose <a href="https://github.com/Megvii-BaseDetection/YOLOX/tree/main"><strong>YOLOX</strong></a> as our main model family. The choice was driven by two requirements:</p><ul><li>The model had to be available under a free commercial license</li><li>It had to be lightweight enough for a real production environment, where images were arriving at roughly<strong> 5–6 frames per second</strong> and needed to be processed with low latency</li></ul><p>For this reason, we selected <strong>YOLOX-tiny</strong>, a smaller variant in the YOLOX family, with ~5 million parameters. It offered a good balance between speed and detection performance.</p><p>The dataset contained around <strong>900 training images</strong> and <strong>360 validation images</strong>, with about <strong>150 images containing wood</strong> in each split. The model was trained on a local machine using CPU only, for <strong>25 epochs</strong>, with the full training run taking around <strong>4 hours</strong>.</p><p>Like most detection models, YOLOX tracked <strong>mAP</strong> <strong>(mean Average Precision)</strong> during training, and the best checkpoint was selected based on that metric. In simple terms, mAP measures how well the predicted bounding boxes match the annotated objects.</p><p>However, mAP alone was not enough for our use case. In the real system, the decision was made at the <strong>frame level</strong>: did the model detect something suspicious or not?</p><p>That is why, for evaluation, we converted detection outputs into an image-level decision and computed <strong>TP, FP, TN, and FN</strong>. If the model predicted at least one valid box on a frame, we treated that frame as positive.</p><h4>Offline Training and Results</h4><p>We started by training the default YOLOX-tiny setup on our dataset. Even this baseline version already gave good frame-level results: it correctly identified <strong>129 positive frames</strong> and <strong>206 negative ones</strong>, while missing <strong>22 frames</strong> that actually contained wood.</p><p>This was a good starting point, but the model was still missing too many wood fragments.</p><p>We then focused on improving the training setup. Since this was a commercial project, we do not disclose the exact parameters, but the tuning was aimed at adapting the training process<strong> </strong>to our dataset rather than changing the model architecture.</p><p><a href="https://github.com/Megvii-BaseDetection/YOLOX/blob/main/docs/train_custom_data.md#4-tips-for-best-training-results">Following the recommendations from the YOLOX authors</a>, we adjusted the training schedule, reduced heavier augmentation, and made the overall training process more stable for our relatively small industrial dataset.</p><p>Here are some of the detected/missed wood examples and the table comparison between the baseline and tuned versions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeIpt5MRokiukrFOIUiEzA.png" /><figcaption>Detection examples with predicted bounding boxes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*J-DArq7ZvU2v-OdVc7KZVg.png" /><figcaption>Comparison of baseline and tuned YOLOX models on the validation set</figcaption></figure><p>The tuned model performed significantly better: it correctly identified <strong>149 positive frames</strong> and <strong>204 negative ones</strong>, while missing only <strong>2 positive frames</strong> and producing <strong>2 false alarms</strong>.</p><p>Based on these results, the tuned model was selected for deployment in the mine.</p><h4>Production Adaptation</h4><p>In the pilot stage, the model was tested directly in the Narva mine under real operating conditions.</p><p>To make the system less sensitive to singe noisy detections, we did not treat every positive frame as an alert. Instead, an alert was triggered only when the model detected a suspicious object in <strong>3–4 consecutive frames</strong>, with roughly <strong>0.25 seconds between frames.</strong></p><p>The feedback from the mine showed that, on the one hand, the model successfully detected all real wood pieces observed during the pilot period, but on the other hand, it generated too many false alerts.</p><p>For example, during one week, the model generated:</p><ul><li><strong>896 </strong>single-frame false detections, which resulted in roughly<strong> 4–8 false alerts per day</strong></li></ul><p>For the customer, this was still too frequent for daily operation - the target was to reduce false alerts to <strong>no more than 3 per week</strong>.</p><p>To improve the system, we broke the problem into three steps:</p><ul><li>adjusting the threshold</li><li>analyzing false-positive patterns</li><li>retraining the model on production data</li></ul><p>1.<strong> Threshold Analysis</strong></p><p>We first looked at data from real mine shifts to understand how changing the model’s confidence threshold affected the number of false detections and missed objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKzqR3fN0swgphtbuShNBQ.png" /><figcaption>Effect of confidence threshold on false positives and false negatives</figcaption></figure><p>From the graph above, we saw that increasing the threshold would reduce false positives much faster than it would increase false negatives. For example, raising it from <strong>0.5 to 0.8</strong> would reduce FP by about<strong> 65%</strong>, while FN would rise only to 5 cases, or about <strong>13%</strong> of all real objects.</p><p>Based on this, we increased the confidence threshold from the original <strong>0.5 to 0.8</strong> for the next stage of improvement.</p><p>2.<strong> False-Positive Patterns</strong></p><p>We then manually reviewed the false-positive frames to better understand what the model was reacting to.</p><p>The pattern was quite consistent. In most cases, the model was repeatedly triggered by <strong>belt joints</strong> or by <strong>wet surfaces on an empty belt</strong>. These cases were never present in the training data, so the model treated them as suspicious objects, often with confidence scores above <strong>0.8</strong>.</p><p>There were also other types of mistakes, but they were less frequent. Most of them were related to <strong>large rocks on the belt</strong>, which may have looked similar to wood in terms of shape or size.</p><p>Some examples of these FP patterns are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-6ZfyRt9ruQASm0tIZetg.png" /><figcaption>Examples of the typical false-positive patterns such as belt joints, wet surfaces etc.</figcaption></figure><p>These findings gave us a clear next step: the model needed to see more real production examples, especially hard negatives.</p><p>3. <strong>Retraining with Real Data</strong></p><p>To adapt the detector to real production conditions, we retrained it using new data collected from the mine.</p><p>We extended the original dataset with <strong>41 new true positives</strong> and <strong>200+ hard negative examples</strong> taken from production FP. In total, the updated training set contained roughly <strong>840+ images</strong>, with about <strong>190 images containing wood</strong>.</p><p>We did not train a new model from scratch. Instead, we took the best checkpoint of the previously deployed model and continued training from there for about <strong>15 additional epochs</strong>. At the same time, we kept the original training data together with the new production samples. This was important because training only on the new data could cause the model to forget previously learned patterns - a problem commonly known as <strong>catastrophic forgetting</strong>.</p><p>We also changed how we selected the best model. mAP was still tracked during training, but it was no longer the main criterion. At this stage, the goal was to reduce FP without losing too many TP, so we selected the final model based mainly on that balance across epochs.</p><p>4.<strong> Final Results in the Mine</strong></p><p>The table below shows the final comparison on a set of false-positive frames collected earlier during pilot operation.</p><p>On this set, the previously deployed model had produced <strong>896 false positives. </strong>After retraining the model on additional production data, including hard negatives, that number dropped to just <strong>3</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1D9vZ6g5ew2m4AeUADSgWg.png" /><figcaption>Comparison of previously tuned and production adapted models on the negative dataset</figcaption></figure><p>As a result, we reached the main practical goal: the model no longer produced consecutive false alerts that would trigger a conveyor stop. What remained were only occasional single-frame detections.</p><p>The model was then deployed in the mine, and over the next <strong>two pilot weeks </strong>it showed the same behavior. There were <strong>no consecutive FP events </strong>at all.</p><p>During this time, it detected <strong>3 real wood cases</strong>. It also detected a small pipe on the belt, which was also useful to catch ☺️.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3y6hMptGZPcVn2yF_zDLzA.jpeg" /><figcaption>Example detections from the first week of pilot operation</figcaption></figure><p>Finally, we also made an artificial test in the mine by manually throwing <strong>9 wooden objects </strong>onto the moving belt. The model detected <strong>9 out of 9</strong> without producing any false alert events!</p><p>Overall, these results gave us confidence that the model had become reliable enough for production use.🎉🥳</p><h3>Conclusion</h3><p>Looking back, the biggest lesson from this project was that a model can show great metrics and still learn the wrong thing.🤷</p><p>At first, the classification approach looked very promising. But once we looked closer, it became clear that the real challenge was not just training a model - it was framing the task in the right way. Moving to object detection turned out to be a much better fit for the problem, and the biggest improvements came later, when we started learning from real production data rather than only from offline experiments.</p><p>For me, this project was also a reminder that in industrial computer vision, the hard part is often not the model itself. It is the data, the edge cases, the evaluation logic, and all the small decisions that sit between a good validation result and something that can actually work in the field.</p><p>In the end, that was probably the most interesting part of the whole process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28004586244e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enefitit/foreign-object-detection-in-estonian-mines-rethinking-the-problem-from-classification-to-detection-28004586244e">Foreign Object Detection in Estonian Mines: Rethinking the Problem from Classification to Detection</a> was originally published in <a href="https://medium.com/enefitit">enefitit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Battery Operations with Reinforcement Learning in Electricity Markets]]></title>
            <link>https://medium.com/enefitit/optimizing-battery-operations-with-reinforcement-learning-in-electricity-markets-4e9e43da7a11?source=rss-8bb40242e26d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e9e43da7a11</guid>
            <category><![CDATA[electricity-market]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[energy-storage]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Yaroslava Mykhailenko]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 14:12:09 GMT</pubDate>
            <atom:updated>2025-06-18T13:04:35.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*roef5wUCXNPk-4mtu9Y0tg.png" /></figure><p>The ongoing energy transition toward renewable sources like wind and solar has brought significant challenges for electricity grids worldwide. One big question stands out: <strong>how do we keep supply and demand in balance when renewable generation is inherently volatile and shaped by ever-changing weather conditions?</strong> That’s where batteries come in. <a href="https://ourworldindata.org/battery-price-decline">Thanks to falling battery costs</a>, large-scale Battery Energy Storage Systems (BESS) are becoming an attractive asset for energy companies. By storing surplus energy when generation exceeds demand and release it when supply falls short, BESS help stabilize the grid and turn price fluctuations into trading opportunities. But to operate a battery profitably, especially in dynamic markets, you need smart trading strategies — algorithms capable of deciding when to charge, when to discharge, and when to hold energy in reserve.</p><p><strong>One of the simplest and most straightforward</strong> ways to approach the problem of battery trading is through <strong>linear optimization</strong>. This method provides clear decision rules and is relatively easy to implement, making it a popular choice for tackling this type of problem. While effective, this method has its limitations — it makes trading decisions based only on the information available at the time. For example, when placing bids for the day-ahead market, it can’t take into account future price movements in the intraday or balancing markets, simply because that data isn’t available yet. As a result, it may act too aggressively and miss better opportunities. Since some market patterns are only visible over time, we started wondering: <strong>could Reinforcement Learning(RL), which learns from delayed outcomes, do better?</strong></p><p>RL in real-world settings is still rare — not because it lacks promise, but because it’s hard. It requires careful modeling, lots of trial and error, and a good dose of patience. But when tuned well, RL has shown impressive results across fields, from robotics to games — and many believe it could become a powerful tool in real-world operations too.</p><p>This article provides a <strong>high-level overview of how RL can be applied to optimize battery trading</strong>. The article is structured as follows:</p><ol><li><strong>Problem Setting: </strong>defining the battery setup and the goal.</li><li><strong>Simulated Environment: </strong>building a custom training environment to reflect market dynamics and battery behavior, including state, actions, and rewards.</li><li><strong>Algorithm Selection &amp; Training: </strong>why specific algorithms were chosen, how training was configured and how performance was measured.</li><li><strong>Results &amp; Agent Behavior</strong>: algorithms’ financial performance versus the linear optimizer and examples of how the trained agent schedules charge and discharge in practice.</li><li><strong>Conclusion: </strong>final thoughts and takeaways.</li></ol><h3>Problem setting</h3><p>For this project, <strong>we focused on a real battery system: the </strong><a href="https://www.energy-storage.news/estonias-first-grid-scale-bess-to-come-online-in-2025-lg-to-supply-batteries/"><strong>Auvere battery</strong></a><strong> in northeastern Estonia.</strong> It was launched in 2025 and is currently the largest energy storage system in the country, <strong>with a maximum storage capacity of 50 MWh and a charging/discharging power limit of 26 MW per hour.</strong> We initialized the battery at 20 MWh charge level and applied simplified assumptions, such as a €10/MWh discharge cost (to reflect degradation) and a €50/MWh penalty for imbalances.</p><p><strong>The main goal was to train an RL agent to maximize trading profits </strong>by deciding when to charge or discharge the battery <strong>in the day-ahead electricity market.</strong> We also we wanted to compare its decision-making with that of a linear optimization approach and evaluate whether RL can achieve higher profits.</p><h3><strong>Simulated Environment</strong></h3><p>Reinforcement learning works by training an agent through interactions with an environment. At each step, the agent observes the state, takes an action, receives a reward as feedback, and updates its policy (the strategy for choosing actions) to improve future decisions. This environment can either be real or a simulation. Operating directly in a real environment, such as the day-ahead electricity market, is costly and risky, so we created a simulated environment using the <a href="https://gymnasium.farama.org/introduction/create_custom_env/">Gymnasium framework</a> that mimics the real market behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*lr2kOhvV8tMC_V0KTavZSg.png" /><figcaption>RL agent training loop using a simulated environment modeled on historical day-ahead electricity market data</figcaption></figure><p>To effectively simulate trading scenarios, the environment must clearly define several core components:</p><p>- <strong>Observation space</strong> : represents the information available to the agent at each step. It includes all the data needed to make an informed decision.</p><p>- <strong>Action space</strong> : defines the range of possible actions the agent can take, such as how much to charge or discharge.</p><p>- <strong>Execution logic</strong>: determines how the environment updates in response to an action, including physical constraints and market outcomes.</p><p>- <strong>Reward function</strong>: assigns a numerical value to the result of each agent’s action, accounting for trading profit and operational costs.</p><p>Below, we describe how each was implemented in our project.</p><h4>Observation space</h4><p><strong>In our ideal environment design</strong>, at each decision step, the agent’s observation includes:</p><ul><li>the current battery state of charge (SOC)</li><li>the 24 hours forecasted electricity prices</li></ul><p>This gives the agent a clear picture of both its own status and the expected market conditions. However, to simplify the learning process for this project, <strong>we replaced forecasts with actual historical prices</strong>, allowing the agent to operate with fully known price information. We also found it useful to include not only one-day prices but next-day prices as well, under the assumption that access to future information can help the agent become more robust and adaptable to varied market conditions.</p><pre># Example observation<br>example_obs = {<br>    &quot;battery_level&quot;: np.array([20.0], dtype=np.float32),<br>    &quot;prices_today&quot;: np.array([29.81666306, ... ,75.2629312], dtype=np.float32),<br>    &quot;prices_tomorrow&quot;: np.array([138.86421, ... ,170.58394], dtype=np.float32)<br>}</pre><p>To make this input suitable for a neural network, the structured observation is than flattened. As a result, we have a 49-dimensional input vector at each time step.</p><h4>Action space</h4><p>At each decision step, the agent outputs a 24-dimensional vector of real values, representing the planned charging or discharging power for each hour of the upcoming day. <strong>The action space is continuous, allowing any value between –26 and 26 MW, where negative values indicate discharging and positive values indicate charging.</strong> These actions directly affect both the battery’s energy level and the financial outcome.</p><h4>Execution logic</h4><p>After the agent has proposed its 24-hour trading schedule, <strong>the environment simulates how these decisions would play out in a realistic battery operation scenario. </strong><br>First, it calculates the potential bid revenues the agent would earn if the proposed actions were executed exactly as planned. This is done by multiplying the energy bought or sold each hour by the actual market price.</p><p>But plans don’t always match reality 🤭. So next, <strong>the environment checks whether the battery can physically follow the agent’s schedule.</strong> If the agent tries to overcharge or over-discharge, the actions are automatically adjusted to fit within the battery’s technical limits — its energy capacity (0 to 50 MWh) and max power flow (±26 MW). <strong>This gives us a valid schedule</strong>, and the battery’s SOC is updated hour by hour to reflect the true energy flow.</p><p>Next, the simulation checks for mismatches between the agent’s original schedule and what was actually feasible. These imbalances come with financial consequences:</p><ul><li>If the battery charged less than planned, the surplus energy is returned to the grid, but at a lower price.</li><li>If it didn’t discharge as expected, the missing energy has to be covered, but at a higher cost.</li></ul><p><strong>These imbalance adjustments simulate what happens in real markets when you don’t stick to your bids.</strong></p><p>Additionally, a degradation cost is applied to all discharged energy to reflect battery wear, calculated as a fixed cost per MWh.</p><p>Finally, the environment aggregates all these components into a<strong> single reward value</strong> for that step(described below). It also updates the battery’s SOC, loads the next day’s prices, and returns a new observation for the next training step.</p><h4>Reward function</h4><p>We define the <strong>reward function for each trading day as the total daily profit</strong>, calculated as:</p><blockquote>Reward = Bid Revenues + Imbalance Revenues — Degradation Cost</blockquote><p>It tells the agent how good its decisions were. Over time, these rewards guide the agent toward smarter strategies that <strong>aim to maximize trading profits during training</strong>.</p><p>In our project, we also <strong>scaled the rewards to fall within a smaller range</strong>, typically between [-1, 1]. This is a common best practice in RL, as it helps stabilize and speed up training. We experimented with several scaling methods and found that using a <strong>fixed scaling factor gave the best results</strong>.</p><p>The code snippet below demonstrates how a single step is executed within our simulation:</p><pre>import gymnasium as gym<br>from modules.price_generation import generate_sample_price_forecast<br>from modules.utils import (calculate_valid_schedule, calculate_imbalance_revenues)<br><br>class BatteryTradingEnv(gym.Env):<br><br>    ...<br><br>    def step(self, action):<br>        &quot;&quot;&quot;<br>        Executes one time step within the environment.<br>        Args:<br>            action (list[float]): Quantities of energy to charge or discharge for each of the 24 hours.<br>        Returns:<br>            tuple: Observation, reward, termination flag, truncation flag, and info dictionary.<br>        &quot;&quot;&quot;<br>        <br>        bid_revenues = sum(-qty * price for qty, price in zip(action, self.actual_prices_today))<br>        valid_schedule, final_battery_level = calculate_valid_schedule(action, self.battery_level)      <br>        imbalance_revenues = calculate_imbalance_revenues(action, valid_schedule, self.actual_prices_today)<br>        depreciation = sum(abs(action) for action in valid_schedule if action &lt; 0) * DEPRECIATION_COEFF   <br>      <br>        # reward calculation<br>        daily_revenue = bid_revenues + imbalance_revenues - depreciation<br>        policy_reward = daily_revenue <br>    <br>        self.battery_level = final_battery_level<br>        self.step_count += 1<br>        terminated = False<br>    <br>        # scale the reward <br>        if self.eval_mode:<br>            reward = policy_reward<br>        else:<br>            reward = policy_reward / CONSTANT_SCALE<br>    <br>        self.all_unscaled_rewards.append(policy_reward)<br>                    <br>        info = {}<br>        if not terminated: <br>            if self.days_in_month_counter &gt; 30:<br>                self.current_month = self.current_month % 12 + 1<br>                self.days_in_month_counter = 0<br>    <br>            # After each step, the state is updated: tomorrow&#39;s prices become today&#39;s prices, and new tomorrow&#39;s prices are generated.<br>            self.actual_prices_today = self.actual_prices_tomorrow<br>            forecast_prices_tomorrow, actual_prices_tomorrow = generate_sample_price_forecast(self.current_month, self.monthly_distributions)<br>            self.actual_prices_tomorrow = actual_prices_tomorrow<br>      <br>            self.days_in_month_counter += 1<br>    <br>            if not self.eval_mode:<br>                info[&quot;custom_data&quot;] = { &quot;unscaled_daily_reward&quot;: policy_reward,<br>                                        &quot;all_unscaled_rewards&quot;: self.all_unscaled_rewards}   <br>    <br>        observation = self._get_obs()<br>             <br>        return observation, reward, terminated, False, info</pre><h3><strong>Algorithm Selection &amp; Training</strong></h3><p>We chose two widely-used reinforcement learning algorithms: <a href="https://arxiv.org/abs/1509.02971"><strong>Deep Deterministic Policy Gradient (DDPG)</strong></a> and <a href="https://arxiv.org/abs/1707.06347"><strong>Proximal Policy Optimization (PPO)</strong></a>, and built our experiments using the <a href="https://docs.cleanrl.dev/">CleanRL library</a>. We selected DDPG because it is <strong>specifically designed for environments with continuous action spaces</strong>, making it a natural fit for battery control tasks — where the agent must decide exact power values for charging or discharging, rather than choosing from a set of predefined actions. DDPG is also an off-policy method, meaning it can use experiences generated by different policies, which makes training more efficient by allowing the algorithm to learn from replayed data. In contrast, PPO is an on-policy algorithm known for its training stability and robust performance across diverse RL problems. It also uses a stochastic policy, which naturally encourages exploration and helps avoid catastrophic policy collapses that can sometimes occur with purely deterministic algorithms. So, it provided a good baseline to compare against.</p><p><strong>While most of our experiments used the standard architectures from CleanRL for both algorithms, we found that DDPG performed best after we improved its architecture</strong> by adding Layer Normalization to both actor and critic networks and refining our input data processing( critic now processes the observation alone in its first layer and concatenates the action only after that transformation, rather than feeding state + action together from the start).</p><h4>Training process</h4><p>We trained our models using a <strong>continuous setup, where the agent interacts with the environment without having explicit episodic boundaries, mimicking uninterrupted real-world battery operation.</strong> After each simulated trading day, the agent received a daily reward reflecting its performance. Within this setup, learning proceeded step by step until a fixed total number of interactions is reached. Specifically, training was performed over 1000000 steps. To speed up the training, we used a single-node Databricks cluster with 28 GB RAM, 4 CPU cores, and an NVIDIA Tesla T4 GPU, which reduced average run-time to ≈3.5 hours per training session.</p><p>While daily rewards were useful for learning, they were not reliable for evaluating long-term performance due to the effects of reward scaling, exploration noise, and market volatility. So, <strong>we implemented our custom offline evaluation strategy</strong>. Every 10,000 steps, the model’s weights were frozen, exploration noise was turned off, and reward scaling was removed to show the true financial profits from the learned strategy. The policy was then tested in this deterministic setting using fixed synthetic price data for four representative months(January, April, July, October) to capture seasonal patterns. In each month, the model was evaluated over the 15 consecutive trading days. <strong>The main metric used for evaluation was Mean Return, calculated as the average profit over these four months.</strong></p><h3>Results</h3><p>Our experiments were conducted in a simplified version of the environment, where each observation included actual electricity prices for only 6 hours of the day instead of the full 24-hour horizon. At the end, we performed the evaluation on the full day horizon using the best achieved model. In all cases, performance was compared against a linear optimization benchmark to assess financial profits.</p><p><strong>We have done an extensive hyperparameter tuning for both PPO and DDPG algorithms</strong>, and the Table 1 below presents the best-performing configurations we were able to obtain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*ZENCkcZQaPFXcw1ifRgWrg.png" /><figcaption>Table 1. The blue table shows the DDPG hyperparams, and the red one shows PPO hyperparams</figcaption></figure><p>The results showed that even the tuned PPO underperformed the default DDPG(configured from CleanRL) by ≈12% in terms of mean revenues, with lower profits in every individual month. <strong>The best performance was achieved using a tuned DDPG model, which reached 85.5% of the optimizer’s mean return.</strong> Table 2 below shows how all the models performed in terms of financial profits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXWyZH9b1R9LFKzcdmuLKw.png" /><figcaption>Table 2. Comparative performance analysis of all the models</figcaption></figure><p>As we can see, tuning helped DDPG improve its mean revenue by <strong>24.5%</strong> compared to its default version, with consistent gains across all months. <strong>Still, even our best model didn’t quite catch up to the linear optimizer benchmark.</strong></p><p>When we returned to the full 24-hour setup and deployed the best DDPG configuration in this more complex environment, its <strong>mean revenues dropped to about 65% of the optimizer’s returns, compared to the 85% achieved in the simplified 6-hour case</strong>, see Table 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKjJ70n0N_oZAGPkW0qmfA.png" /><figcaption>Table 3. Comparative performance analysis of optimizer and the best DDPG model with a 24-hour horizon.</figcaption></figure><p>This performance degradation is <strong>likely due to the increased complexity introduced by extending both the input and output spaces</strong>, suggesting that further tuning and possible architectural modifications are needed for better performance in realistic settings.</p><h4>RL agent in action</h4><p>Finally, to understand the learned decision-making behavior of DDPG agent, let’s take a look at its battery trading actions on a single evaluation day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4SQK4_n7dT_sirkcizHxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWzCd6n-a5ZkNropqh-Ruw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEy6jQtQEhrAMSI0gzGwsA.png" /></figure><p><strong>The agent showed good general market awareness</strong> — charging the battery during low-price hours (like midnight to 3 AM and 9–11 AM) and discharging around local price peaks (such as 4–5 AM and 5–7 PM). Toward the end of the day, it even strategically filled the battery to max capacity, anticipating higher prices on the following day.</p><p><strong>However, the the main problem the agent has faced is its inability to focus trades strictly around global price extrema.</strong> Instead, it spread actions across the day, sometimes making poorly timed discharges during moderate-price hours where doing nothing might have been more profitable. Such trading behavior may result from limited feature information available to the agent, which currently relies only on price arrays without any additional context. This suggests room for improvement 😏— such as applying feature engineering to add useful signals like price ranks to the input, helping the agent better identify the most and least profitable hours to act.</p><h3>Conclusion</h3><p><strong>Reinforcement learning isn’t magic — but it does have potential.</strong> Our experiments show that with the right setup, an RL agent like DDPG can come close to traditional linear optimization when trading a battery in volatile electricity markets. And while RL didn’t outperform the benchmark in our study, it showed something more important: <strong>promise</strong>☺️.</p><p>In particular, RL has two advantages worth keeping in mind:</p><ul><li><strong>It’s better at handling uncertainty:</strong> Unlike traditional optimization, which relies on a price forecasts and treats them as ground truth, RL can learn from a variety of price trajectories and build strategies that are more robust to forecasting errors.</li><li><strong>Flexibility:</strong> RL policies can (in theory) learn from richer input data, like historical patterns or weather forecasts, without needing full knowledge of future prices.</li></ul><p>That said, RL is an empirical science with no guaranteed recipes. <strong>Results vary depending on how you design the environment, scale the rewards, structure your networks, and even how you define the task. Just tuning hyperparameters can take weeks or months.</strong></p><p>Finally, getting strong results starts with one key ingredient: the simulation environment. It must closely reflect real-world dynamics; otherwise, the agent may learn patterns that perform well in training but fail to generalize in practical applications.</p><p>RL can be powerful. But it takes patience, precision, and a lot of careful engineering. <strong>It’s worth asking whether your problem can be solved with a simpler method first — and turning to RL only when that’s no longer enough</strong>🙄<strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e9e43da7a11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enefitit/optimizing-battery-operations-with-reinforcement-learning-in-electricity-markets-4e9e43da7a11">Optimizing Battery Operations with Reinforcement Learning in Electricity Markets</a> was originally published in <a href="https://medium.com/enefitit">enefitit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>