<?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 Oguz Enver Uzan on Medium]]></title>
        <description><![CDATA[Stories by Oguz Enver Uzan on Medium]]></description>
        <link>https://medium.com/@oguzenveruzan?source=rss-b67ce03605ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Jf1ouLSn8IrdDHNShEdXPQ.jpeg</url>
            <title>Stories by Oguz Enver Uzan on Medium</title>
            <link>https://medium.com/@oguzenveruzan?source=rss-b67ce03605ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:11:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oguzenveruzan/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[Brain CT Hemorrhage Detection and Segmentation]]></title>
            <link>https://medium.com/@oguzenveruzan/brain-ct-hemorrhage-detection-segmentation-75b50e33bdfc?source=rss-b67ce03605ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/75b50e33bdfc</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[medical-imaging]]></category>
            <dc:creator><![CDATA[Oguz Enver Uzan]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 09:19:00 GMT</pubDate>
            <atom:updated>2026-10-30T09:19:00.009Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Intracranial hemorrhage classification and segmentation with EfficientNetB0 and U-Net. Patient-level splitting, patient-level confidence intervals and an interpretability analysis show the limits of an 82-patient dataset.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JL_GEJQ_Eggc3TnVnCPVWQ.png" /><figcaption>(five hemorrhage types: raw CT slice on top, radiologist mask below)</figcaption></figure><p><strong>Note:</strong> This work is for education and research purposes only. The models developed here are not clinical diagnostic tools.</p><h3>Summary</h3><p>In a CT scan taken after head trauma, the presence and location of a hemorrhage directly affect treatment decisions. In this study, I developed deep learning models for two tasks on an open dataset of 82 patients: (1) classifying whether each CT slice contains a hemorrhage (EfficientNetB0, transfer learning) and (2) pixel-level segmentation of the hemorrhage region in hemorrhagic slices (U-Net).</p><p>Key findings:</p><ul><li><strong>Classification (slice level):</strong> ROC-AUC 0.806 (95% CI: 0.665 to 0.917), PR-AUC 0.301, sensitivity 0.63, specificity 0.812</li><li><strong>Classification (patient level):</strong> ROC-AUC 0.714 (17 test patients)</li><li><strong>Segmentation:</strong> mean Dice 0.224, mean IoU 0.149; the hemorrhage was missed entirely in 38.9% of test slices</li><li><strong>Interpretability:</strong> Grad-CAM heatmaps did not overlap with the true hemorrhage region in three of the four correct predictions I examined</li></ul><p>The results are insufficient for clinical use. The contribution of this article is to show, with concrete data, how results on small medical datasets can be inflated and how to prevent it.</p><p>All the code and outputs are in my Kaggle notebook:</p><p><a href="https://www.kaggle.com/code/oguzuzan/brain-hemorrhage-detection-seg-u-net">🧠 Brain Hemorrhage Detection &amp; Seg (U-Net)</a></p><h3>1. Motivation</h3><p>In acute traumatic brain injury, CT is the first-line imaging method. A radiologist reviews dozens of slices to answer two questions: is there a hemorrhage, and where is it? Time is critical in this process. AI-assisted systems can help with prioritization (triage) and as a second reader. However, the reliability of such systems, especially on small datasets, requires careful evaluation.</p><p>I addressed two questions in this study:</p><ol><li>With a correct patient-level evaluation, what performance can be reached on a dataset of 82 patients?</li><li>Are the model’s decisions based on the hemorrhage itself, or on other cues?</li></ol><h3>2. Dataset</h3><p>The dataset used is <em>Computed Tomography Images for Intracranial Hemorrhage Detection and Segmentation</em>, published on PhysioNet (Hssayeni, 2019; CC BY 4.0). It contains CT scans of 82 patients who had traumatic brain injury in 2018 at a teaching hospital in Iraq. <strong>36 of the patients have a hemorrhage.</strong></p><ul><li>About 30 slices per patient (5 mm thickness), <strong>2,501 slices</strong> in total</li><li>Each slice was labeled by two radiologists; hemorrhage regions were outlined by hand</li><li>Five hemorrhage types: intraventricular, intraparenchymal, subarachnoid, epidural, subdural; fracture information is also provided</li><li>The radiologists did not see the patient’s clinical history</li></ul><p><strong>Data limitation:</strong> The images are 650×650 JPGs. Because they were converted from the original DICOM files, Hounsfield (HU) values are lost, and the images were pre-windowed and compressed to 8 bits. This can limit the performance the model can reach.</p><h3>2.1 Data integrity checks</h3><p>Before training any model I ran these checks:</p><ul><li>The SHA-256 hashes of 40 randomly selected files were compared with the official list: <strong>all 40 matched.</strong></li><li>There are no missing or duplicate records; all images have the same size and are readable. (One bone-window image is missing; since the brain window was used for the analysis, this has no effect.)</li><li>There are <strong>318 hemorrhagic slices and 318 masks</strong>; none of the 2,183 normal slices has a mask. Labels and masks are consistent.</li><li>Patient labels derived from two separate CSV files (slice level and patient level) show no mismatch.</li><li>25 slices contain more than one hemorrhage type. Since the target is binary classification, this is not an obstacle.</li></ul><h3>2.2 Class imbalance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ws9PiaZLVggKKpoAfyrKTw.png" /><figcaption><em>Class distribution at the slice level (left) and slice counts by hemorrhage type (right).</em></figcaption></figure><p>About 87% of the slices are normal. Therefore, a baseline model that classifies every slice as “normal” reaches an accuracy of <strong>89.3%</strong> on the test set while catching <strong>0%</strong> of hemorrhages. Accuracy is not an informative metric for this problem. So the evaluation relies on <strong>ROC-AUC, PR-AUC, sensitivity and specificity</strong>, and class weights were used in training. Because some hemorrhage types appear in only a few patients, type classification was not attempted.</p><h3>3. Evaluation design: patient-level splitting</h3><p>One of the most common methodological errors in medical imaging is <strong>data leakage</strong>. In the plot below, each row is a patient and each column is a slice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aU1aPpZ5WD_7UiLv2Gm14A.png" /><figcaption><em>Patient × slice label map. The hemorrhage (red) forms a continuous block across a patient’s consecutive slices.</em></figcaption></figure><p>Consecutive slices contain almost the same image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXsLBqDBH0qzv1jTtyRsSQ.png" /><figcaption><em>All slices of one patient. Note how similar consecutive slices are.</em></figcaption></figure><p>If slices are distributed randomly into training and test sets, neighboring slices of the same patient end up in both. The model memorizes the patient and the test score comes out higher than the real performance. Therefore the split was done at the <strong>patient level</strong>: all slices of a patient are in a single set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ryCMsmjAXDoEhs73v-Qzg.png" /><figcaption><em>Patient-level training / validation / test split.</em></figcaption></figure><ul><li><strong>Training:</strong> 48 patients, 1,478 slices (196 hemorrhagic slices, 21 hemorrhagic patients)</li><li><strong>Validation:</strong> 17 patients, 517 slices (68 hemorrhagic slices, 8 hemorrhagic patients)</li><li><strong>Test:</strong> 17 patients, 506 slices (54 hemorrhagic slices, <strong>7 hemorrhagic patients</strong>)</li></ul><p>The seven hemorrhagic patients in the test set mean that all test results must be interpreted with a wide margin of uncertainty.</p><h3>3.1 Why deep learning?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_KTyqROAOcC7kwLgo9XUQ.png" /><figcaption><em>Gray-value distributions of the hemorrhage region and of non-masked brain tissue in the same slices.</em></figcaption></figure><p>The mean gray value is 158.7 in the hemorrhage region and 144.3 in non-masked tissue, but the distributions overlap substantially. Pixel brightness alone cannot separate a hemorrhage. In addition, hemorrhages are small:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JXRBYcSCg3VUmmdXcmmUw.png" /><figcaption><em>Distribution of hemorrhage mask areas (percentage of image area).</em></figcaption></figure><p>The median hemorrhage area is 0.41% of the image, the mean is 0.73% and the maximum is 4.16%. In the training set, hemorrhage pixels make up only <strong>0.77%</strong> of all pixels. This indicates a severe pixel-level imbalance for segmentation.</p><h3>4. Classification</h3><h3>4.1 Method</h3><p>Training from scratch with only 36 hemorrhagic patients is not reliable, so I applied transfer learning with <strong>EfficientNetB0</strong> (about 4 million parameters) pretrained on ImageNet. Training has two stages:</p><ol><li><strong>Head training (10 epochs):</strong> The pretrained backbone is frozen and only the new classification head is trained.</li><li><strong>Fine-tuning (15 epochs):</strong> The last 30 layers of the backbone are unfrozen and trained with a low learning rate (1e-5); BatchNorm layers stay frozen.</li></ol><p>Grayscale images were copied to 3 channels. Augmentation used horizontal flips plus slight rotation, shifting and zooming (vertical flips were not applied because of anatomical orientation). Class weights were used for the rare class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3IzuGjdeM8wt-NGBMp0jg.png" /><figcaption><em>Classification training curves. Validation curves are noisy because of the small number of hemorrhagic patients in the validation set.</em></figcaption></figure><p>Validation AUC rose from about 0.82 to 0.89 during head training and to about 0.90 with fine-tuning.</p><h3>4.2 Choosing the decision threshold</h3><p>In a medical context, a missed hemorrhage is more costly than a false alarm. Therefore the <strong>F2 score</strong>, which weights sensitivity twice as much, was used, and the threshold was chosen on the <strong>validation set</strong> without looking at the test set: <strong>0.49.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*GKDvWfl8v_poa-to-2S-NQ.png" /><figcaption><em>Threshold selection on the validation set (F2 score).</em></figcaption></figure><h3>4.3 Test results (slice level)</h3><p>The test set was evaluated only once:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfypAKrbV6yjOb2Q7f7UOw.png" /><figcaption><em>Test set: confusion matrix, ROC curve and Precision-Recall curve.</em></figcaption></figure><ul><li><strong>ROC-AUC:</strong> 0.806</li><li><strong>PR-AUC:</strong> 0.301 (the random-guess baseline is about 0.11)</li><li><strong>Sensitivity:</strong> 63% (34 of 54 hemorrhagic slices caught, 20 missed)</li><li><strong>Specificity:</strong> 81.2% (85 false alarms among 452 normal slices)</li><li><strong>Precision:</strong> 0.286</li><li><strong>Accuracy:</strong> 79.2%</li></ul><p>The model’s accuracy (79.2%) is lower than that of the baseline that calls every slice “normal” (89.3%), but that baseline catches no hemorrhage at all. The evaluation should therefore be made through sensitivity, specificity and AUC. On the other hand, only about 29% of the slices the model calls hemorrhagic actually are, which is insufficient for clinical use.</p><h3>4.4 Uncertainty: patient-level bootstrap</h3><p>Because the test set is small, the confidence interval for ROC-AUC was computed with a <strong>patient-level bootstrap</strong> (resampling was done at the patient level because slices from the same patient are dependent):</p><p><strong>ROC-AUC = 0.806 (95% CI: 0.665 to 0.917)</strong></p><p>The wide interval shows that a change in the class of a few patients could change the result substantially.</p><h3>4.5 Patient-level decision</h3><p>The clinical question is at the patient level, not the slice level. Slice probabilities were aggregated to the patient level with three methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgQvraIUuubE2tKH5YhxIA.png" /><figcaption><em>Patient-level decision: three aggregation methods.</em></figcaption></figure><ul><li><strong>Maximum:</strong> ROC-AUC 0.714; 9 of 17 patients correct</li><li><strong>Mean of the top 3 slices:</strong> 0.714; 10 of 17 patients correct</li><li><strong>Mean of all slices:</strong> 0.729; 11 of 17 patients correct</li></ul><p>Patient-level performance is weaker than slice-level performance and rests on only 17 patients. This model does not make reliable decisions at the patient level.</p><h3>5. Interpretability and error analysis</h3><h3>5.1 Grad-CAM</h3><p>Grad-CAM was used to examine what the model bases its decisions on. Below are correctly predicted hemorrhagic test slices; the yellow outline is the hemorrhage region drawn by the radiologist:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4uZ-scKsu7n8AVLMAbKroA.png" /><figcaption><em>Correctly predicted hemorrhagic test slices (top) and Grad-CAM heatmaps (bottom). Yellow outline: radiologist mask.</em></figcaption></figure><p><strong>In three of the four examples, the heatmap does not overlap with the true hemorrhage region:</strong></p><ul><li>In the first two examples (Patient 85), the heat concentrates in a broad area in the middle of the brain and does not focus on the small hemorrhage outline.</li><li>In the fourth example (Patient 68), the heat highlights the lower region while the hemorrhage is in the upper left.</li><li>In the third example (Patient 50), the heat is near the hemorrhage region, but it also seems influenced by bright structures at the edge of the skull.</li></ul><p>Although the model produced high probabilities of 0.95 to 0.98 on these slices, it is possible that the decision rests not on the hemorrhage itself but on general characteristics of the patient, such as age or head shape. This is a suspicion, not proof: Grad-CAM is only a qualitative tool and four examples are a small sample. Still, I could not find evidence supporting the conclusion that the model learned the hemorrhage.</p><h3>5.2 Error analysis</h3><p>The initial hypothesis was that missed hemorrhages would be smaller lesions. The data did not support it:</p><ul><li><strong>Missed hemorrhagic slices (FN): 20</strong>; <strong>false alarms (FP): 85</strong></li><li>Median hemorrhage area in missed slices: <strong>0.39%</strong></li><li>Median area in correctly caught slices: <strong>0.29%</strong></li></ul><p>Missed hemorrhages are not smaller than caught ones. The reason for missing them may relate more to location, appearance or patient-specific characteristics than to lesion size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o582nLGzDfl6j_0ddlvVkQ.png" /><figcaption><em>Examples of missed hemorrhages (FN)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8WoW2Bqd_lDBPPbDILmE_A.png" /><figcaption><em>Examples of false alarms (FP)</em></figcaption></figure><h3>6. Segmentation</h3><h3>6.1 Method</h3><p>Because masks exist only in hemorrhagic slices, segmentation was trained with <strong>318 slices</strong> (196 training, 68 validation, 54 test); the split is <strong>the same patient split</strong> as in classification. Images were resized to 256×256; masks were resized with nearest-neighbor interpolation.</p><p>Because data is limited, a small <strong>U-Net</strong> was used (16 to 256 filters, <strong>1,945,233 parameters</strong>). The loss function is <strong>BCE + Dice</strong>; since hemorrhage pixels make up only 0.77% of the total, using BCE alone could push the model toward predicting background.</p><ul><li><strong>Dice = 2|A ∩ B| / (|A| + |B|)</strong></li><li><strong>IoU = |A ∩ B| / |A ∪ B|</strong></li><li>Total loss = BCE + (1 − Dice)</li></ul><p>In augmentation, the image and mask received the same geometric transformation (they were combined in a single 2-channel tensor); brightness changes were applied to the image only.</p><h3>6.2 Training</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CE9EzvQ_5d8qjD2jMg_X0A.png" /><figcaption><em>U-Net training. Left: BCE + Dice loss. Right: Dice coefficient (training in blue, validation in red).</em></figcaption></figure><p>Training Dice reached about <strong>0.75</strong>, while validation Dice stayed at about <strong>0.41</strong>. This gap indicates clear overfitting.</p><h3>6.3 Test results</h3><p>Dice was computed separately for each test slice:</p><ul><li><strong>Mean Dice:</strong> 0.224; <strong>median Dice:</strong> 0.172; <strong>mean IoU:</strong> 0.149</li><li>Share of slices with Dice &gt; 0.5: <strong>16.7%</strong></li><li>Share of slices where the hemorrhage was <strong>missed entirely</strong> (Dice &lt; 0.05): <strong>38.9%</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*072GkWtZ7yS8vVIyFO3pBw.png" /><figcaption><em>Left: Dice distribution per slice. Middle: relationship between lesion size and Dice. Right: predicted versus true area.</em></figcaption></figure><p>The Dice distribution clusters at the two ends: 38.9% of slices are near zero and a small portion is above 0.5. Dice tends to increase as the lesion grows, but the relationship is not clear; some large lesions also received low scores. In some slices, the model also marked a much larger area than the true one, which was very small (over-prediction).</p><h3>6.4 Qualitative review: worst, median and best examples</h3><p>Since showing only successful examples would be misleading, the <strong>worst, median and best</strong> examples from the test set by Dice are presented:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJ2CkRLb7U_-Ddj8e9CDYw.png" /><figcaption><em>Right column: green = model and radiologist agree, blue = model marked but radiologist did not, red = radiologist marked but model missed.</em></figcaption></figure><ul><li><strong>Worst (Patient 85, Dice 0.00):</strong> The model misses the real hemorrhage and makes false markings in other regions.</li><li><strong>Median examples (Dice 0.17 to 0.18):</strong> The model captures only a small portion of the lesion.</li><li><strong>Best (Patient 84, Dice 0.83):</strong> The lesion is clustered and distinct; the model identifies nearly all of it correctly.</li></ul><p>The model performs better on distinct, single-piece hemorrhages and worse on fragmented and small ones.</p><h3>7. Discussion and limitations</h3><p>The strength of this study is that the results are not inflated: patient-level splitting, threshold selection on the validation set, a single use of the test set and patient-level confidence intervals. The weaknesses are overfitting, weak patient-level performance, and the suspicion from the interpretability analysis that the model does not decide for the right reasons.</p><p>Limitations:</p><ol><li><strong>Very small sample.</strong> 82 patients, 36 with hemorrhage; only 7 hemorrhagic patients in the test set. Confidence intervals are wide.</li><li><strong>Single center, single scanner.</strong> There is no external validation.</li><li><strong>Young, trauma-based population.</strong> The median age is 18 for hemorrhagic patients and 31 for the normal group (Mann-Whitney p = 0.062). Generalization to spontaneous hemorrhages in older patients should not be expected.</li><li><strong>JPG format and HU loss.</strong> Original Hounsfield values and multi-window information are not available.</li><li><strong>Rare hemorrhage types.</strong> Type-level classification is not reliable.</li><li><strong>Single split.</strong> Results may depend on which patients fell into the test set.</li><li><strong>2D model.</strong> Neighboring-slice context was not used.</li><li><strong>Limited interpretability analysis.</strong> Grad-CAM was reviewed qualitatively on only four examples.</li></ol><h3>8. Conclusion</h3><p>This study establishes three main points:</p><ol><li><strong>Patient-level splitting is mandatory on small medical datasets.</strong> Because consecutive slices are nearly identical, slice-level splitting artificially inflates results.</li><li><strong>Accuracy is misleading on imbalanced medical data.</strong> A baseline that calls every slice “normal” reaches 89% accuracy while catching no hemorrhage. Results should be reported together with sensitivity, specificity, AUC and confidence intervals.</li><li><strong>A correct high-probability prediction is not proof that it rests on the right reason.</strong> Grad-CAM heatmaps mostly did not overlap with the true hemorrhage region; the model may be relying on the wrong features.</li></ol><p>The performance achieved is insufficient for clinical use, but the limits of the method have been made explicit. Thanks for reading. Leave your questions in the comments.</p><p>All the code:</p><p><a href="https://www.kaggle.com/code/oguzuzan/brain-hemorrhage-detection-seg-u-net">🧠 Brain Hemorrhage Detection &amp; Seg (U-Net)</a></p><h3>References</h3><ul><li>Hssayeni, M. (2019). <em>Computed Tomography Images for Intracranial Hemorrhage Detection and Segmentation.</em> PhysioNet. <a href="https://doi.org/10.13026/w8q8-ky94">https://doi.org/10.13026/w8q8-ky94</a> (CC BY 4.0)</li><li>Hssayeni, M. D. et al. (2020). <em>Intracranial Hemorrhage Segmentation Using a Deep Convolutional Model.</em> Data, 5(1), 14.</li><li>Tan, M., &amp; Le, Q. (2019). <em>EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks.</em> ICML.</li><li>Ronneberger, O., Fischer, P., &amp; Brox, T. (2015). <em>U-Net: Convolutional Networks for Biomedical Image Segmentation.</em> MICCAI.</li><li>Selvaraju, R. R. et al. (2017). <em>Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization.</em> ICCV.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75b50e33bdfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Grew a Flower from a Single Cell: A Neural Network That Heals Its Own Wounds]]></title>
            <link>https://medium.com/@oguzenveruzan/neural-cellular-automata-self-healing-236f3e6905a1?source=rss-b67ce03605ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/236f3e6905a1</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cellular-automata]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Oguz Enver Uzan]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 14:09:30 GMT</pubDate>
            <atom:updated>2026-10-28T14:09:30.303Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A tiny neural network with 8,320 parameters grows a pattern from one live pixel and repairs it after damage. Ablation experiments show which training tricks make it work.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*QRLmaxNNNyz3Cp0cLdfizA.gif" /><figcaption>target pattern and the NCA growing from a single cell side by side, with damage and repair in the middle</figcaption></figure><p>An egg starts as a single cell. That cell divides, multiplies and eventually becomes a creature with a heart, eyes and fingers. No individual cell knows the blueprint of the whole body. Each one looks only at its neighbors and follows the same DNA. Even more remarkable, a salamander that loses a limb can run the same process again and grow it back.</p><p>In this article I built an artificial version of that idea. Every pixel is a “cell”, all of them <strong>share the same small neural network</strong>, and each one sees only its 3×3 neighborhood. The system starts from one live pixel, builds the target pattern, and repairs itself when part of the pattern is erased.</p><p>The method comes from the 2020 Distill article <em>Growing Neural Cellular Automata</em> by Mordvintsev and colleagues. <strong>I am not proposing a new method.</strong> My goal was to examine it in a measurement-focused, reproducible way: how large a wound can it repair, does it degrade when it runs for a long time, and which parts of the training recipe actually matter?</p><p>All the code and outputs are in my Kaggle notebook:</p><p><a href="https://www.kaggle.com/code/oguzuzan/growing-neural-cellular-automata-self-healing">🦎 Growing Neural Cellular Automata: Self Healing</a></p><h3>Four questions I wanted to answer</h3><ol><li>How does a purely local rule produce a coherent global pattern?</li><li>How large a wound can the system repair, and what happens when the damage is bigger than anything it saw in training?</li><li>Does the pattern stay stable forever, or does it degrade over time?</li><li>Which training components (sample pool, damage, asynchronous updates, number of hidden channels) are really necessary?</li></ol><h3>How do the cells think?</h3><h3>Every pixel carries 16 numbers</h3><p>The grid is 72×72 pixels: a 40×40 target image with a 16-pixel margin of empty space around it for growth. Each pixel carries a 16-channel <strong>state vector</strong>. The first four channels are the visible color and transparency (RGBA), and the remaining <strong>12 channels are hidden</strong>. The hidden channels are the communication line cells use to pass messages to each other, one we never see.</p><h3>One update step has four parts</h3><ol><li><strong>Perception (not learned).</strong> Three fixed filters: identity, Sobel-x and Sobel-y. Each cell sees its own value and the <em>gradient</em> in its neighborhood. In other words, “what is on my right, what is on my left” is handed to it by hand.</li><li><strong>Update network (learned).</strong> A 1×1 convolution (48 → 128), a ReLU, and another 1×1 convolution (128 → 16). The same small MLP is applied to every pixel. In total there are <strong>8,320 parameters</strong>.</li><li><strong>Stochastic mask.</strong> At each step only half of the cells (fire_rate=0.5) are updated. There is no global clock, so the cells run asynchronously.</li><li><strong>Alive masking.</strong> A pixel with no neighbor whose alpha is above 0.1 is considered “dead” and reset to zero.</li></ol><p>The final layer is <strong>initialized to zeros</strong>. At the start of training the system does nothing at all, which gives it a stable starting point.</p><h3>Why does such a small network matter?</h3><p>8,320 parameters is fewer than the number of pixels in a single photo. This network has no concept of a “pattern”: the only thing each cell knows is its neighbors. Yet because every cell applies the same rule, a global shape emerges. You can watch it happen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qI02t_GgPyFp0JFvOddK2A.png" /><figcaption><em>Top row: growth from a single cell to the pattern (t = 0 to 150). Bottom row: after the pattern matures, a region is erased and then repaired.</em></figcaption></figure><h3>Training: four tricks</h3><p>If you train this system by simply minimizing MSE, you run into trouble. Train it directly from a single cell and the model learns to reach the target, but not to <strong>stay</strong> there. So four techniques are used:</p><ul><li><strong>Sample pool.</strong> Eight samples are drawn at random from a pool of 512, run for a number of steps, and the results are written back to the pool. The worst sample is replaced by a fresh seed (a single cell) every time. This way the model sees not only how to build the pattern, but also how a mature pattern should hold still.</li><li><strong>Damage.</strong> In 3 of the 8 samples in each batch, a random circular region with a radius of 6 to 14 pixels is erased. The ability to repair comes from here.</li><li><strong>Gradient normalization.</strong> Backpropagation runs through dozens of time steps, so gradients can explode. Each parameter’s gradient is clipped to unit norm.</li><li><strong>Random step count.</strong> Each iteration runs between 64 and 96 steps, so the model cannot memorize a particular number of steps.</li></ul><p>The loss is the pixel-wise <strong>MSE</strong> between the predicted RGBA and the target RGBA. I used the Adam optimizer with a learning rate of 2e-3, multiplied by 0.3 at 50% and 80% of training, for 3,000 iterations in total.</p><h3>Results 1: Growth</h3><p>Training took about <strong>9.6 minutes</strong> on a Kaggle T4 GPU. The loss fell from 0.096 to <strong>0.0043</strong> (mean of the last 100 iterations).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fI7ufwu8fynvAEh1UcBzog.png" /><figcaption><em>Training loss (log scale). Light line: raw values. Dark line: 50-iteration moving average.</em></figcaption></figure><p>The loss curve is noisy but clearly heading down. The noise is expected: some of the samples drawn from the pool are damaged and some are fresh seeds.</p><p>Here are the growth stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJ5L1tpv6JPUOZfPKbHeEQ.png" /><figcaption><em>From a single cell to the target pattern: t = 0, 5, 10, 20, 40, 80, 150 and 250.</em></figcaption></figure><p>In the early steps (t = 10 to 20) the cells form a dark, colorful, chaotic clump. At t = 40 there is a round mass. By t = 80 the flower has taken its six-petal shape, and at t = 150 it is sharp. It looks the same at t = 250. The growth MSE is <strong>2.7 × 10⁻³</strong>.</p><p>The order resembles biological growth: first an undefined cluster of cells, then the main shape, then the fine details.</p><h3>The secret language of cells</h3><p>The color we see is only 4 channels. What about the other 12?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*QSlMqBSQEuUwa5vwS45YBg.gif" /><figcaption><em>Left: the visible output. Right: the 12 hidden channels (channels 4 to 15) over time.</em></figcaption></figure><p>The hidden channels are not random noise. Each seems to highlight a different region or ring of the flower: one lights up the center, another the outer edge, another the petal tips. I did not assign these channels any meaning, and I don’t know what they are “saying”. The network built them on its own. It is reasonable to read them as carrying position information such as “this is the center, this is the edge”, but I did not test that directly.</p><h3>Results 2: Repair</h3><p>This is the exciting part. Once the pattern is mature (t = 150), I erase a circular region and watch what the system does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOiuht0PSf0wSH7x7Kjjaw.png" /><figcaption><em>Just before the damage, just after, and 10, 20, 40 and 80 steps later.</em></figcaption></figure><p>The cells fill the erased region from the edge inward. At 10 to 20 steps a colorful ring appears at the edge of the wound, and by 40 to 80 steps it spreads inward. To be honest, the repair is <strong>not perfect</strong>: at +80 steps the repaired area is still a bit speckled and the yellow center is blurrier than the original. Even so, the overall shape and colors of the flower come back. After r = 10 damage, the repair MSE is <strong>3.8 × 10⁻³</strong>, close to the growth MSE of 2.7 × 10⁻³.</p><h3>What happens as the damage grows?</h3><p>During training the damage radius was between 6 and 14. I deliberately tested outside that range (r = 16 and 20): can it repair damage of a size it never saw?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LajNNkcOugau21T0Foh_BA.png" /><figcaption><em>Left: repair error by damage radius (damage at t = 120). Right: long-term stability over 2,000 steps (the gray band is the step range seen in training).</em></figcaption></figure><p>Error after repair (at step 250):</p><ul><li><strong>r = 4:</strong> 2.6 × 10⁻³ (almost no trace)</li><li><strong>r = 8:</strong> 2.8 × 10⁻³</li><li><strong>r = 12:</strong> 4.9 × 10⁻³ (inside the training range, good repair)</li><li><strong>r = 16:</strong> 1.1 × 10⁻² (outside the training range, partial repair)</li><li><strong>r = 20:</strong> 3.0 × 10⁻² (outside the training range, insufficient repair)</li></ul><p>The notebook’s success criterion was “repair error must not exceed 3 times the growth error”. By that standard, <strong>the largest damage repaired successfully is r = 12</strong>, which is inside the training range. Outside it, the system still reduces the damage partially (the error drops right after the hit), but it quickly falls short. So generalization is not free: <strong>the model repairs about as much damage as it saw in training.</strong></p><h3>Does the pattern last forever?</h3><p>In theory an NCA can run indefinitely, but the model saw only about 100 steps during training. The right-hand chart shows 2,000 steps.</p><p>The error first drops quickly, reaches its lowest point around step 150, then rises <strong>slowly and steadily</strong>. The error of 2.6 × 10⁻³ at step 100 becomes 9.4 × 10⁻³ at step 2,000 (about 3.6 times higher). This is not an explosion but a slow drift: the pattern stays recognizable for hundreds of steps, but the cells gradually move away from the target. The notebook’s own criterion flagged this as “degrades in the long run”, and that is the right way to read it. <strong>Stability is not guaranteed by training; it is only something the measurement shows.</strong></p><h3>Results 3: Ablation, which parts are really needed?</h3><p>Not every component of a method matters equally. Each time I changed a single factor and retrained with the same budget (<strong>1,500 iterations</strong>, <strong>3 different seeds</strong>):</p><ul><li><strong>baseline:</strong> the reference</li><li><strong>no_pool:</strong> no sample pool, always start from the seed</li><li><strong>no_damage:</strong> no damage during training</li><li><strong>fire_0.25 / fire_1.0:</strong> 25% / 100% of cells updated per step</li><li><strong>ch_8 / ch_32:</strong> 8 / 32 channels (baseline is 16)</li></ul><p>Each experiment gets three error measurements (lower is better): grow_mse (growth after 96 steps), regen_mse (96 steps after an r = 10 injury) and stability_mse@1000 (after 1,000 steps).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etoYNZqsvPFNjaXS74auCg.png" /><figcaption><em>Ablation error metrics (log scale, lower is better). Green: baseline. Error bars show the standard deviation across seeds.</em></figcaption></figure><h3>Baseline</h3><p>Growth 5.6 × 10⁻³, repair 6.0 × 10⁻³, and 7.3 × 10⁻³ after 1,000 steps. These ablations ran with half the budget (1,500 iterations) of the main model (3,000 iterations), so they are coarser.</p><h3>Removing the sample pool breaks everything</h3><p>The no_pool model’s <strong>training loss is lower than the baseline’s</strong> (0.0063 versus 0.0082). So during training it looks better. But:</p><ul><li>Growth error: 7.5 × 10⁻³ (close to baseline)</li><li>Repair error: <strong>0.158</strong>, about <strong>26 times</strong> the baseline</li><li>Error after 1,000 steps: a mean of <strong>about 3 × 1⁰³¹</strong>. In other words, at least one seed truly blows up.</li></ul><p>This is the most instructive result of the ablation: <strong>training loss does not show the model’s real condition.</strong> The pool-free model learns to go from the seed to the target in 64 to 96 steps, but it never learns to stop at the target. The loss looks good while the system is not stable. This is live proof of the “learning to stop” problem I described at the start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wA4o5gpOwHAR8To15DSOWA.png" /><figcaption><em>Ablation training loss curves. </em><em>no_pool (orange) looks lower at the beginning and also later, but that is not an indication of stability.</em></figcaption></figure><h3>Train without damage</h3><p>The no_damage model is <strong>better</strong> at growth (3.8 × 10⁻³ versus 5.6 × 10⁻³), which makes sense because everything is devoted to growth. At repair it is <strong>about 3 times worse</strong> than baseline (0.0176 versus 0.0060). That value is close to the error measured right after an r = 10 injury in the main model (roughly 0.01 to 0.025 from the chart), so a model trained without damage most likely repairs almost nothing. I did not measure this directly; it is my reading of the chart. Either way the message is clear: <strong>the ability to repair does not appear on its own; you have to show the model damage during training.</strong></p><h3>Asynchronous updates: the opposite of what I expected</h3><p>The literature suggests fully synchronous updates (fire_rate=1.0) should be more fragile. In my measurement it was the opposite: <strong>fire_1.0 was clearly better than baseline on all three metrics</strong> (growth ×0.30, repair ×0.54, stability ×0.43). fire_0.25 was worse at growth (×1.71) and within seed noise on the other two.</p><p>I don’t know the exact reason. One possible explanation: when only half the cells update per step, the same number of steps does half as much work, and with a half-size budget (1,500 iterations) that gap may have been magnified. I did not test this; it would need longer training and more seeds. So rather than saying “asynchronous is bad” or “synchronous is good”, I say: <strong>in this budget, synchronous came out better.</strong></p><h3>Number of channels</h3><p>ch_8 (4,224 parameters) is worse than baseline on all three metrics (roughly ×1.4 to ×1.6). ch_32 (16,512 parameters) is clearly better at growth (×0.69), while the differences in repair and stability are within seed noise. So too few channels has a cost, but doubling the channels does not give a dramatic jump either.</p><h3>Reading the ablation correctly</h3><p>These results have limits: only 3 seeds, half the training budget, and a rough criterion that calls a difference “noticeable” if it is larger than twice the seed standard deviation. That is not a formal statistical test. The most solid results are no_pool and no_damage, where the differences are huge. fire_1.0 is a surprise, but not a certain one.</p><h3>Same rule, different targets</h3><p>I trained four more targets separately, with the same architecture and hyperparameters (2,000 iterations each): a heart, a star, a smiley face and a flower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69FX1RcqpyHsqmEj-vC6NA.png" /><figcaption><em>Each column is a separate model. Rows: target, growth, damage, repair.</em></figcaption></figure><p>Growth errors: star 0.0005, heart 0.0015, smiley 0.0040, flower 0.0045. Simple shapes with large color regions, like the heart and the star, are easy. The <strong>smiley face</strong> is harder: the eyes and mouth stay blurry and the fine details are lost. The star’s repair also leaves a small smudge on the left edge.</p><h3>Limitations</h3><ol><li><strong>Each model produces a single image.</strong> Multi-target training was not done.</li><li><strong>Low resolution (40×40).</strong> As resolution grows, the step count and memory cost rise quickly, because backpropagation runs through all the steps.</li><li><strong>Stability is not guaranteed.</strong> Only about 100 steps were seen in training; long-term behavior is reported by measurement only.</li><li><strong>Limited statistical power.</strong> Ablations used few seeds and short training; small differences may be noise.</li><li><strong>MSE does not fully capture perceptual quality.</strong> Subtle edge shifts can look small in MSE.</li><li><strong>A narrow damage distribution.</strong> Training used only circular damage with a radius of 6 to 14; robustness to other damage shapes was not tested.</li></ol><h3>Next steps</h3><ul><li><strong>Multi-target:</strong> generate several patterns from a single network by feeding the target identity into the seed channel.</li><li><strong>Self-classifying MNIST:</strong> have cells classify a digit together through local communication.</li><li><strong>Texture synthesis:</strong> train with VGG feature statistics (Gram matrix) instead of a fixed target image.</li></ul><h3>Three takeaways</h3><ol><li><strong>A local rule, a global pattern.</strong> A rule with 8,320 parameters, identical in every cell, can grow a whole pattern from a single cell and repair damage.</li><li><strong>Training loss alone can lie.</strong> The model without a sample pool trained to a lower loss, yet it does not repair and it blows up in the long run. Looking only at the loss is misleading.</li><li><strong>Repair has to be taught.</strong> A model trained without damage does not learn to repair on its own, and a model that did see damage cannot repair much more than it saw. Generalization is limited.</li></ol><p>Thanks for reading! Leave your questions in the comments. All the code is in my Kaggle notebook:</p><p><a href="https://www.kaggle.com/code/oguzuzan/growing-neural-cellular-automata-self-healing">🦎 Growing Neural Cellular Automata: Self Healing</a></p><h3>References</h3><ul><li>Mordvintsev, A., Randazzo, E., Niklasson, E., &amp; Levin, M. (2020). <em>Growing Neural Cellular Automata.</em> Distill. <a href="https://distill.pub/2020/growing-ca/">https://distill.pub/2020/growing-ca/</a></li><li>Noto Emoji, Google, Apache License 2.0. <a href="https://github.com/googlefonts/noto-emoji">https://github.com/googlefonts/noto-emoji</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=236f3e6905a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Taught a Robot to Run, Then Injured It: PPO vs SAC vs TD3]]></title>
            <link>https://medium.com/@oguzenveruzan/i-taught-a-robot-to-run-then-injured-it-ppo-vs-sac-vs-td3-ab3749e8c124?source=rss-b67ce03605ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab3749e8c124</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Oguz Enver Uzan]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 16:48:57 GMT</pubDate>
            <atom:updated>2026-10-27T16:48:57.128Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Taught a Robot to Run, Then Injured It</h3><p><em>PPO vs SAC vs TD3 learning to run from scratch, and what happened when I paralyzed one of its legs</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*CC_z8PACY9YXtUF4yh1LtA.gif" /><figcaption>healthy, injured and adapted robot side by side</figcaption></figure><p>A robot’s first steps are always a little funny. The eight-motor, four-legged robot called Ant starts training by twitching on the floor, tipping over and flailing its legs at random. Nobody tells it how to walk. All it has is a score: the faster it moves forward, the better.</p><p>In this article I pitted three deep reinforcement learning algorithms (PPO, SAC and TD3) against each other on the same problem, with a fair budget and 3 random seeds each. Then I deliberately injured the best robot by cutting the motor power of one leg. First I checked how resilient it was to the damage, then I asked the real question: <strong>can the robot adapt to its new body, and how much does reusing prior knowledge help compared to learning from scratch?</strong></p><p>All the code and outputs are in my Kaggle notebook:</p><p><a href="https://www.kaggle.com/code/oguzuzan/teaching-a-robot-to-run-then-injuring-it">Teaching a Robot to Run, Then Injuring It</a></p><h3>Six questions I wanted to answer</h3><ol><li>What does the robot do before learning, and how does its behavior evolve during training?</li><li>How fast and how reliably do PPO, SAC and TD3 learn?</li><li>Which reward component drives the gains: speed, survival, or energy saving?</li><li>What does the gait look like? In what order do the legs touch the ground?</li><li>How much does the policy degrade when a leg is weakened or paralyzed?</li><li>Can the robot adapt to its new body, and what does transfer learning buy compared to learning from scratch?</li></ol><h3>Ant-v5: the stage and the actor</h3><p>The environment is <strong>Ant-v5</strong>, built on MuJoCo physics through Gymnasium. The robot is a torso with four legs. Each leg has a hip and an ankle motor, so there are <strong>8 joints</strong> in total.</p><ul><li><strong>Observation:</strong> a 105-dimensional vector (joint angles and velocities, torso orientation and velocity, contact forces)</li><li><strong>Action:</strong> an 8-dimensional continuous vector, each motor torque in [-1, 1]</li><li><strong>Reward:</strong> survival (+1 per step) + forward speed − control cost − contact cost</li><li><strong>Termination:</strong> the torso height leaves the healthy range (0.2 to 1.0 m), meaning a fall or a jump, or 1000 steps are reached</li></ul><h3>The hidden trap in the reward: the lazy optimum</h3><p>This reward has an interesting quirk. Most of it comes from the “survival” term: +1000 over 1000 steps. That means <strong>a robot that doesn’t move at all, but doesn’t tip over, can collect roughly +1000 points.</strong> An agent that truly learns to run has to rise above this lazy optimum.</p><p>So throughout this article I won’t look at average reward alone. I will always report <strong>forward speed</strong> as well, because reward by itself can be misleading. This detail comes back in an important way near the end.</p><h3>Before training: the random policy</h3><p>The untrained robot sends random commands to its 8 motors at every step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*d8-tpsiy-3mhnSjr8EEmUw.gif" /><figcaption><em>The untrained robot: a random policy. It twitches, tips over and goes nowhere.</em></figcaption></figure><h3>The contenders: PPO, SAC and TD3</h3><p>I picked three algorithms because they represent different philosophies and are among the most widely used for continuous control.</p><ul><li><strong>PPO</strong> (on-policy, policy gradient): prevents the policy from changing “too much” during an update by clipping. Simple and stable, but it uses each batch of collected data only once. <em>Expectation: reliable but expensive in steps.</em></li><li><strong>SAC</strong> (off-policy, actor-critic): maximizes <strong>entropy</strong> on top of reward, which encourages exploration, and reuses data through a replay buffer. <em>Expectation: usually the most sample-efficient and stable.</em></li><li><strong>TD3</strong> (off-policy, deterministic actor-critic): fixes DDPG’s overestimation bias with twin critics, delayed actor updates and target noise. <em>Expectation: close to SAC, but sometimes more sensitive to hyperparameters.</em></li></ul><h3>How the comparison was set up</h3><ul><li><strong>3 seeds.</strong> In reinforcement learning a single run proves nothing. The same algorithm with different seeds can give wildly different results, so I report mean ± standard deviation.</li><li><strong>Not equal steps, but a reasonable budget for each.</strong> PPO is on-policy: it throws data away after one use and needs more steps for comparable performance. So PPO got <strong>1 million</strong> steps and SAC/TD3 got <strong>300 thousand</strong>. I plot everything on the same x-axis so the differences in sample efficiency are clearly visible.</li><li><strong>Same evaluation protocol.</strong> Deterministic policy, 10 episodes, identical initial seeds.</li><li><strong>Normalization for PPO.</strong> Observation and reward normalization (VecNormalize) is almost mandatory for PPO in MuJoCo, because observation scales vary wildly.</li><li><strong>No hyperparameter tuning.</strong> Everything stays close to the standard SB3 / RL-Zoo MuJoCo settings. So “PPO lost in this notebook” does not mean “PPO is bad.” The results hold for this budget and these settings.</li><li><strong>Independent processes.</strong> Each training run was a separate subprocess on a single CPU core. The 9 runs really did run in parallel, a crash in one didn’t affect the others, and finished runs were never retrained.</li></ul><h3>Results 1: who learns how fast?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1XgSDr3qOw6W_1lLb9yFA.png" /><figcaption><em>Ant-v5 learning curves (mean ± std, 3 seeds). Left: each algorithm’s full budget. Right: the first 300k steps, a fair comparison window.</em></figcaption></figure><p>Thin lines are individual seeds, the thick line is the mean, and the shaded area is ±1 standard deviation. Three things stand out:</p><ol><li><strong>SAC is clearly ahead in the first 300k steps.</strong> It crossed the 1000-point threshold in about 169k steps on average, in all three seeds.</li><li><strong>TD3 starts fast but plateaus low.</strong> It climbs even faster than SAC early on, then flattens out around 500.</li><li><strong>PPO is very slow.</strong> Even after 1 million steps it sits around 500, and in the first 300k steps it is close to zero.</li></ol><p>Sample efficiency by reward threshold:</p><ul><li><strong>Reaching ≥ 500:</strong> SAC ~82k steps (3/3 seeds), TD3 ~133k (3/3), PPO ~738k (3/3)</li><li><strong>Reaching ≥ 1000:</strong> SAC ~169k (3/3). TD3 and PPO never reached it.</li><li><strong>Reaching ≥ 2000:</strong> only SAC, in 1 of 3 seeds, at ~257k steps</li><li><strong>Reaching ≥ 3000:</strong> nobody</li></ul><h3>“Fewer steps” does not always mean “less time”</h3><p>There is a catch. SAC and TD3 do a gradient update at every step, so each step is much more expensive. Average training time on one core:</p><ul><li><strong>PPO:</strong> 44.9 minutes</li><li><strong>TD3:</strong> 187.3 minutes</li><li><strong>SAC:</strong> 192.0 minutes</li></ul><p>SAC and TD3 are far better in <strong>sample efficiency</strong>, yet roughly 4 times slower in <strong>wall-clock time</strong>. In a cheap simulator, PPO’s time advantage is a real argument. On a real robot where every step is expensive, the picture flips completely.</p><h3>Results 2: final performance and the anatomy of the reward</h3><p>The learning curve measures the stochastic policy during training. For true performance, I tested each run’s final policy <strong>deterministically</strong> for 10 episodes, with the same initial seeds for every algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUCEwpHZDevqaLBTLL3YwQ.png" /><figcaption><em>Final policies (deterministic; black dots are individual seeds).</em></figcaption></figure><ul><li><strong>PPO:</strong> reward 705 ± 92, speed 0.93 ± 0.20 m/s, episode length 597 / 1000</li><li><strong>SAC:</strong> reward <strong>1582 ± 431</strong>, speed <strong>1.75 ± 0.70 m/s</strong>, episode length <strong>831 / 1000</strong></li><li><strong>TD3:</strong> reward 578 ± 18, speed 0.79 ± 0.34 m/s, episode length 603 / 1000</li></ul><p><strong>SAC</strong> is first in reward, speed and survival. But the spread across seeds is huge: individual seeds range from about 1200 to above 2100. PPO and TD3 are more consistent, but consistently low. An honest reading: “SAC is best on average, but it depends on which seed you draw.”</p><p>No algorithm’s average episode length reached 1000, so all of them fall over from time to time.</p><h3>Where does the score come from?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*J6LeQANLPmehOjYrh8r0CA.png" /><figcaption><em>Reward components per episode: where does the score come from?</em></figcaption></figure><p>Splitting the reward into its four components makes each algorithm’s strategy clear:</p><ul><li><strong>SAC</strong> is fast but energy-hungry: it earns the most from forward speed and pays for it with the heaviest motor load (control cost around −600).</li><li><strong>PPO</strong> sits in the middle: control cost around −375, low speed, early falls.</li><li><strong>TD3</strong> is the most frugal: control cost around −250, but low speed keeps the total score down.</li></ul><p>In other words, the three algorithms found three different “personalities”: SAC’s bold sprint, TD3’s thrifty caution, and PPO’s slow, careful progress.</p><h3>Results 3: the learning story</h3><p>Numbers say “reward 1582.” A video says “the robot is actually running now.” I played the best seed’s saved checkpoints side by side: <strong>start of training, 10%, 50%, 100%</strong>. Same initial seed and same camera, so the only difference is the policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*IR2uDc5vPqF-Uz9yYiXGLQ.gif" /><figcaption><em>The same robot at 4 stages of training.</em></figcaption></figure><p>The early behaviors (shivering in place, crawling, tumbling) also show the order in which learning progresses: first stay upright, then move forward, and only then speed up.</p><h3>Gait analysis: how does the robot run?</h3><p>In biomechanics, locomotion types (diagonal trot, bound, pace…) are described with a <strong>gait diagram</strong>. Each row is a leg, and each dark bar is a time interval in which that leg is <strong>on the ground</strong> (stance). The gaps are moments when the leg is in the air (swing). The RL agent finds this pattern entirely on its own, without anyone telling it to “walk.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AniVW_s4HLAs0BK4iGYghg.png" /><figcaption><em>Left: SAC’s gait pattern (dark = foot on ground). Right: top-down trajectory.</em></figcaption></figure><p>Honesty matters here: SAC’s pattern does not look like a clean textbook diagonal trot. Contacts are short, broken and irregular, and the legs touch down more as “needed” than in a clear phase relationship. The learned policy looks less like an animal and more like <strong>its own peculiar, slightly stumbling gait.</strong></p><p>The top-down trajectory tells the same story: the robot covers about 20 meters forward, but instead of a straight line it drifts to one side (roughly 3.5 meters of lateral drift). Controlled, but not perfect.</p><h3>Robustness map: what happens when a leg weakens?</h3><p>This is where the project gets exciting. <strong>Without any retraining</strong> (zero-shot), I placed each algorithm’s best policy into an injured body. I systematically dropped each leg’s motor power to 75%, 50%, 25% and 0%.</p><p>The injury is simulated by an InjuryWrapper that multiplies the commands going to the selected leg’s two motors (hip + ankle) by a power factor. power=0 fully paralyzes the leg and 0.5 halves its strength. The agent <strong>does not know</strong> about this change. It only sees the consequences of its own behavior.</p><p><strong>Why this test?</strong> Average reward tells you a policy is “good,” but not <em>what it relies on</em>. If losing a single leg collapses performance, the policy is overly dependent on that leg, which means it is fragile. Two policies with the same reward can differ drastically in robustness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqEgid1IdKEkBdQthY6dSw.png" /><figcaption><em>Zero-shot robustness map (green = robust, red = collapse). Values are relative to the healthy robot’s reward.</em></figcaption></figure><p><strong>SAC has the highest score but is the most fragile.</strong> The SAC policy, with a healthy reward of about 2394, drops to a ratio of <strong>−0.06</strong> when the <strong>Front-Left</strong> leg is fully paralyzed and to <strong>0.00</strong> when the <strong>Back-Right</strong> leg is. Lose either of those legs and the robot loses its balance and the entire gain. Yet the same policy is almost unaffected when the Back-Left leg is paralyzed (ratio 1.26). The load is not spread symmetrically across the legs: some legs are critical, others nearly idle.</p><p><strong>TD3 is more resilient.</strong> Its worst case is full paralysis of the Front-Left leg (ratio 0.18), and it never falls into negative territory.</p><p><strong>PPO shows misleading ratios.</strong> In some cells the ratio exceeds 1.0 (for example 1.54 for the Back-Left leg at 50% power). That does not mean “the injured robot is better.” PPO’s healthy baseline is already low (about 733), and as power drops the control cost drops too, or the robot settles into a stiffer, static posture that doesn’t fall, which inflates the ratio. Its worst case is the Back-Right leg at 0% power: 0.68.</p><p><strong>Important caveat:</strong> the map comes from a single (best) seed per algorithm and only a few episodes per cell, so it is noisy. Look at the overall pattern rather than individual cells. The main message: <strong>the highest score does not mean the most robust policy.</strong></p><h3>The real question: can the robot adapt to its new body?</h3><p>What if the injury is permanent? I compared two strategies:</p><ul><li><strong>A) Fine-tuning (transfer):</strong> start from the SAC policy learned on the healthy body and train 150k more steps on the injured body. <em>Hypothesis: most of the walking knowledge survives, so small corrections are enough and adaptation is fast.</em></li><li><strong>B) From scratch:</strong> start randomly on the same injured body with the same step budget. <em>Hypothesis: no prior knowledge, so it is slow.</em></li></ul><p><strong>Design decisions:</strong></p><ul><li><strong>Choice of injury:</strong> the leg that did the most damage in the robustness map: for SAC, the <strong>Front-Left leg at 0% power (full paralysis)</strong>. An easy injury would have made adaptation look too easy.</li><li><strong>Algorithm:</strong> the best off-policy algorithm (SAC). Thanks to the replay buffer, fine-tuning works naturally and robustly.</li><li><strong>Warm-up (5000 steps):</strong> at the start of fine-tuning the replay buffer is empty, and updating weights on a handful of samples can corrupt the policy. So I first collect data on the injured body <strong>without updating weights</strong>, then start learning.</li><li><strong>Fair comparison:</strong> fine-tuning and training from scratch ran in the same environment, with the same number of steps and the same seeds (2 seeds).</li><li><strong>Adaptation time:</strong> the number of steps for the fine-tuning curve to reach 80% of the healthy robot’s performance.</li></ul><h3>Bad news first: what does the unaware robot do?</h3><p>When the unadapted (zero-shot) policy is dropped into the injured body, its reward collapses from <strong>1582 to about 21</strong> (even negative in a cross-section measured with fewer episodes), and forward speed falls to <strong>0.11 m/s</strong>. But look at the episode length: <strong>1000 steps, the full duration.</strong></p><p>This is a live example of the lazy optimum I mentioned at the start. The robot doesn’t tip over, it survives, but <strong>it goes nowhere.</strong> Because of the injured leg, it has given up running and settled for staying upright. Someone looking only at reward could miss the size of this collapse, and that is exactly why I report forward speed separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTrmAE_QPt1gGasjiGTiIQ.png" /><figcaption><em>Adaptation to Front-Left leg paralysis (SAC). Red: fine-tuning. Gray: from scratch. Green dashed: healthy robot. Red dotted: unadapted injured robot.</em></figcaption></figure><h3>The numbers</h3><ul><li><strong>Unadapted (zero-shot):</strong> reward 21.4, speed 0.11 m/s, episode length 1000</li><li><strong>From scratch:</strong> reward 1224.7, speed 1.08 m/s, episode length 841.8, reached 80% of healthy performance at ~149k steps</li><li><strong>Fine-tuning (transfer):</strong> reward <strong>1301.0</strong>, speed <strong>1.90 m/s</strong>, episode length 668.4, reached 80% of healthy performance at <strong>~91k steps</strong></li></ul><p>Both approaches reached 80% of the healthy robot’s performance (about 1266). So even with a paralyzed leg, the robot can learn to run again. What transfer learning bought:</p><ol><li><strong>Faster adaptation:</strong> 91k steps versus 149k. In the plot, the red curve is clearly ahead of the gray one over the first 60k steps.</li><li><strong>Faster running:</strong> 1.90 m/s versus 1.08 m/s.</li><li><strong>But less stability:</strong> the fine-tuned robot falls sooner (668 steps versus 842). The from-scratch robot is more cautious and stays upright longer. The classic trade-off between speed and safety shows up here too.</li></ol><p><strong>Let’s not overclaim.</strong> After 150k steps the two curves end very close together (both around 1250), and the fine-tuning curve is quite noisy. The “91k steps” figure is the first moment the curve crosses the threshold, which on a noisy curve may be a temporary spike. I also used only 2 seeds. So what I can say with confidence is: “transfer gives a clear advantage early on, and learning from scratch catches up later.” I can’t say “transfer is always 1.6 times faster.”</p><h3>Final video: healthy, injured, adapted</h3><p>All three panels share the same initial seed. The <strong>red leg</strong> is the paralyzed one. The left panel is the control (healthy robot), the middle is the policy unaware of the injury, and the right is the policy re-learned through fine-tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*CC_z8PACY9YXtUF4yh1LtA.gif" /></figure><h3>Limitations</h3><p>This is an experiment, not a research paper.</p><ol><li><strong>Few seeds (3 / 2).</strong> The standard deviations are rough estimates. Publication quality needs 5 to 10 seeds, and the shaded regions don’t carry a claim of statistical significance.</li><li><strong>No hyperparameter tuning.</strong> Every algorithm ran with shared defaults. Per-algorithm tuning could change the ranking, especially for PPO and TD3.</li><li><strong>Unequal but reasonable step budget.</strong> PPO got 1M steps and SAC/TD3 got 300K. At 1M steps SAC and TD3 could go much further.</li><li><strong>A simple injury model.</strong> Scaling motor power is only an approximation of real damage (a broken joint, latency, sensor failure). The adaptation test covered a single injury type on a single leg.</li><li><strong>Simulation is not a real robot.</strong> Friction, latency and noise differ on real hardware (the sim-to-real gap).</li><li><strong>One fine-tuning setting.</strong> Warm-up length and learning rate were not tuned, and other settings could change the adaptation speed.</li></ol><h3>Next steps</h3><ul><li>Train a single policy that is robust to injury from the start with <strong>domain randomization</strong>, and compare the robustness maps.</li><li>Run a <strong>reward shaping ablation</strong>: set the control cost to 0 / 0.5 / 2.0 and see how the gait diagram changes.</li><li>Try the same pipeline on a harder body, <strong>Humanoid-v5</strong> (longer training needed).</li><li>Build <strong>meta-RL / context-based policies</strong> that detect an injury automatically and adapt instantly.</li></ul><h3>Three takeaways</h3><ol><li><strong>Reward is just a number, not success.</strong> The “stay alive” reward gives even a motionless robot ~1000 points. Without extra metrics like forward speed and episode length, SAC’s paralyzed robot would have looked “successful.”</li><li><strong>The best score is not the most robust policy.</strong> SAC is the fastest and highest-scoring, but it is also the one that collapses when a leg is paralyzed.</li><li><strong>Prior knowledge speeds up adaptation, but it is not a cure-all.</strong> Transfer learning gave a clear early advantage, and with enough steps, learning from scratch caught up.</li></ol><p>Thanks for reading! Leave your questions in the comments. All the code is in my Kaggle notebook:</p><p><a href="https://www.kaggle.com/code/oguzuzan/teaching-a-robot-to-run-then-injuring-it">Teaching a Robot to Run, Then Injuring It</a></p><h3>References</h3><ul><li>Sutton, R. S., &amp; Barto, A. G. (2018). <em>Reinforcement Learning: An Introduction</em> (2nd ed.). MIT Press.</li><li>Gymnasium, “MuJoCo / Ant” environment page: <a href="https://gymnasium.farama.org/environments/mujoco/ant/">https://gymnasium.farama.org/environments/mujoco/ant/</a></li><li>Cully, A., Clune, J., Tarapore, D., &amp; Mouret, J.-B. (2015). <em>Robots that can adapt like animals.</em> Nature, 521, 503–507.</li><li>Tobin, J. et al. (2017). <em>Domain Randomization for Transferring Deep Neural Networks from Simulation to the Real World.</em> IROS. arXiv:1703.06907</li><li>Zhao, W., Queralta, J. P., &amp; Westerlund, T. (2020). <em>Sim-to-Real Transfer in Deep Reinforcement Learning for Robotics: a Survey.</em> arXiv:2009.13303</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab3749e8c124" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>