<?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 Arkananta on Medium]]></title>
        <description><![CDATA[Stories by Arkananta on Medium]]></description>
        <link>https://medium.com/@luminolous?source=rss-c8792029593b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*STxyWW0WHY9ZzsKA1sX3fQ.png</url>
            <title>Stories by Arkananta on Medium</title>
            <link>https://medium.com/@luminolous?source=rss-c8792029593b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:54:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luminolous/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[Where the Brain Goes Quiet]]></title>
            <link>https://medium.com/@luminolous/where-the-brain-goes-quiet-743c298e3d7d?source=rss-c8792029593b------2</link>
            <guid isPermaLink="false">https://medium.com/p/743c298e3d7d</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[neuroscience]]></category>
            <dc:creator><![CDATA[Arkananta]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 13:28:25 GMT</pubDate>
            <atom:updated>2026-10-09T13:32:11.134Z</atom:updated>
            <content:encoded><![CDATA[<h4>I trained YOLO to find imagined movements in EEG spectrograms.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*uzwiJjrk9OSYsjsbIyvNhA.gif" /><figcaption>Boxes from my labeling rule (left) and from YOLO11n (right) on right-hand imagery of one subject. Each image stacks five electrodes. Blue marks a drop in power, red a rise.</figcaption></figure><p>Imagine squeezing your right hand without moving a finger. Over your left motor cortex, the 8 to 30 Hz rhythms lose power. Average enough attempts and you can see the loss on a spectrogram: across 9 people in a public dataset, power at electrode C3 fell 23.8 % below baseline while they imagined the movement.</p><p>That drop has an electrode, a start, an end and a frequency band. I looked at it and saw a bounding box, so I trained YOLO to find these patches.</p><p>The detector reached a test mAP@0.5 of 0.93. Before I could trust that number, I had to throw away my first set of labels, because a surrogate test showed they marked noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zIbXH02bevBSBK5bwmkvFQ.png" /><figcaption><em>Average change in power for each imagined movement (rows) and electrode (columns), 9 subjects. Hand imagery lowers power over both hand areas, with the larger drop on the opposite side of the body.</em></figcaption></figure><h3>Two minutes of neuroscience</h3><p>The motor cortex keeps two rhythms at rest: mu, 8 to 13 Hz, and beta, 13 to 30 Hz. When you move or imagine moving, the rhythm over that body part weakens. Neuroscientists call this event-related desynchronization, or ERD. When the imagery stops, beta power overshoots the baseline for about a second. They call that overshoot a beta rebound, an event-related synchronization (ERS).</p><p>The location follows a map of the body. Right-hand imagery lowers power at C3 over the left hemisphere, left-hand imagery at C4, and foot imagery near the midline at Cz. Engineers build motor imagery brain-computer interfaces on these changes, so a person can steer a cursor or a wheelchair by imagining a movement.</p><p>I used BCI Competition IV dataset 2a: 9 subjects, 22 EEG channels at 250 Hz, and four imagined movements (left hand, right hand, both feet, tongue). Each subject recorded two sessions on different days. I trained and validated on the first session and tested on the second, so every test number crosses sessions. After artifact rejection I kept 2,328 and 2,368 trials.</p><h3>One image, five electrodes</h3><p>I band-passed the EEG to 4–40 Hz, cut epochs from 1.5 s before to 5.75 s after the cue, and applied a small Laplacian to five electrodes over the motor strip: C5, C3, Cz, C4 and C6. The Laplacian subtracts the mean of each electrode’s neighbours and sharpens local activity. I computed power from 4 to 40 Hz with Morlet wavelets.</p><p>Each image stacks the five spectrograms from top to bottom, left hemisphere first. A panel is 640 × 128 pixels, with time on x (−1 to 5.5 s around the cue) and frequency on y (40 Hz at the top). Color shows a z-score of power: blue for a drop, red for a rise.</p><p>I defined the class by the panel. A drop on C4 is ERD_C4, the candidate for left-hand imagery. C3 points to the right hand, Cz to the feet, and C5 or C6 (ERD_lateral) to the tongue. A beta rise after 4 s becomes ERS_rebound on any panel. My labeler never reads the cue, so a drop over both hand areas gets two boxes.</p><p>A classifier tells you which movement a trial contains. A detector adds where the evidence sits in electrode, time and frequency, and you can check each box by eye.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*15oRxjx87Sfg_usQOi_rfg.png" /><figcaption>The pipeline, from raw EEG to one shared evaluator.</figcaption></figure><h3>My first labels were noise</h3><p>No public dataset marks ERD with bounding boxes, so I wrote a rule to generate them. My first rule flagged any region more than 20 % below baseline during the imagery. It found ERD candidates on every panel in 85 to 97 % of trials, whatever the cue. A typical left-hand trial showed ERD on all five electrodes.</p><p>I moved to a z-score. Then I compared the spread of z after the cue with its spread in the baseline window, and the post-cue spread came out 2.4 times larger, in real data and in surrogates. I had z-scored maps that I had already normalized to each trial’s own baseline. That step pins the baseline window near zero, and every z after it comes out too large. I fixed it by z-scoring absolute power in dB against the baseline pixels of all trials in the session.</p><p>Next I needed to know whether the boxes marked cue-locked brain activity or random swings that crossed the threshold. I used surrogate data. For each trial and channel I randomized the Fourier phases. A surrogate keeps the amplitude spectrum, so its power rises and falls by the same amounts as the real signal, yet nothing in it lines up with the cue. I ran the same labeler on both and counted boxes per image. I set the bar in advance: a class passes if it appears at least 3 times as often in real data.</p><p>Single trials failed. At z ≥ 2.5 the real-to-surrogate ratios were 1.8 for ERD_C4, 2.6 for ERD_C3, 1.5 for ERD_Cz and 2.2 for ERS_rebound. ERD_lateral scored 0.5: my rule found more “tongue ERD” in surrogates than in brains. Within one trial, mu and beta power swing as much as the ERD itself, and a threshold cannot tell the two apart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOUfQ-1NyDcW3NwIysmMQA.png" /><figcaption><em>Five single trials of subject A03 with the right-hand cue, and their average, on the same z scale. The C3 drop stands out in the average.</em></figcaption></figure><h3>Averaging five trials</h3><p>When I averaged trials, the spontaneous swings cancelled out in part and the cue-locked drop stayed. I built each image from the mean power of 5 trials with the same subject, cue and data split, and kept separate trial pools for training, validation and test. For each subject and cue I drew 50, 10 and 50 distinct groups, which gave 1,800, 360 and 1,800 images.</p><p>I rendered each image from the same z map the labeler thresholds, with ERD at z ≤ −3 and ERS at z ≥ +3. At 5 trials every class cleared the bar: 22.2× for ERD_C4, 13.1× for ERD_C3, 16.7× for ERD_Cz, 11.5× for ERD_lateral and 5.3× for ERS_rebound. Real images came out empty 56 % of the time, surrogates 94 %.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMCBiQ8P9KK3hX3yeDSLkQ.png" /><figcaption>Boxes per image on real data divided by boxes per image on phase-randomized surrogates. Grey: single trials. Blue: averages of 5 trials. Dashed line: the 3× bar.</figcaption></figure><p>I ran an AI-assisted review in two passes over 98 boxes in 50 training images. It rated 82.7 % of them valid. Hand and midline boxes scored 94 to 95 %, ERD_lateral 67 % and ERS_rebound 68 %. The three invalid boxes sat on broadband bursts at the end of the epoch that look like muscle artifacts. Many valid boxes cover the strongest core of a larger blue region and miss its edges.</p><p>The averaging has a cost. One image now stands for five trials, so every result below describes groups of trials, and none of it measures single-trial BCI performance.</p><h3>Augmentations that break a spectrogram</h3><p>Detection libraries ship augmentations designed for photos. A horizontal flip reverses time. A vertical flip swaps C5 with C6 and C3 with C4, which swaps the classes. Mosaic glues panels from different images together, and a hue shift changes the z values. I turned every augmentation off, including random erasing, which Ultralytics 8.4 enables by default at 0.4.</p><p>I hit two more problems. Ultralytics validates on rectangular batches and pads 640 × 640 images to 672 × 672 with grey borders. On my first run its validation reported mAP@0.5 of 0.823, while my own evaluator gave 0.969 for the same weights. ERS_rebound, which sits at the right edge, scored 0.46 in that validation and 0.96 in mine. Ultralytics stopped training and picked best.pt by that wrong number until I passed it a trainer that validates on unpadded images. The second problem: model.predict on a Python list ignores the batch argument and sends all 1,800 images at once, which ran my 6 GB GPU out of memory. I now predict in chunks of 16.</p><p>I scored every model, the threshold rule included, with one evaluator built on torchmetrics, so the numbers below compare like with like.</p><h3>The detector works</h3><p>I tuned YOLO11n on validation data, one setting at a time. My starting configuration won: SGD, learning rate 0.01, batch 16, 640 px, 100 epochs. Shrinking images to 512 px hurt box precision most, with mAP@0.5:0.95 falling from 0.815 to 0.748.</p><p>Results on the test session:</p><ul><li><strong>Threshold rule:</strong> mAP@0.5 1.000. It generated the labels, so read it as the ceiling.</li><li><strong>YOLO11n:</strong> 0.925 (0.927 ± 0.005 over three seeds), mAP@0.5:0.95 0.735, 28 min of training.</li><li><strong>YOLO11s:</strong> 0.937, mAP@0.5:0.95 0.777, 49 min.</li><li><strong>Faster R-CNN (ResNet50-FPN v2):</strong> 0.837, mAP@0.5:0.95 0.596, 114 min.</li></ul><p>I selected YOLO11n because it scored highest on validation (0.974). YOLO11s did better on test. My validation set holds 360 images whose groups share trials, and it cannot separate models that sit 0.01 apart.</p><p>Most YOLO errors are false positives. YOLO11n found 1,892 labeled boxes, added 438 extra ones and missed 59. Of 333 extra boxes with no same-class match, 236 overlap no label at all and mark weaker events that you can see in the image but that stay above the z ≤ −3 threshold.</p><p>Faster R-CNN made a different mistake. It swapped classes between panels and predicted 87 ERD_C4 boxes as ERD_C3. My hypothesis, which I have not tested: its second stage classifies cropped regions that lose their absolute position in the image, and in my data the position is the class. YOLO11n made 5 cross-class errors.</p><p>Dropping to two classes (ERD_C4 and ERD_C3, left- and right-hand trials) gave no gain: AP50 of 0.955 and 0.976, against 0.965 and 0.975 with five classes. With position-defined classes, the hard part is finding the event and its extent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbRvr_AGjBSRS-F0d4l4ag.png" /><figcaption>Ground truth and YOLO11n predictions (confidence ≥ 0.25) on test images from the second session.</figcaption></figure><h3>Two tests the detector failed</h3><p><strong>Noise.</strong> I added white noise to each trial and channel before the Laplacian, rebuilt the test images, and kept the clean labels. YOLO11n and the threshold rule lost the same share of their clean score at every level. At 15 dB nominal SNR, YOLO11n kept 42.8 % of its clean mAP@0.5 and the rule kept 42.9 %. The trained detector showed no robustness advantage over the rule that made its labels. Both fell below 0.17 at 10 dB, because the Laplacian subtracts the signal the neighbours share and adds up their independent noise. A nominal 10 dB per channel left 2.4 dB in the 4–40 Hz signal I analysed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JmrVAg_hvPz5hWOgkARWg.png" /><figcaption>Test mAP@0.5 (left) and mAP@0.5:0.95 (right) against nominal SNR per channel.</figcaption></figure><p><strong>Decoding.</strong> For each test group I took the ERD class with the highest summed confidence as the predicted movement and compared it with the cue. I counted groups without an ERD box as wrong. As a reference I used CSP + LDA, a classic motor imagery pipeline, and averaged its class probabilities over the same five trials.</p><ul><li><strong>CSP + LDA:</strong> accuracy 0.718, Cohen’s κ 0.624</li><li><strong>Threshold rule:</strong> accuracy 0.203, κ −0.063, no decision in 68.2 % of groups</li><li><strong>YOLO11n:</strong> accuracy 0.164, κ −0.115, no decision in 67.3 % of groups</li></ul><p>Coverage explains the gap. 32.7 % of test groups contained an ERD box: 58.9 % of left-hand groups, 46.2 % of right-hand groups, 20.7 % of feet groups and 5.1 % of tongue groups. In this dataset tongue imagery raises power over the hand areas, and feet imagery produces more beta rebound at Cz than ERD. When YOLO11n did find an ERD box, its panel named the right movement in 50 % of groups, twice the 25 % chance level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKGejs5VUcnmMRkw7gOCpw.png" /><figcaption>Group decoding accuracy per subject on the test session. Subject A02 produced no ERD box at all.</figcaption></figure><p>Subjects differ more than models. A03, A07 and A08 carry most of the detector’s correct decisions. A02, A04 and A05 show little or no ERD, a pattern BCI researchers call BCI inefficiency.</p><h3>What I’d change next time</h3><p>I would run the surrogate test before training on any rule-generated label. The overlays of my first dataset looked convincing, and the test showed they were no better than noise.</p><p>I would compute z-scores from power that I had not normalized to itself, and check the baseline spread before I trust a threshold.</p><p>When position defines the class, I would audit every augmentation and every validation transform, and check whether the detector keeps absolute position.</p><p>And I would read a high mAP for what it measures. Here 0.93 means YOLO learned to reproduce my labeling rule. Whether the boxes carry useful information about the brain is a separate test, and CSP + LDA won that one by a wide margin.</p><h3>Limitations</h3><ul><li>Labels come from a rule. ERD_lateral and ERS_rebound are the weakest classes, some ERS boxes mark artifacts, and many boxes miss the edges of an event.</li><li>The threshold rule made the labels, so its perfect clean score serves as a ceiling.</li><li>Validation holds 360 images whose groups share 38.7 % of their trials on average, and seed 0, the selected run, was the best of three seeds on validation.</li><li>Every result describes groups of five trials.</li></ul><p>Code, notebooks and the source table for every number in this post: <a href="https://github.com/luminolous/quiet-cortex">github.com/luminolous/quiet-cortex</a></p><h3>References</h3><ol><li>Brunner, C., Leeb, R., Müller-Putz, G. R., Schlögl, A., &amp; Pfurtscheller, G. (2008). <em>BCI Competition 2008 — Graz data set A</em>. Institute for Knowledge Discovery, Graz University of Technology. <a href="https://www.bbci.de/competition/iv/desc_2a.pdf">https://www.bbci.de/competition/iv/desc_2a.pdf</a></li><li>Pfurtscheller, G., &amp; Lopes da Silva, F. H. (1999). Event-related EEG/MEG synchronization and desynchronization: basic principles. <em>Clinical Neurophysiology</em>, 110(11), 1842–1857.</li><li>Ramoser, H., Müller-Gerking, J., &amp; Pfurtscheller, G. (2000). Optimal spatial filtering of single trial EEG during imagined hand movement. <em>IEEE Transactions on Rehabilitation Engineering</em>, 8(4), 441–446.</li><li>Theiler, J., Eubank, S., Longtin, A., Galdrikian, B., &amp; Farmer, J. D. (1992). Testing for nonlinearity in time series: the method of surrogate data. <em>Physica D: Nonlinear Phenomena</em>, 58(1–4), 77–94.</li><li>Ren, S., He, K., Girshick, R., &amp; Sun, J. (2015). Faster R-CNN: Towards real-time object detection with region proposal networks. <em>Advances in Neural Information Processing Systems 28</em> (NeurIPS 2015), 91–99.</li><li>Li, Y., Xie, S., Chen, X., Dollár, P., He, K., &amp; Girshick, R. (2021). Benchmarking detection transfer learning with vision transformers. <em>arXiv:2111.11429</em>.</li><li>Jocher, G., &amp; Qiu, J. (2024). <em>Ultralytics YOLO11</em> (Version 11.0.0) [Computer software]. AGPL-3.0. <a href="https://github.com/ultralytics/ultralytics">https://github.com/ultralytics/ultralytics</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=743c298e3d7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When More Damping Makes Your IK Solver Worse]]></title>
            <link>https://medium.com/@luminolous/when-more-damping-makes-your-ik-solver-worse-005397d7f266?source=rss-c8792029593b------2</link>
            <guid isPermaLink="false">https://medium.com/p/005397d7f266</guid>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[control-system]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[inverse-kinematics]]></category>
            <dc:creator><![CDATA[Arkananta]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 06:18:46 GMT</pubDate>
            <atom:updated>2026-08-29T06:20:22.579Z</atom:updated>
            <content:encoded><![CDATA[<h4>A non-monotonic result in differential inverse kinematics, and three wrong explanations before the right one.</h4><p>I swept the damping parameter of an inverse kinematics solver across five orders of magnitude, expecting a smooth trade-off between tracking accuracy and stability. I got a curve with a hole punched in the middle of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*RrKQjuoDNxZi85Hpi-c2JA.png" /><figcaption>Damping sweep at a reach of 0.70 m. Four values in the middle fail by a factor of twenty, and the failure disappears again as the damping keeps rising.</figcaption></figure><p>Small damping works. Large damping works. Four values in between fail by a factor of twenty, then the failure vanishes as you keep increasing the same parameter. No textbook description of damped least squares predicts this shape, and my first three explanations for it turned out to be wrong.</p><p>The reason to read on, if you work on anything with more joints than task dimensions: the mechanism behind this has little to do with damping, and it applies to any redundant manipulator. If you run whole-body control on a humanoid, you have far more null directions than the one I am about to describe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*rOhcP_Bx6FGn81YlnSSrYw.gif" /><figcaption>The solver tracking a target the user drags through the workspace. Every frame solves one damped least squares problem and hands the result to the position actuators.</figcaption></figure><h3>What the solver does</h3><p>The Jacobian relates joint velocity to end-effector velocity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*9JqAeyczCVIUNGkggcrziA.png" /></figure><p>For the 7-joint Franka Panda and a 6-dimensional pose task, J is 6×7. You want the inverse relationship: given a pose error e, which joint velocity shrinks it? With more unknowns than equations the standard answer takes the minimum-norm solution through the pseudo-inverse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*wqZtMlOhPbLsfbg2l68jbw.png" /></figure><p>Straighten the arm out and J loses rank. The pseudo-inverse then asks for enormous joint velocities to produce a small end-effector motion, and your robot lunges. Damped least squares heads that off by adding a term to the matrix you invert.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*xzIlUrO6hLDlNV6gOB_Pbg.png" /></figure><p>The λ²I keeps the 6×6 matrix invertible whatever J does. Far from a singularity, λ² contributes almost nothing and you recover the pseudo-inverse. Close to one, it bounds the joint velocity and you pay for that bound in accuracy.</p><p>Textbooks describe one knob and one gradient: small λ tracks tightly and misbehaves near singularities, large λ stays smooth and tracks loosely. Table 1 is a different shape.</p><p>My test drives a target straight out from the home pose to 0.70 m from the shoulder and back, over 6 seconds at a 2 ms timestep, holding orientation fixed. That radius does a lot of work. The Panda reaches roughly 0.85 m if you only constrain position, but pinning the orientation costs workspace, and past about 0.70 m the requested pose leaves the reachable set. The run sits on that edge by design, because that is where damping has anything to do.</p><h3>Wrong explanation one: too much damping</h3><p>The obvious reading says heavy damping sacrifices accuracy. It dies on contact with the table. λ = 10⁻² carries more damping than any failing value and gives one of the best runs in the sweep.</p><h3>Wrong explanation two: the arm is stuck in a singularity</h3><p>The failing runs log condition numbers up to 1.57 million, which makes this a reasonable suspicion. Reading the time series kills it. At the moment the run reaches its worst error, cond(J) has come back down to around 32. The arm sits in a well-conditioned configuration while it fails. Whatever broke happened earlier, and the huge condition number belongs to the aftermath.</p><h3>Wrong explanation three: joint-limit clipping</h3><p>I held this one for a while, and watching it collapse taught me more than the answer did.</p><p>After solving for q̇ you integrate it into a position setpoint, then clip that setpoint to the joint limits before commanding it. Every failing run clips for more than 1,100 of its 3,000 steps. Every healthy run clips a dozen times or never. The correlation across the sweep runs above 0.95.</p><p>The mechanism sounded right too. Clipping shortens the commanded motion and points it somewhere else, so the arm jams against a limit and cannot work its way free.</p><p>Then I ran the ablation, holding λ = 10⁻³ and changing one thing at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*w6SeUNV7A64mL-8voQv7yg.png" /><figcaption>Ablation at the damping that fails. Removing the clipping changes the outcome by 0.0003 m. The nullspace term changes it by a factor of sixty-five.</figcaption></figure><p>Turning the clipping off repairs nothing. The run lands at 0.4299 m instead of 0.4302 m. Bounding the joint velocity leaves the outcome untouched as well. The only change that rescues the run is a secondary objective projected into the nullspace, and it works with clipping on or off.</p><p>If you try to reproduce this, one detail will bite you. MuJoCo clamps data.ctrl against each actuator&#39;s ctrlrange by default, and the Panda&#39;s ctrlrange matches its joint range. Disable your own clipping without also disabling mjDSBL_CLAMPCTRL and you have moved the clipping inside the physics engine rather than removing it, which hands you a null result for the wrong reason.</p><p>The timing closes the case. Logging a failing run and a healthy one step by step, their joint trajectories separate at step 1401. The first clip in the failing run happens at step 1860. The two runs had already parted company for 459 steps, almost a full second, before anything got clipped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPUaLg6Yvp5R_IPVgeXvpQ.png" /><figcaption>Joint trajectories for the failing and healthy runs. The vertical markers show where the paths separate and where the first clip occurs, 459 steps apart.</figcaption></figure><h3>Where the arm actually ends up</h3><p>Compare the final configurations joint by joint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*-DluXWRO3F1MTTIBnGeqhg.png" /><figcaption>Final joint angles. Three healthy runs agree to three decimals across a 30x range of damping. The failing run rests against two joint limits at once.</figcaption></figure><p>The three healthy runs return to the same posture, to three decimals, across a 30× range of damping. The failing run finishes somewhere else entirely, with joint4 resting at −0.068 rad against an upper limit of −0.0698, and joint2 at 1.747 against a limit of 1.7628. The elbow has straightened and locked, and the shoulder has swung up to compensate. The arm ends folded onto two of its limits at once.</p><p>The solver resolved the redundancy into a configuration it could not leave.</p><p>Seven joints serving a six-dimensional task leave one direction of joint motion that moves nothing at the gripper. The elbow swings while the hand stays put. With no secondary objective, nothing at all decides where that free coordinate goes: the minimum-norm solution picks whatever is locally cheapest, step by step, and it has no memory. Passing near the singularity, the free coordinate can settle on either side of a fold, and λ decides which side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pngw7rF7YIrp2_7csuszvQ.png" /><figcaption>Both runs use the same damping and the same target. The one on the right resolved the redundancy into a fold it could not undo, and finished 0.43 m from a target it had already reached once.</figcaption></figure><h3>Two outcomes with nothing in between</h3><p>Once I knew what to measure, the structure became easy to see. I ran a grid of 126 runs across six reach radii, seven damping values and three nullspace gains, recording each run’s final distance from the home posture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*4-VVjB3VmwfO1bVv1op02A.png" /><figcaption>End states across 126 runs. The collapsed group is tighter than the measurement noise on any single joint.</figcaption></figure><p>Twenty runs land between 2.671 and 2.673 rad from home. The other 106 stay at or below 1.599. The interval between those clusters holds nothing.</p><p>Matching all seven joint angles rather than the norm makes the point sharper. The twenty collapsed runs finish within 0.0079 rad of each other, with a per-joint standard deviation under 0.003 rad, across three different reach radii and seven damping values. They do not merely share a distance from home. They come to rest in the same posture, every time. The 93 healthy runs are just as consistent in the other direction, finishing within 0.00118 rad of home.</p><h3>A metric that lied to me</h3><p>That grid also exposed a flaw in my own headline number.</p><p>RMS position error mixes two failures that have nothing to do with each other. A run scores badly if it collapses, and it also scores badly if the target was unreachable at the peak, in which case the arm lags through the middle of the trajectory and then comes home fine. Thirteen runs in the grid are the second kind, and at 0.70 m the two coincide closely enough that I never noticed.</p><p>Final position error separates them cleanly. All 106 non-collapsed runs finish within 0.0066 m of the target whatever their RMS says. Posture drift separates them too. If you sweep parameters and choose your outcome metric without care, you can spend a week explaining a single phenomenon that is really two.</p><h3>Does any of this survive a different reach?</h3><p>Here the tidy version of the story dies, and I think the untidy version is worth more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*Xp0-RZj1bL93MrNyQiiXvQ.png" /><figcaption>Collapsed runs by reach radius and nullspace gain. Nothing collapses below 0.70 m, and raising the gain shifts the vulnerable cells rather than clearing them.</figcaption></figure><p>The collapse does not occur below 0.70 m. It appears at 0.70 and widens as the target reaches further. So the interval λ ∈ [5×10⁻⁴, 5×10⁻³] describes one trajectory, not damped least squares. What holds across radii is the mechanism and the posture, while the numbers move.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZXMQiT6dpPMO28YcLygjw.png" /><figcaption>The same grid as a map. The collapse region grows with reach instead of sitting at a fixed interval of damping.</figcaption></figure><p>The nullspace term offers no general cure either. It clears every collapse at 0.70 m by gain 5, yet at 0.72 m a gain of 5 still collapses at two damping values, and at 0.70 m a gain of 2 introduces a collapse that gain 0 avoids. Raising the secondary gain relocates the vulnerable region.</p><p>For reference, I also ran the same trajectory through a QP-based solver, which handles joint and velocity limits as hard constraints. It never collapses. Before crediting the QP formulation for that, note that it also carries a posture task by default, which is the same kind of secondary objective that rescues the DLS side. Its immunity here does not come from the QP alone.</p><h3>What to take from this</h3><p><strong>Damping controls conditioning. It has nothing to say about redundancy.</strong> These two problems get conflated because both surface near singularities. λ keeps JJᵀ invertible, and that is the whole of its job. Where the null direction drifts is a separate question, and on a redundant arm that drift decides whether you can come back.</p><p><strong>A secondary objective earns its place.</strong> I implemented the nullspace projector because it demos well, letting you swing the elbow while the gripper holds still.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*1kS7KEH1BQkUMgfmqQeadg.png" /></figure><p>Setting q̇₀ = Kₙ(q_home − q) costs almost nothing when the arm starts at home, since it pulls toward the posture the arm already holds. Its real job is keeping the solver inside one basin over a long run.</p><p><strong>Correlation near a singularity is worth very little.</strong> Clipping tracked failure at better than 0.95 across the sweep and had no part in causing it. The ablation and the step-level timing settled the question. When a parameter sweep hands you a suspicious pattern, switch the suspected cause off before you write it up.</p><p>If you want to check your own solver for this, three things are cheap to log and tell you most of what you need: the distance from a reference posture at every step, the step index of the first joint-limit clip, and the final error separate from the RMS. Run the same target trajectory at two damping values and diff the joint traces. Divergence that shows up before any limit is touched points at redundancy rather than at your clipping code.</p><h3>Scope</h3><p>One trajectory shape, radial with orientation held constant. One integration gain, one robot. The 0.70 m threshold belongs to this path rather than to the Panda. I have not tested whether the same fold is reachable at shorter reaches under a rotating target or a curved path, and I would expect that it is.</p><h3>References</h3><p>[1] D. E. Whitney, “Resolved motion rate control of manipulators and human prostheses,” <em>IEEE Transactions on Man-Machine Systems</em>, vol. 10, no. 2, pp. 47–53, 1969.</p><p>[2] Y. Nakamura and H. Hanafusa, “Inverse kinematic solutions with singularity robustness for robot manipulator control,” <em>ASME Journal of Dynamic Systems, Measurement, and Control</em>, vol. 108, no. 3, pp. 163–171, 1986.</p><p>[3] C. W. Wampler, “Manipulator inverse kinematic solutions based on vector formulations and damped least-squares methods,” <em>IEEE Transactions on Systems, Man, and Cybernetics</em>, vol. 16, no. 1, pp. 93–101, 1986.</p><p>[4] E. Todorov, T. Erez, and Y. Tassa, “MuJoCo: A physics engine for model-based control,” in <em>Proc. IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS)</em>, 2012, pp. 5026–5033.</p><p>[5] S. Chiaverini, “Singularity-robust task-priority redundancy resolution for real-time kinematic control of robot manipulators,” <em>IEEE Transactions on Robotics and Automation</em>, vol. 13, no. 3, pp. 398–410, 1997.</p><p>[6] A. Liégeois, “Automatic supervisory control of the configuration and behavior of multibody mechanisms,” <em>IEEE Transactions on Systems, Man, and Cybernetics</em>, vol. 7, no. 12, pp. 868–871, 1977.</p><p>[7] S. R. Buss, “Introduction to inverse kinematics with Jacobian transpose, pseudoinverse and damped least squares methods,” unpublished technical note, University of California San Diego, 2004.</p><p>[8] Google DeepMind, “MuJoCo Menagerie: A collection of high-quality models for the MuJoCo physics engine,” 2022. [Online]. Available: <a href="https://github.com/google-deepmind/mujoco_menagerie">https://github.com/google-deepmind/mujoco_menagerie</a></p><p>[9] K. Zakka, “mink: Python inverse kinematics based on MuJoCo,” 2024. [Online]. Available: <a href="https://github.com/kevinzakka/mink">https://github.com/kevinzakka/mink</a></p><p>Code, data and every number quoted here: <a href="https://github.com/luminolous/diffik-panda">github.com/luminolous/diffik-panda</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=005397d7f266" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can RNNs See? Patch-wise Recurrent Models for Image Classification]]></title>
            <link>https://medium.com/@luminolous/can-rnns-see-patch-wise-recurrent-models-for-image-classification-1df6ca9c53d2?source=rss-c8792029593b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1df6ca9c53d2</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Arkananta]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 19:20:21 GMT</pubDate>
            <atom:updated>2026-04-25T19:20:21.336Z</atom:updated>
            <content:encoded><![CDATA[<p>CNNs are usually the first architecture that comes to mind when we talk about image classification. They are naturally designed to capture spatial patterns through convolutional filters. But in this project, I wanted to explore a slightly different question: what if an image is not processed as a 2D grid, but as a sequence of small patches? Inspired by the patch-based idea behind Vision Transformers, this experiment converts BloodMNIST images into patch sequences and feeds them into recurrent models such as RNN, LSTM, GRU, BiLSTM, and BiGRU. A simple CNN is also included as a baseline, so the goal is not only to see whether recurrent models can classify images, but also to understand how close they can get to a conventional vision model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vuR0Xkkubo32RhQiuHCoLw.jpeg" /><figcaption><strong>Figure 1.</strong> Overall illustration of the proposed idea: a blood cell image is converted into a sequence of patch tokens and processed by a recurrent model for classification.</figcaption></figure><h3>Introduction</h3><blockquote>CNNs are the default choice for image classification. But what happens if we treat an image not as a 2D grid, but as a sequence of patches?</blockquote><p>Image classification is often introduced through Convolutional Neural Networks, and for good reason. CNNs are very effective at learning local visual patterns such as edges, textures, shapes, and object parts. Their convolutional filters slide across the image and gradually build higher-level representations from low-level pixels. Because of this, CNNs have become one of the most common starting points for many computer vision tasks.</p><p>However, modern vision models have shown that images do not always need to be processed only as 2D grids. Vision Transformers, for example, split an image into fixed-size patches and treat those patches as a sequence of visual tokens. This idea makes image processing look closer to how text is processed in NLP: instead of words, we have image patches; instead of a sentence, we have a sequence of visual regions. The original Vision Transformer paper showed that a pure Transformer can be applied directly to sequences of image patches for image recognition.</p><p>This experiment takes inspiration from that idea, but with a different direction. Instead of using a Transformer encoder, I use recurrent neural networks to process the patch sequence. The image is divided into small patches, each patch is flattened into a vector, and the resulting sequence is passed into several recurrent architectures: vanilla RNN, LSTM, BiLSTM, GRU, and BiGRU. To make the comparison more meaningful, I also train a CNN baseline on the same dataset.</p><p>The main question is simple: can recurrent models “see” images when the images are represented as sequences? More specifically, how much do positional encodings help, and which recurrent architecture works best for this patch-wise image classification setup?</p><h4>CNN Path:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*45F_1ex5pwWMl7sW0ihViA.png" /><figcaption><strong>Figure 2.</strong> The CNN baseline processes the image as a 2D grid using convolution blocks, global pooling, and a final classifier.</figcaption></figure><h4>Sequential Path:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*ELjGIIjfo9Ry9A73FscFMw.png" /><figcaption><strong>Figure 3.</strong> The sequential path converts the image into patches, embeds them as visual tokens, and feeds the sequence into an RNN-family model.</figcaption></figure><h3><strong>Dataset: BloodMNIST</strong></h3><p>I used BloodMNIST, one of the datasets from the <a href="https://medmnist.com/">MedMNIST collection</a>. <a href="https://medmnist.com/">MedMNIST</a> is a lightweight biomedical image classification benchmark designed to make medical image experiments easier to run and compare. It contains multiple standardized 2D and 3D biomedical datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*5QiTeg2DZd5tlyaWe525Qg.png" /><figcaption><strong>Figure 4.</strong> Example images from the BloodMNIST dataset. Each image represents one of the eight blood cell categories used in this classification task.</figcaption></figure><p>BloodMNIST contains images of individual blood cells and is organized into 8 classes: basophil, eosinophil, erythroblast, immature granulocytes, lymphocyte, monocyte, neutrophil, and platelet. The dataset contains 17,092 images in total and follows a predefined train-validation-test split with a 7:1:2 ratio. In this notebook, I used the 224×224 version of the dataset so that the images could be divided cleanly into 16×16 patches.</p><p>The task is a multi-class classification problem. Given an input blood cell image, the model needs to predict which of the 8 cell categories it belongs to. Since the dataset already provides official splits, the experiment can focus more on model behavior rather than dataset preparation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*r3KJ8stwGU4Rpi2_tcWofw.png" /><figcaption><strong>Figure 5.</strong> Training class distribution of BloodMNIST.</figcaption></figure><h3><strong>Turning Image into Sequences</strong></h3><p>The key idea of this project is to convert an image into a sequence. Instead of feeding the whole image directly into a CNN, the image is divided into smaller non-overlapping patches. Each patch is then flattened into a vector, and all patch vectors are arranged in order from left to right and top to bottom. This creates a sequence representation of the image.</p><p>In this experiment, every image has a size of 224×224 pixels with 3 color channels. I used a patch size of 16×16. This means each image is divided into a 14×14 grid of patches, resulting in 196 patches in total. Each patch contains 3×16×16 values, so every patch becomes a 768-dimensional vector.</p><pre>Image size  = 224 × 224<br>Patch size  = 16 × 16<br>Patch grid  = 224 / 16 = 14 patches per side<br>Total patch = 14 × 14 = 196 patches<br>Patch dim   = 3 × 16 × 16 = 768</pre><p>From this equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*ncHk49XODZeOIGOtIfpIcg.png" /></figure><p>And then, we can put the configuration…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*NrBLkGDS46K0D3sFyE9w2Q.png" /></figure><p>So the sequence form is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*nExGy-w53MlGjoU1NtUBWw.png" /></figure><p><strong><em>B</em></strong> is the batch size, 196 is the number of patch tokens, and 768 is the feature dimension of each patch. In other words, each image is no longer represented as a tensor of shape <strong>3 × 224 × 224</strong>, but as a sequence of 196 visual tokens.</p><p>This representation makes the image compatible with sequential models. The recurrent model reads the patch sequence step by step, just like it would read a sentence token by token. The difference is that each token is not a word, but a small region of the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*Z41U9PI7Jk6zLebxLHVp3w.png" /><figcaption><strong>Figure 6.</strong> Example of patch extraction, where a BloodMNIST image is divided into non-overlapping 16×16 patches before being converted into a sequence.</figcaption></figure><h4>Patch Projection</h4><p>Before the patch sequence is passed into the recurrent model, each 768-dimensional patch vector is projected into a smaller embedding dimension. In this experiment, the patch vectors are projected into 256-dimensional embeddings. This step works like a visual token embedding layer: instead of asking the model to process raw pixel values directly, we first transform each patch into a compact learnable representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*mmhXncAS4NcEOT2k3iJzrw.png" /></figure><p>This projection is useful for two reasons. First, it reduces the patch dimension from 768 to 256, making the sequence representation more compact. Second, it gives the model a learnable feature space for each patch before the sequence is processed by RNN, LSTM, GRU, or their bidirectional variants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*Jjssmpa-PZV1HpXKUB1_aA.png" /></figure><p>After this step, each image is represented as a sequence of 196 patch embeddings. Each token in the sequence corresponds to one visual region of the original image.</p><h3>Why Positional Encoding Matters</h3><p>Once an image is converted into a sequence, one important problem appears: the model needs to know where each patch came from. A patch from the top-left corner and a patch from the bottom-right corner may have completely different meanings, even if their pixel values look similar. Without positional information, the sequence model only receives patch contents, but not their spatial location.</p><p>To study this, I tested three input scenarios. The first scenario uses patch embeddings only, without explicit positional information. The second scenario adds 1D learnable positional encoding, where every patch index has its own position embedding. The third scenario uses 2D learnable positional encoding, where row and column embeddings are added to preserve the grid structure of the image.</p><p><strong>1D Positional Encoding:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*2gNwtQxd-9xZxha2TzuciQ.png" /></figure><p><strong>2D Positional Encoding:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*VFDiwcP4tqwZxci8_nw6rg.png" /></figure><p>The 1D version treats the image as a flat sequence of patch indices, while the 2D version keeps the idea that the image originally came from a grid. This makes the comparison interesting: does the model only need patch order, or does it benefit from a more spatially aware positional representation?</p><h3><strong>Model Architecture</strong></h3><p>In this experiment, I compared a simple CNN baseline with several recurrent neural network variants. The CNN serves as the conventional image classification baseline, while the recurrent models are used to test whether an image can be classified effectively after being converted into a sequence of patches. For the sequential models, each image is represented as a sequence of 196 patch tokens, and each token is processed step by step by the recurrent architecture.</p><p>The recurrent models used in this experiment are Vanilla RNN, LSTM, BiLSTM, GRU, and BiGRU. All of them receive the same patch-based image representation, but they differ in how they store, update, and propagate information across the sequence.</p><h4>CNN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RiBUDEEV18TmfqGbPYI8Q.png" /><figcaption><strong>Figure 7.</strong> A general CNN architecture showing how convolution, pooling, flattening, and fully connected layers transform an input image into class predictions. Image Source: <a href="https://www.quarkml.com/2023/06/introduction-to-convolutional-neural-networks.html">Quark Machine Learning</a>.</figcaption></figure><p>Before testing the recurrent models, I used a simple CNN as the baseline. This baseline represents the more conventional way of solving image classification problems. Instead of converting the image into a sequence, the CNN directly processes the image as a 2D grid using convolutional layers.</p><p>The CNN architecture consists of three convolutional blocks. Each block contains convolution, batch normalization, ReLU activation, and max pooling. After the feature extraction stage, adaptive average pooling is applied, followed by a fully connected classifier.</p><p><strong>Architecture design:</strong></p><pre>Input image: 3 × 224 × 224<br>↓<br>ConvBlock: 3 → 64<br>↓<br>ConvBlock: 64 → 128<br>↓<br>ConvBlock: 128 → 256<br>↓<br>Adaptive Average Pooling<br>↓<br>Linear Classifier<br>↓<br>8-class prediction</pre><p>This CNN baseline is useful because it gives a reference point for how well a standard vision model performs on BloodMNIST. If the recurrent models can approach the CNN baseline, it suggests that patch-wise sequential modeling can be a reasonable alternative representation for image classification.</p><h4><strong>Vanilla RNN</strong></h4><p>The first recurrent model is the Vanilla RNN. This is the simplest recurrent architecture in the experiment. It processes the patch sequence one token at a time and updates its hidden state based on the current patch embedding and the previous hidden state. In this setup, the model reads the image patches from the top-left region to the bottom-right region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*4CyEuT665DTsgv167MEs1A.png" /></figure><p><strong><em>z_t</em></strong>​ is the patch embedding at step <strong><em>t</em></strong>, <strong><em>h_t-1</em></strong>​ is the previous hidden state, and <strong><em>h_t</em></strong>​ is the updated hidden representation. After the whole patch sequence is processed, the final hidden state is used as the image-level feature for classification.</p><p>However, Vanilla RNNs often struggle with long sequences because information from earlier steps can gradually fade as the sequence gets longer. In this experiment, one image becomes 196 patch tokens, which is already a relatively long sequence for a simple recurrent model. This makes Vanilla RNN an important baseline, but not necessarily the strongest candidate.</p><h4><strong>LSTM</strong></h4><p>Long Short-Term Memory, or LSTM, is designed to handle longer sequences better than Vanilla RNN. Instead of using only a simple hidden state update, LSTM introduces a memory cell and several gates. These gates control which information should be remembered, updated, or forgotten.</p><p>In the context of this experiment, the LSTM reads the image patch sequence and tries to decide which visual patterns should be kept across the sequence. This is useful because a blood cell image may contain important visual cues that appear in different patch locations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*CfVO34B8jVaynQVMw_khzA.png" /></figure><p><strong><em>h_t</em></strong>​ is the hidden state and <strong><em>c_t</em></strong>​ is the cell state. The cell state acts like a memory path that helps the model preserve useful information over longer sequences.</p><h4><strong>BiLSTM</strong></h4><p>BiLSTM extends LSTM by reading the sequence in two directions: forward and backward. The forward LSTM reads the patch sequence from the first patch to the last patch, while the backward LSTM reads it from the last patch to the first patch.</p><p>Simple equation for forward and backward direction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*Pq_FVZDyaufdUlgHRBBT5Q.png" /></figure><p>and then, the final feature is…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*epSsWbAqv3uSX5bMN3_QDg.png" /></figure><p>This bidirectional setup allows the model to use information from both directions of the patch sequence. In image terms, this means the representation is not only influenced by patches that appear earlier in the scan order, but also by patches that appear later.</p><p>Since an image does not naturally have a single reading direction like a sentence, bidirectional processing can be useful. It gives the model a more complete view of the patch sequence before making the final prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*9uM2BCusY8sMw-ROnzswMA.png" /><figcaption><strong>Figure 8.</strong> Bidirectional recurrent models read the patch sequence from both directions.</figcaption></figure><h4><strong>GRU</strong></h4><p>Gated Recurrent Unit, or GRU, is another gated recurrent architecture. Compared to LSTM, GRU is usually simpler because it does not use a separate cell state. Instead, it uses gates to control how much past information should be kept and how much new information should be added.</p><p>In this experiment, GRU is interesting because it offers a balance between simplicity and memory control. It is more expressive than Vanilla RNN, but usually lighter than LSTM. This makes it a strong candidate for processing patch sequences efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*ufPOJs_SOS561dPmhCgBqg.png" /></figure><p>The update gate controls how much previous information is carried forward, while the reset gate helps decide how much past information should be ignored when computing the new candidate state.</p><h4><strong>BiGRU</strong></h4><p>BiGRU is the bidirectional version of GRU. Similar to BiLSTM, it processes the patch sequence in both forward and backward directions. The final feature is created by concatenating the last hidden state from the forward GRU and the last hidden state from the backward GRU.</p><p>This model is especially important in this experiment because it combines two useful properties: gated memory updates and bidirectional sequence reading. The gates help the model handle long patch sequences, while the bidirectional structure allows the classifier to use context from both directions.</p><p>In a patch-wise image classification setup, this can be useful because the meaning of one patch may depend on visual patterns that appear before or after it in the flattened sequence.</p><h4>Classification Head</h4><p>After the recurrent layer processes the patch sequence, the model takes the final hidden representation as the image-level feature. For bidirectional models, the final forward and backward hidden states are concatenated. Then, this feature is normalized, passed through dropout, and finally projected into 8 output classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*LcBbAbDp6D4WlWe9eGjNHg.png" /></figure><p>The output logits are then used to compute the cross-entropy loss during training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*2Z4RUT7-plryoGbGmR3HHg.png" /></figure><p>In this task, <strong><em>K=8</em></strong>, because BloodMNIST contains eight blood cell classes.</p><pre>if self.bidirectional:<br>    last_forward = h_n[-2]<br>    last_backward = h_n[-1]<br>    final_feature = torch.cat([last_forward, last_backward], dim=1)<br>else:<br>    final_feature = h_n[-1]<br><br>final_feature = self.norm(final_feature)<br>final_feature = self.dropout(final_feature)<br>logits = self.classifier(final_feature)</pre><blockquote>This snippet shows how the final hidden state is converted into class logits. For bidirectional models, the forward and backward final states are concatenated before classification.</blockquote><h3><strong>Experiment Scenario</strong></h3><p>The experiment is designed to answer a simple question: if an image is converted into a sequence of patches, how well can recurrent models classify it? To make the comparison more informative, I tested three patch-wise recurrent scenarios and one CNN baseline. The CNN baseline represents the standard image-based approach, while the recurrent scenarios represent different ways of adding spatial information to the patch sequence.</p><h4>Scenario 1: CNN</h4><p>The first scenario uses a CNN. In this setup, the image is processed directly as a 2D grid. No patch extraction or sequence conversion is applied. The goal of this scenario is to provide a conventional computer vision reference point.</p><pre>Image → CNN Feature Extractor → Global Pooling → Classifier</pre><p>This baseline helps answer whether patch-wise recurrent models can become competitive with a standard convolutional approach.</p><h4>Scenario 2: Image Patch Only</h4><p>The second scenario uses only image patches without positional encoding. Each image is divided into 196 patches, and each patch is flattened into a 768-dimensional vector. The resulting sequence is passed directly into the recurrent model.</p><p><strong>Pipeline:</strong></p><pre>Image → Patch Extraction → Patch Sequence → RNN / LSTM / BiLSTM　/ GRU / BiGRU → Classifier</pre><p>This scenario tests whether the recurrent model can learn useful visual patterns from the patch sequence alone. However, the limitation is that the model receives patch content but no explicit positional information. It knows the order of the sequence, but the spatial structure of the original 2D image is not directly encoded.</p><p>In this patch-only setup, each patch is represented by its raw flattened pixel values. Therefore, the recurrent input size is 768.</p><h4>Scenario 3: Image Patch + 1D Positional Encoding</h4><p>The third scenario adds learnable 1D positional encoding to the patch sequence. Before entering the recurrent model, each raw patch vector is projected into a 256-dimensional embedding. Then, a learnable positional embedding is added to each patch token based on its index in the flattened sequence.</p><p><strong>Pipeline:</strong></p><pre>Image → Patch Extraction → Patch Projection → 1D Positional Encoding → Recurrent Model (RNN / LSTM / BiLSTM / GRU / BiGRU) → Classifier</pre><p>This scenario tests whether giving each patch a learnable position index helps the recurrent model understand the order of visual tokens. It is similar in spirit to the way patch-based vision models use positional information to distinguish one patch location from another. Vision Transformers also use patch embeddings and position embeddings because the model needs information about where each patch comes from in the original image.</p><pre>x = self.patch_projection(x)  # [B, num_patches, embed_dim]<br><br>if self.use_positional_embedding:<br>    x = x + self.pos_embedding</pre><blockquote>The 1D positional encoding is added after patch projection and before the recurrent layer.</blockquote><h4>Scenario 4: Image Patch + 2D Positional Encoding</h4><p>The fourth scenario uses 2D learnable positional encoding. Instead of assigning a single positional vector to each flattened patch index, the model uses separate row and column embeddings. This is closer to the original image structure because each patch comes from a specific row and column in the 14×14 patch grid.</p><p><strong>Pipeline:</strong></p><pre>Image → Patch Extraction → Patch Projection → 2D Row + Column Positional Encoding → Recurrent Model (RNN / LSTM / BiLSTM / GRU / BiGRU) → Classifier</pre><p>This scenario tests whether preserving the 2D grid structure helps the recurrent model understand spatial relationships better than a simple 1D patch index.</p><pre>x = self.patch_projection(x)  # [B, num_patches, embed_dim]<br><br>x = x.view(B, self.grid_h, self.grid_w, self.embed_dim)<br><br>pos_2d = self.row_embedding + self.col_embedding<br>x = x + pos_2d<br><br>x = x.view(B, self.num_patches, self.embed_dim)</pre><blockquote>In the 2D positional encoding setup, the patch sequence is temporarily reshaped back into a 14×14 grid so row and column embeddings can be added.</blockquote><h4>Model Variants Tested in Each Sequential Scenario</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*zKBTjq4jyf14yOrOjNqSRw.png" /><figcaption><strong>Table 1.</strong> Summary of the input representation, positional information, and model variants used in each experimental scenario.</figcaption></figure><p>This setup allows the experiment to separate two questions. First, which recurrent architecture works best for patch-wise image classification? Second, how much does positional information matter when an image is represented as a sequence?</p><h4>Training Configuration</h4><p>All models were trained using the same general training strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*NlVkzvLkXPc_6sWPIEBNew.png" /><figcaption><strong>Table 2.</strong> Training configuration used for the patch-wise recurrent models, including patch size, hidden size, optimizer, and evaluation metric.</figcaption></figure><p>Macro-F1 is used as the main evaluation metric because this is an 8-class classification problem. Unlike accuracy, macro-F1 gives equal importance to every class by averaging the F1-score across all classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*-JFOTVNA0ho8-RW6iGT_qA.png" /></figure><h4>Multi-seed Evaluation</h4><p>To reduce the effect of randomness, each architecture was trained using multiple random seeds. This makes the comparison more reliable than a single training run, because neural network performance can vary depending on initialization, data shuffling, and other stochastic factors.</p><pre>Seeds: 13, 27, 42, 123, 3407</pre><p>The final result is reported using the mean and standard deviation across seeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*dpCwPF-RtoUH1CJEaX6epw.png" /></figure><h3><strong>Results and Discussion</strong></h3><p>After training the CNN baseline and all patch-wise recurrent models, I evaluated each model using test accuracy, precision, recall, and macro-F1. Since BloodMNIST is an 8-class classification problem, macro-F1 is especially useful because it gives each class the same importance, instead of letting the largest class dominate the final score.</p><p>I focus mainly on macro-F1 because it gives a more balanced view of model performance across all blood cell categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*-JFOTVNA0ho8-RW6iGT_qA.png" /></figure><h4>Overall Result</h4><p>The table below summarizes the best-performing model from each experimental scenario. The CNN baseline represents the conventional image classification approach, while the other three scenarios represent the patch-wise recurrent approach with different positional encoding strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*LLm1CAvPx3T-01J9ZM2O8A.png" /><figcaption><strong>Table 3.</strong> Overall comparison between the CNN baseline and the best-performing patch-wise recurrent model from each scenario.</figcaption></figure><p>The first thing that stands out is that the CNN basline is still very strong. It achieved the best single-run macro-F1 score of 0.9755, which is the highest single result in the experiment. However, the patch-wise recurrent models, especially BiGRU with positional encoding, came surprisingly close.</p><p>The best average result among all scenarios came from <strong>BiGRU with 1D positional encoding</strong>, reaching <strong>0.9573 ± 0.0063 macro-F1</strong>. This is slightly higher than the CNN baseline average of <strong>0.9569 ± 0.0244</strong>, although the difference is very small. Because of that, I would not frame this as “BiGRU beats CNN,” but rather as a more careful finding: <strong>patch-wise BiGRU can be highly competitive with a simple CNN baseline on BloodMNIST.</strong></p><h4>Result by Sequential Architecture</h4><p>To understand the behavior of each recurrent model more clearly, I also compared RNN, LSTM, BiLSTM, GRU, and BiGRU under the three patch-wise scenarios.</p><p><strong>1. Image Patch Only</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*eW2yEYFB1UWBjEQLfz8tlw.png" /><figcaption><strong>Table 4.</strong> Performance comparison of recurrent architectures in the image patch-only scenario without explicit positional encoding.</figcaption></figure><p>Without positional encoding, GRU and BiGRU already performed much better than the other recurrent variants. This suggests that gated recurrent models are more suitable for processing long image patch sequences than vanilla RNN or even LSTM in this setup.</p><p><strong>2. Image Patch + 1D Positional Encoding</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*lVJ2AHvjvj2rKdhFH9qEHw.png" /><figcaption><strong>Table 5.</strong> Performance comparison of recurrent architectures when 1D learnable positional encoding is added to the patch sequence.</figcaption></figure><p>The 1D positional encoding scenario produced the strongest average result in the entire experiment. BiGRU achieved <strong>0.9573 macro-F1</strong>, while GRU also performed strongly with <strong>0.9509 macro-F1</strong>. This shows that adding learnable patch-index information helps the model understand the order of patch tokens more effectively.</p><p><strong>3. Image Patch + 2D Positional Encoding</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*udPEpIrARLhhMhuAZeo9yg.png" /><figcaption><strong>Table 6.</strong> Performance comparison of recurrent architectures when 2D row-and-column positional encoding is added to the patch sequence.</figcaption></figure><p>The 2D positional encoding scenario was also very competitive. BiGRU reached <strong>0.9564 macro-F1</strong> on average and achieved the best recurrent single-run macro-F1 score of <strong>0.9679</strong>. However, it did not clearly outperform the 1D positional encoding setup. This is an interesting result because 2D positional encoding seems more spatially informative, but in this experiment, the simpler 1D positional encoding gave the best average performance.</p><h4>Discussion</h4><p><strong>1. CNN is still a strong baseline</strong></p><p>The CNN baseline remains a very strong reference point. This is expected because CNNs are naturally designed to process images as 2D grids. Their convolutional filters can capture local spatial patterns such as edges, textures, and cell morphology. In this experiment, the CNN achieved the best single-run macro-F1 score, showing that convolution is still highly effective for BloodMNIST classification.</p><p>However, the interesting part is not that CNN performs well. The interesting part is that the patch-wise recurrent models can get very close. This suggests that image classification can also be approached from a sequence modeling perspective, as long as the image is represented properly.</p><p><strong>2. Patch-wise recurrent models can be surprisingly competitive</strong></p><p>The best recurrent model, BiGRU with 1D positional encoding, reached <strong>0.9573 ± 0.0063 macro-F1</strong>, which is almost identical to the CNN baseline average. This means that after converting images into patch sequences, recurrent models are still able to learn useful visual representations.</p><p>This result is conceptually related to the patch-based idea used in Vision Transformers. ViT treats an image as a sequence of patches, linearly embeds those patches, adds positional embeddings, and then processes the resulting sequence with a Transformer encoder. In this project, I used a similar patch-sequence representation, but replaced the Transformer with recurrent models.</p><p><strong>3. Vanilla RNN struggles with long patch sequences</strong></p><p>Vanilla RNN performed poorly in all three sequential scenarios. Its macro-F1 stayed around <strong>0.20–0.22</strong>, which is far below the gated recurrent models. This result is not too surprising. In this setup, each image becomes a sequence of <strong>196 patch tokens</strong>, and vanilla RNNs are known to struggle when useful information needs to be preserved across long sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*_9-MDfRdgRlnI9e-x78fdw.png" /><figcaption><strong>Table 7.</strong> Vanilla RNN performance across all sequential scenarios, showing its difficulty in handling long patch sequences.</figcaption></figure><p>This tells us that simply converting an image into a sequence is not enough. The architecture also needs a strong mechanism for remembering and updating information across the sequence.</p><p><strong>4. GRU and BiGRU are the most stable recurrent models</strong></p><p>Across all patch-wise scenarios, GRU and BiGRU consistently achieved the best results among the recurrent architectures. This suggests that their gating mechanism is well-suited for this task. GRU uses gates to control how much previous information should be kept and how much new information should be added at each step. The original GRU-based encoder-decoder work introduced this gated recurrent unit as a way to learn sequence representations more effectively.</p><p>BiGRU adds another advantage: it reads the sequence in both directions. In image terms, this means the model is not forced to rely only on a top-left to bottom-right scan order. It can also use information from the reverse direction, which may help create a more complete image-level representation.</p><p>This explains why BiGRU became the strongest recurrent model in all three scenarios.</p><p><strong>5. Positional encoding helps, but 2D is not automatically better</strong></p><p>Positional encoding clearly improved the performance of the best recurrent model. Without positional encoding, BiGRU achieved <strong>0.9410 macro-F1</strong>. After adding 1D positional encoding, the score increased to <strong>0.9573 macro-F1</strong>. With 2D positional encoding, BiGRU achieved <strong>0.9564 macro-F1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*u9J-MSzwGpo62bOQFO9B3A.png" /><figcaption><strong>Table 8.</strong> BiGRU performance across patch-only, 1D positional encoding, and 2D positional encoding scenarios.</figcaption></figure><p>This shows that positional information matters. When an image is flattened into a sequence, the model needs some way to understand where each patch originally came from. This is also why patch-based vision models usually add positional embeddings after patch projection.</p><p>However, the 2D positional encoding did not clearly outperform 1D positional encoding. The 2D version is more spatially explicit because it uses row and column embeddings, but the simpler 1D version gave the best average result in this experiment. One possible explanation is that the recurrent scan order already provides enough structured information, so a learnable 1D patch index may be sufficient for this dataset.</p><h4>Limitations</h4><p>There are several limitations in this experiment. First, the CNN baseline is relatively simple, so the comparison does not include stronger architectures such as ResNet, EfficientNet, ConvNeXt, or Vision Transformer. Second, the experiment only uses BloodMNIST, so the conclusion may not directly generalize to larger or more complex image datasets. Third, the patch-wise recurrent models process a sequence of 196 tokens, which may become expensive or harder to optimize if the image resolution increases or the patch size becomes smaller.</p><h4>Conclusion</h4><p>This experiment started with a simple question: can RNNs see? The answer is yes, but with some important conditions. A vanilla RNN is not enough, but gated recurrent models such as GRU and BiGRU can learn useful visual patterns from image patch sequences. With positional encoding, BiGRU achieved performance that was highly competitive with the CNN baseline on BloodMNIST.</p><p>CNNs still remain a strong and natural choice for image classification. However, this project shows that image classification can also be explored through a sequential modeling lens. By turning images into patch sequences, recurrent models can process visual data in a way that is different from convolution, yet still surprisingly effective.</p><h3><strong>References</strong></h3><ul><li>Yang, J., Shi, R., Wei, D., Liu, Z., Zhao, L., Ke, B., Pfister, H., &amp; Ni, B. <strong>MedMNIST v2: A Large-Scale Lightweight Benchmark for 2D and 3D Biomedical Image Classification.</strong> <em>Scientific Data</em>, 2023.</li><li>MedMNIST Official Website. <strong>MedMNIST: A large-scale MNIST-like collection of standardized biomedical images.</strong></li><li>Dosovitskiy, A., Beyer, L., Kolesnikov, A., et al. <strong>An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale.</strong></li><li>Hochreiter, S., &amp; Schmidhuber, J. <strong>Long Short-Term Memory.</strong> <em>Neural Computation</em>, 1997.</li><li>Cho, K., van Merriënboer, B., Gulcehre, C., Bahdanau, D., Bougares, F., Schwenk, H., &amp; Bengio, Y. <strong>Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation.</strong> EMNLP, 2014.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1df6ca9c53d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>