<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Valentin von Bornhaupt</title>
<link>https://vavobo.de/</link>
<atom:link href="https://vavobo.de/index.xml" rel="self" type="application/rss+xml"/>
<description>Blog and Website of Valentin von Bornhaupt, ML Engineer</description>
<generator>quarto-1.10.18</generator>
<lastBuildDate>Wed, 25 Nov 2026 23:00:00 GMT</lastBuildDate>
<item>
  <title>RapidParc</title>
  <link>https://vavobo.de/posts/rapid_parc.html</link>
  <description><![CDATA[ 





<p><a href="https://github.com/MedVisBonn/RapidParc"><img src="https://img.shields.io/badge/GitHub-181717?logo=github.png" class="img-fluid" alt="Github Repository"></a> <a href="https://pypi.org/project/RapidParc/"><img src="https://img.shields.io/pypi/v/RapidParc.svg?logo=pypi&amp;label=PyPI" class="img-fluid" alt="PyPI - RapidParc"></a> <a href="https://doi.org/10.1162/IMAG.a.1168"><img src="https://img.shields.io/badge/DOI-10.1162%2FIMAG.a.1168-brightgreen" class="img-fluid" alt="Paper DOI"></a></p>
<section id="introduction" class="level1">
<h1>Introduction</h1>
<p>RapidParc is the framework and paper that resulted from my master’s thesis.</p>
<p>Most likely, you are not familiar with tractograms if you have never dug into the medical neuroimaging domain. Using diffusion MRI (dMRI) techniques and processing (“tractography”), we can obtain models of nerve fibers (<a href="https://www.youtube.com/watch?v=Be51OqnBbdc">Video</a>, <a href="https://en.wikipedia.org/wiki/Tractography">Wiki</a>). Each of these nerve fiber models is called a <em>streamline</em>. We call all streamlines of the brain a <em>tractogram</em>. A streamline is coarser than an actual nerve fiber because dMRI has a relatively coarse voxel resolution (<img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bmm%7D"> vs <img src="https://latex.codecogs.com/png.latex?%5Cmu%5Ctext%7Bm%7D">).</p>
<p>But for further scientific investigation, it would be great to have them segmented into white matter tracts. There already exist methods for segmenting tractograms, like TractCloud and DeepWMA. But these methods require at least 100 seconds for a tractogram with 1 million streamlines on an NVIDIA A100 machine and more than 1000 seconds (~17 minutes) on a CPU-only machine (which is more relevant for many clinical scenarios). During my master’s thesis, I developed a framework that is 100x faster while increasing prediction accuracy. These findings resulted in the open-source framework <a href="https://github.com/MedVisBonn/RapidParc/tree/main">RapidParc</a> and the peer-reviewed paper (shared first authorship):</p>
<blockquote class="blockquote">
<p><strong>Valentin von Bornhaupt</strong>, <strong>Justus Bisten</strong><sup>1</sup>, Johannes Grün, Tobias Bauer, Theodor Rüber, Thomas Schultz.<br>
<em>RapidParc: A Global-Context Transformer for Parallel, Accurate, and Lesion-Robust Tractogram Parcellation.</em><br>
<em>Imaging Neuroscience</em> (2026). DOI: <a href="https://doi.org/10.1162/IMAG.a.1168">10.1162/IMAG.a.1168</a></p>
</blockquote>
<p>Even though I am writing this blog post as an individual, I would like to emphasize that the achievements are the result of the work of all those involved. In particular, I would like to highlight Justus Bisten’s model improvements regarding post-hemispherotomy robustness and his extensive TractCloud-variant and tractography comparisons. Thomas Schultz and Johannes Grün advised and supported me while I was working on this master’s thesis. I enjoyed the productive brain storming sessions with you. Many thanks also to Prof.&nbsp;Jan Hasenauer, who co-supervised my thesis, and to Tobias Bauer and Theodor Rüber, who provided post-hemispherotomy data.</p>
</section>
<section id="what-made-this-project-rather-complex" class="level1">
<h1>What made this project rather complex?</h1>
<section id="core-problem-definition" class="level2">
<h2 class="anchored" data-anchor-id="core-problem-definition">Core Problem Definition</h2>
<ul>
<li><strong>Given:</strong> A tractogram of a subject, i.e., a set of <img src="https://latex.codecogs.com/png.latex?%5Capprox"> 1 million streamlines (3D paths). Each streamline is a list of 3D coordinates (supporting points).</li>
<li><strong>Task:</strong> Assign each streamline to one of 42 anatomical classes and one outlier class.</li>
</ul>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://vavobo.de/posts/rapidparc_resources/tractogram_carousel.webp" class="img-fluid figure-img" style="width:60.0%"></p>
<figcaption>Tractogram Classification</figcaption>
</figure>
</div>
</section>
<section id="a-tractogram-a-set-of-paths-all-different-lengths" class="level2">
<h2 class="anchored" data-anchor-id="a-tractogram-a-set-of-paths-all-different-lengths">A Tractogram: A Set of Paths, All Different Lengths</h2>
<p>Each streamline can have a different number of supporting points, which complicates batch processing. To account for this, RapidParc’s approach is to map every streamline to a fixed-size vector and process bags of these vectors in parallel.</p>
<p>The solution: <strong>resample to 15 (or 8) supporting points</strong> per streamline (as done in DeepWMA<sup>2</sup> (2020) and TractCloud<sup>3</sup> (2023)).</p>
</section>
<section id="flip-invariance" class="level2">
<h2 class="anchored" data-anchor-id="flip-invariance">Flip-Invariance</h2>
<p>There is no unique way to store an undirected path as a vector. Which end do you start from? But I developed a method for it. See more in my separate post on <a href="../posts/flip_invariance.html">my <em>flip-invariant embedding</em></a>.</p>
<div id="fig-PCA-original" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-PCA-original-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/flip_inv_resources/1_PCA_original.webp" class="img-fluid figure-img" style="width:80.0%">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-PCA-original-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: PCA of streamlines without flip-invariant embedding
</figcaption>
</figure>
</div>
<div id="fig-PCA-flip-inv" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-PCA-flip-inv-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/flip_inv_resources/2_PCA_flip_inv_embedding.webp" class="img-fluid figure-img" style="width:80.0%">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-PCA-flip-inv-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: PCA of flip-invariant embedded streamlines
</figcaption>
</figure>
</div>
</section>
<section id="registration-free-approach" class="level2">
<h2 class="anchored" data-anchor-id="registration-free-approach">Registration-Free Approach</h2>
<p>Tractograms are highly individual, as they reflect the neural connections within a subject’s brain. While children have small brains and adults have large ones, some people have narrower or wider brains than others (scaling).</p>
<p>Furthermore, tractograms depend on the dMRI imaging conditions: How was the subject positioned in the MRI scanner (rotation, translation)?</p>
<p>There are two main approaches to handle these differences in the domain of tractogram segmentation:</p>
<ul>
<li>Methods like DeepWMA register unseen tractograms to a common template (by applying linear rotations, translations and scalings). Streamlines taken from registered tractograms can be classified using simpler, path-wise classification methods. But registration is expensive (time + compute) and is typically designed for healthy anatomy. What if subjects have altered white matter (e.g., due to heavy lesions, tumors or post-hemispherotomy)? Registration can fail, causing the whole pipeline to fail.</li>
<li>Methods like TractCloud and RapidParc are <strong>registration-free</strong>, i.e., they process tractograms without prior registration. But if a tractogram is not registered, streamline-wise classification is no longer possible: The raw coordinates of a streamline taken from a five-year-old child behave totally differently from those of a 67-year-old adult. Therefore, the model needs global context about the entire tractogram.</li>
</ul>
<section id="how-rapidparc-became-registration-free" class="level3">
<h3 class="anchored" data-anchor-id="how-rapidparc-became-registration-free">How RapidParc Became Registration-Free</h3>
<ol type="1">
<li><strong>Tractogram Normalization:</strong> We normalize every tractogram to <img src="https://latex.codecogs.com/png.latex?%5B-1,%5C,%201%5D%5E3"> using min-max scaling. This prevents any dependency on (axis-specific) scaling and translation.</li>
<li><strong>Data Augmentations:</strong> During training, we applied random data augmentations:
<ul>
<li>Random rotations by <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BUnif%7D(%5B-45%5E%5Ccirc,%2045%5E%5Ccirc%5D)"> on the left-right axis</li>
<li>Random rotations by <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BUnif%7D(%5B-10%5E%5Ccirc,%2010%5E%5Ccirc%5D)"> for both the anterior-posterior and superior-inferior axes</li>
<li>Small additive Gaussian noise <img src="https://latex.codecogs.com/png.latex?%5Cmathcal%7BN%7D(0,%20%5C,0.001%5E2)"> to every supporting point</li>
</ul></li>
<li><strong>Transformer Model:</strong> I created a novel Transformer-based set segmentation pipeline. Please see Section&nbsp;2.5 and read the <a href="../posts/monte_carlo_set_segmentation.html">interactive post</a> to understand how it works.</li>
</ol>
<section id="improvement-1-even-more-augmentations" class="level4">
<h4 class="anchored" data-anchor-id="improvement-1-even-more-augmentations">Improvement 1: Even More Augmentations</h4>
<p>The transformer model is trained on multiple subsets of tractograms in parallel. I thought: What if we apply a different augmentation to every sub-tractogram? In fact, this inflates the number of augmentations per training run to 3.5 million and therefore approximates the desired registration-free behavior even more closely.</p>
</section>
<section id="improvement-2-data-augmentations-on-gpu---double-throughput" class="level4">
<h4 class="anchored" data-anchor-id="improvement-2-data-augmentations-on-gpu---double-throughput">Improvement 2: Data &amp; Augmentations on GPU - Double Throughput</h4>
<p>At one point, I noticed that the data transfer from CPU to GPU took a lot of time during training. The dataset is small enough to fit permanently on the GPU during training. So I refactored the training pipeline to keep the dataset permanently on the GPU and run all preprocessing and augmentations directly on-device. This doubled the training throughput.</p>
</section>
</section>
</section>
<section id="sec-model-selection" class="level2">
<h2 class="anchored" data-anchor-id="sec-model-selection">Model Selection: How to Scale to 1 Million Streamlines?</h2>
<p>Please read my post on the <a href="../posts/monte_carlo_set_segmentation.html">model mechanism</a>. The linked method is so <em>rapidly</em> because it is a Monte Carlo method for approximating the global tractogram state while classifying whole sub-tractograms all at once.</p>
<div id="fig-inference-pipeline" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-inference-pipeline-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/rapidparc_resources/method_inference.webp" class="img-fluid figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-inference-pipeline-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: RapidParc Inference Pipeline
</figcaption>
</figure>
</div>
</section>
</section>
<section id="results" class="level1">
<h1>Results</h1>
<p>There are two main results:</p>
<ol type="1">
<li>RapidParc is at least two orders of magnitude faster than other SOTA methods. Vanilla TractCloud uses k-Nearest Neighbors (k-NN) to find the <img src="https://latex.codecogs.com/png.latex?k"> nearest neighbor streamlines for local context (and random sampling for global context). Our ablation <em>GlobalTractCloud</em> skips the local context and is therefore faster than TractCloud.</li>
</ol>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://vavobo.de/posts/rapidparc_resources/quantitative_results.webp" class="img-fluid figure-img" style="width:80.0%"></p>
<figcaption>Quantitative Results on the TractCloud dataset test split with 20 random augmentations (STA). The RapidParc family is at least two orders of magnitude faster than TractCloud while being more accurate.</figcaption>
</figure>
</div>
<ol start="2" type="1">
<li>RapidParc is much more robust to altered brains. As described in the post about the <a href="../posts/monte_carlo_set_segmentation.html">underlying ML method</a>, this Monte Carlo-based method is inherently much more robust to missing regions. We further reinforced this behavior through <em>streamline dropout augmentations</em>.</li>
</ol>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://vavobo.de/posts/rapidparc_resources/qualitative_hemi.webp" class="img-fluid figure-img" style="width:80.0%"></p>
<figcaption>Qualitative Results on four subjects after hemispherotomy. Shown are the corticospinal tract (CST; rows 1-2) and the arcuate fasciculus (AF; rows 3-4). The ORG-Atlas (with manually guided registration) serves as a reference in this context.</figcaption>
</figure>
</div>


</section>


<div id="quarto-appendix" class="default"><section id="footnotes" class="footnotes footnotes-end-of-document"><h2 class="anchored quarto-appendix-heading">Footnotes</h2>

<ol>
<li id="fn1"><p>These authors contributed equally to this work and may, by mutual agreement, alternate the order of their names in citations and personal references.↩︎</p></li>
<li id="fn2"><p>Fan Zhang et al.&nbsp;Deep white matter analysis (DeepWMA): Fast and consistent tractography segmentation, Medical Image Analysis (2020) <a href="https://doi.org/10.1016/j.media.2020.101761">10.1016/j.media.2020.101761</a>↩︎</p></li>
<li id="fn3"><p>Tengfei Xue et al.&nbsp;TractCloud: Registration-Free Tractography Parcellation with a Novel Local-Global Streamline Point Cloud Representation, MICCAI (2023) <a href="https://doi.org/10.1007/978-3-031-43993-3_40">10.1007/978-3-031-43993-3_40</a>↩︎</p></li>
</ol>
</section></div> ]]></description>
  <guid>https://vavobo.de/posts/rapid_parc.html</guid>
  <pubDate>Wed, 25 Nov 2026 23:00:00 GMT</pubDate>
</item>
<item>
  <title>Smooth, Invertible Flip-Invariant Vector Embeddings for Undirected 3D Paths</title>
  <dc:creator>Valentin von Bornhaupt</dc:creator>
  <link>https://vavobo.de/posts/flip_invariance.html</link>
  <description><![CDATA[ 





<section id="tldr" class="level3">
<h3 class="anchored" data-anchor-id="tldr">TL;DR</h3>
<p>Handling millions of simple undirected 3D paths in geometric deep learning comes with a tradeoff: either you are locked into specific architectures (like graph neural networks) or you handle each path as a vector, which allows usage of more general methods. But by storing undirected paths as vectors you have to handle flips (i.e., cases where you start at one or the other end). This post highlights some solutions for this challenge.</p>
</section>
<section id="motivation" class="level1">
<h1>Motivation</h1>
<p>Inside the <a href="../posts/rapid_parc.html">RapidParc project</a><sup>1</sup> I had the following issue: A streamline can be seen as an undirected 3D path: i.e., a chain of vertices with two ends. Each point on the chain is a 3D coordinate. We can assume every streamline to be resampled to 15 supporting points. We get a chain <img src="https://latex.codecogs.com/png.latex?v_%7B1%7D%20-%20v_%7B2%7D%20-%20%5Ccdots%20-%20v_%7B15%7D%20%5C;%20%5C;%20%5Ctext%7B%20where%20%7D%20v_i%20%5Cin%20%5Cmathbb%7BR%7D%5E3."> But the catch is: These chains have neither a fixed beginning nor an end. Selecting <img src="https://latex.codecogs.com/png.latex?v_1"> as a starting point is as valid as selecting <img src="https://latex.codecogs.com/png.latex?v_%7B15%7D">.</p>
<p>This results in a problem: we want to reduce each streamline into a single vector, i.e., <img src="https://latex.codecogs.com/png.latex?s_1%20:=%20(v_1,%20%5Cdots,%20v_%7B15%7D)%20%5Cin%20%5Cmathbb%7BR%7D%5E%7B15%20%5Ctimes%203%7D%20%5Ctext%7B%20or%20%7D%20%20s_2:=%20(v_%7B15%7D,%20%5Cdots,%20v_%7B1%7D)%20%5Cin%20%5Cmathbb%7BR%7D%5E%7B15%20%5Ctimes%203%7D."> But mathematically speaking <img src="https://latex.codecogs.com/png.latex?s_1"> does not equal <img src="https://latex.codecogs.com/png.latex?s_2">.</p>
<p>But is this something that happens only in theory or can we see this behavior in the data?</p>
<div id="fig-PCA-original" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-PCA-original-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/flip_inv_resources/1_PCA_original.webp" class="img-fluid figure-img" style="width:80.0%">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-PCA-original-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Principal Component Analysis of 3 x 1200 streamlines taken from one HCP-subject. The streamlines are part of three anatomical sub-regions of the left superior longitudinal fasciculus (SLF I, SLF II and SLF III). We see that every cluster is separated into two disconnected sub-clusters. As further investigation shows, this is due to the fact that this vanilla vector representation pays no attention to the flip.
</figcaption>
</figure>
</div>
<p>So yes, as Figure&nbsp;1 shows, this is a real problem. Another point of view: RapidParc processes bags of streamlines simultaneously. What if some of them are all stored in one direction during training and during inference they are flipped? Can this influence the predictions for a single streamline?</p>
<div class="callout callout-style-simple callout-note no-icon callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>What has been done in the literature before?
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<section id="brun-et-al.-clustering-fiber-traces-using-normalized-cuts1-2004" class="level3">
<h3 class="anchored" data-anchor-id="brun-et-al.-clustering-fiber-traces-using-normalized-cuts1-2004">Brun et al.&nbsp;Clustering Fiber Traces Using Normalized Cuts<sup>2</sup> (2004)</h3>
<p>Brun et al.&nbsp;reduced fiber paths to a 9D representation:</p>
<ul>
<li>3 values represent a path mean, i.e., one mean value per dimension: <img src="https://latex.codecogs.com/png.latex?(%5Ctext%7Bmean%7D_x,%20%5C,%20%5Ctext%7Bmean%7D_y,%20%5C,%20%5Ctext%7Bmean%7D_z)"></li>
<li>6 values from the (symmetric) 3x3 covariance matrix <img src="https://latex.codecogs.com/png.latex?(%5Ctext%7Bcov%7D_%7Bxx%7D,%20%5C,%20%5Ctext%7Bcov%7D_%7Bxy%7D,%20%5C,%20%5Ctext%7Bcov%7D_%7Bxz%7D,%20%5C,%20%5Ctext%7Bcov%7D_%7Byy%7D,%20%5C,%20%5Ctext%7Bcov%7D_%7Byz%7D,%20%5C,%20%5Ctext%7Bcov%7D_%7Bzz%7D)"></li>
</ul>
<p>This representation is fully flip invariant (as the mean and the covariance matrix are independent of the order of elements). But it also loses a lot of information on its way.</p>
</section>
<section id="fan-zhang-et-al.-deepwma2-2020" class="level3">
<h3 class="anchored" data-anchor-id="fan-zhang-et-al.-deepwma2-2020">Fan Zhang et al.&nbsp;DeepWMA<sup>3</sup> (2020)</h3>
<p>DeepWMA also stores each streamline as a sequence of 15 3D supporting points. But to handle flip-invariance, they translated each 15x3 vector into a [15x2, 15x2, 3] tensor (called FiberMap) using a zig-zag pattern on each dimension. This embedding into higher dimensional space can be processed by convolutional neural networks (CNNs). This technique handles flip invariance by using shift invariance of convolutions. For analytical flip invariance it is important that <code>circular</code> padding<sup>4</sup> and a position-independent pooling layer (like <code>GlobalMaxPooling2D</code>) are used. Note that the data expansion is quite extensive: handling a single path with <img src="https://latex.codecogs.com/png.latex?15%20%5Ctimes%203%20=%2045"> entries results in a picture with <img src="https://latex.codecogs.com/png.latex?30%20%5Ctimes%2030%20%5Ctimes%203%20=%202700"> entries.</p>
<div id="fig-deepwma" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-deepwma-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/flip_inv_resources/deepwma.webp" class="img-fluid figure-img" style="width:80.0%">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-deepwma-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Illustration for the zig-zag pattern used within DeepWMA. One single 15x3 path gets copied and flipped multiple times to create an image tensor. This image is taken from DeepWMA’s publication.
</figcaption>
</figure>
</div>
</section>
<section id="tengfei-xue-et-al.-tractcloud3-2023" class="level3">
<h3 class="anchored" data-anchor-id="tengfei-xue-et-al.-tractcloud3-2023">Tengfei Xue et al.&nbsp;TractCloud<sup>5</sup> (2023)</h3>
<p>TractCloud does not use a flip-invariant data representation. It utilizes a PointNet/DGCNN-style local-global point cloud architecture. Therefore, instead of handling paths <img src="https://latex.codecogs.com/png.latex?v_1%20-%20%5Cdots%20-%20v_%7B15%7D">, it processes the point cloud <img src="https://latex.codecogs.com/png.latex?%5Cleft%5C%7Bv_%7Bi%7D%20%5C,%20%5Cvert%20%5C,%20i%20%5Cin%20%5C%7B1,%20%5Cdots,%2015%5C%7D%5Cright%5C%7D">, which is permutation invariant and therefore flip invariant.</p>
<p>For direct comparison with the RapidParc model, please look inside the <a href="https://doi.org/10.1162/IMAG.a.1168">RapidParc paper</a>.</p>
</section>
</div>
</div>
</div>
</section>
<section id="initial-flip-invariant-embedding" class="level1">
<h1>Initial Flip-Invariant Embedding</h1>
<p>It would be great to have a function <img src="https://latex.codecogs.com/png.latex?f"> such that <img src="https://latex.codecogs.com/png.latex?f(v)%20=%20f(%5Ctext%7Bflip%7D(v))"> where flip is the function that reorders the elements (<img src="https://latex.codecogs.com/png.latex?1,%20%5Cdots,%2015"> to <img src="https://latex.codecogs.com/png.latex?15,%20%5Cdots,%201">).</p>
<p>But not every function <img src="https://latex.codecogs.com/png.latex?f"> with this attribute is a great choice. (<img src="https://latex.codecogs.com/png.latex?f(x)%20=%200"> does the job, but also discards all information). So <img src="https://latex.codecogs.com/png.latex?f"> has to be invertible up to the decision whether <img src="https://latex.codecogs.com/png.latex?v_1"> or <img src="https://latex.codecogs.com/png.latex?v_%7B15%7D"> is the first element.</p>
<p>My solution for this problem combines two main ideas:</p>
<ol type="1">
<li>If <img src="https://latex.codecogs.com/png.latex?f(v)%20=%20f(%5Ctext%7Bflip%7D(v))">, the first and the last element of the chain have some kind of correspondence, the 2nd with the 14th and so on. Think about a horseshoe.</li>
<li>The <strong>midpoint formula</strong>: <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7Bx%20+%20y%20%20%5Cpm%20%5Cvert%20x%20-%20y%20%5Cvert%7D%7B2%7D%20=%20%5C%7Bx,%20y%5C%7D%20%5C;%20%5C;%20%5Ctext%7B%20for%20any%20%7D%20x,%20y%20%5Cin%20%5Cmathbb%7BR%7D"> While the left-hand side of the equation is (kind of) ordered (<img src="https://latex.codecogs.com/png.latex?x">: 1st, <img src="https://latex.codecogs.com/png.latex?y">: 2nd), the right-hand side is not (as sets are unordered). In practice, we store the midpoints <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7Bx+y%7D%7B2%7D"> and the signed half-differences <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7B%7Cx-y%7C_%5Ctext%7Bentangle%7D%7D%7B2%7D"> (defined in Note&nbsp;1 below) instead of the sets <img src="https://latex.codecogs.com/png.latex?%5C%7Bx,%20y%5C%7D">.</li>
</ol>
<p>Combining both ideas, we can define <img src="https://latex.codecogs.com/png.latex?%5Calpha(v)%20:=%20%5Cbegin%7Bbmatrix%7D%5C%7Bv_1,%20v_%7B15%7D%5C%7D%20&amp;%20%5C%7Bv_2,%20v_%7B14%7D%5C%7D&amp;%20%5Ccdots%20&amp;%20%5C%7Bv_7,%20v_%7B9%7D%5C%7D%20&amp;%20%5C%7Bv_8%5C%7D%20%5Cend%7Bbmatrix%7D."> Note that this representation is flip-invariant as sets do not have an order.</p>
<p>But these sets have a problem. They contain too little information to reconstruct the whole path: If you select for example <img src="https://latex.codecogs.com/png.latex?v_%7B15%7D"> as the first element for reconstruction, <img src="https://latex.codecogs.com/png.latex?v_%7B14%7D"> should be the next choice. But the selection of <img src="https://latex.codecogs.com/png.latex?v_%7B15%7D%20%5Cin%20%5C%7Bv_1,%20v_%7B15%7D%5C%7D"> and <img src="https://latex.codecogs.com/png.latex?v_%7B14%7D%20%5Cin%20%5C%7Bv_2,%20v_%7B14%7D%5C%7D"> happens independently of each other. That said, <img src="https://latex.codecogs.com/png.latex?v_%7B15%7D%20-%20v_%7B2%7D%20-%20%5Ccdots%20-%20v_%7B14%7D%20-%20v_%7B1%7D"> could be a possible reconstruction from the embedding <img src="https://latex.codecogs.com/png.latex?%5Calpha">. Therefore, we have to connect them to a chain again, adding the term:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cdelta(v)%20:=%20%5Cbegin%7Bbmatrix%7D%5C%7Bv_2-v_1,%20v_%7B14%7D%20-%20v_%7B15%7D%5C%7D%20&amp;%20%5C%7Bv_3%20-%20v_2%20,%20v_%7B13%7D%20-%20v_%7B14%7D%5C%7D&amp;%20%5Ccdots%20&amp;%20%5C%7Bv_7%20-%20v_6,%20v_9%20-%20v_%7B10%7D%5C%7D%5Cend%7Bbmatrix%7D."> The final embedding is then defined as: <img src="https://latex.codecogs.com/png.latex?f(v)%20:=%20%5Cbegin%7Bbmatrix%7D%5Calpha(v)%20&amp;%20%5Cdelta(v)%5Cend%7Bbmatrix%7D"></p>
<p>We can also apply the flip-invariant embedding to the example from above:</p>
<div id="fig-PCA-flip-inv" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-PCA-flip-inv-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/flip_inv_resources/2_PCA_flip_inv_embedding.webp" class="img-fluid figure-img" style="width:80.0%">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-PCA-flip-inv-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Principal Component Analysis of 3 x 1200 streamlines taken from one HCP-subject - but now embedded using the flip-invariant embedding from above. The streamlines are part of three anatomical sub-regions of the left superior longitudinal fasciculus (SLF I, SLF II and SLF III). We see that every cluster is now continuous.
</figcaption>
</figure>
</div>
<div id="nte-extend-3d" class="callout callout-style-simple callout-note no-icon callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note&nbsp;1: How to extend the midpoint formula to 3D Vectors?
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>The midpoint formula from above <img src="https://latex.codecogs.com/png.latex?%5C%7Bx,%20y%5C%7D%20=%20%5Cfrac%7Bx+y%7D%7B2%7D%20%5Cpm%20%5Cfrac%7B%5Cvert%20x-y%20%5Cvert%7D%7B2%7D%20%5C;%20%5C;%20%5Ctext%7B%20for%20any%20%7D%20x,y%20%5Cin%20%5Cmathbb%7BR%7D"> contains a norm. For 1D values, this is the absolute value norm. But if <img src="https://latex.codecogs.com/png.latex?x,y%20%5Cin%20%5Cmathbb%7BR%7D%5Ed"> are vectors this breaks: If we tried to extend the absolute norm to multiple dimensions by applying it on every component separately, we would lose the relationship of the signs within vectors. E.g., the <img src="https://latex.codecogs.com/png.latex?d=2"> vector <img src="https://latex.codecogs.com/png.latex?(1,%20-2)%5ET"> would become <img src="https://latex.codecogs.com/png.latex?(1,%202)%5ET">, resulting in <img src="https://latex.codecogs.com/png.latex?2%5E2%20=%204"> possibilities to reconstruct it <img src="https://latex.codecogs.com/png.latex?(%5Cpm%201,%20%5Cpm%202)%5ET">. And for <img src="https://latex.codecogs.com/png.latex?d=3"> we would even have <img src="https://latex.codecogs.com/png.latex?2%5E3%20=%208"> possibilities. But we want exactly 2 possibilities. Therefore, we replace the absolute value norm from above by the following <em>vector absolute value</em>: <img src="https://latex.codecogs.com/png.latex?%5Cleft%20%5Cvert%20%5Cvec%7Bv%7D%20%5Cright%20%5Cvert_%5Ctext%7Bentangle%7D%20:=%20%5Ctext%7Bsign%7D(v_1)%20%5Ccdot%20%5Cvec%7Bv%7D%20%5C;%20%5C;%20%5Ctext%7B%20for%20%7D%20%5Cvec%7Bv%7D=(v_1,%20%5Cdots,%20v_d)%5ET%20%5Cin%20%5Cmathbb%7BR%7D%5Ed."></p>
<p>Note that for <img src="https://latex.codecogs.com/png.latex?v%20%5Cin%20%5Cmathbb%7BR%7D"> we have <img src="https://latex.codecogs.com/png.latex?%5Cleft%20%5Cvert%20v%20%5Cright%20%5Cvert_%5Ctext%7Bentangle%7D%20=%20%5Cleft%20%5Cvert%20v%20%5Cright%20%5Cvert_%5Ctext%7Babs%7D."></p>
<p>As a result, the midpoint formula generalizes to: <img src="https://latex.codecogs.com/png.latex?%5C%7Bx,%20y%5C%7D%20=%20%5Cfrac%7Bx+y%7D%7B2%7D%20%5Cpm%20%5Cfrac%7B%5Cleft%5Cvert%20x-y%20%5Cright%5Cvert_%5Ctext%7Bentangle%7D%7D%7B2%7D%20%5C;%20%5C;%20%5Ctext%7B%20for%20any%20%7D%20x,y%20%5Cin%20%5Cmathbb%7BR%7D%5Ed"></p>
<p>Further generalization uses the first non-zero entry of each component for sign calculations. Please read the code below for more information.</p>
</div>
</div>
</div>
<div class="callout callout-style-simple callout-note no-icon callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-3-contents" aria-controls="callout-3" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>The Reconstruction Algorithm: Inverse of the Embedding
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-3" class="callout-3-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>Note that I designed <img src="https://latex.codecogs.com/png.latex?f"> as an embedding function. It was never designed to have a nice decoding function. But reconstruction is interesting from a mathematical perspective: to understand how the embedding contains all path information.</p>
<p>The input to the following algorithm is <img src="https://latex.codecogs.com/png.latex?f(v)%20:=%20%5Cbegin%7Bbmatrix%7D%5Calpha(v)%20&amp;%20%5Cdelta(v)%5Cend%7Bbmatrix%7D">. The goal is to reconstruct the path in any orientation.</p>
<ul>
<li><p>Select one element as a starting element and the other one as the last. <img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Balign*%7Dx%5E%7B(1)%7D%20&amp;%5Cin%20%5C%7Bv_1,%20v_%7B15%7D%5C%7D%20=%20%5Calpha(v)_1%20%5C%5C%0Ax%5E%7B(15)%7D%20&amp;:=%20%5C%7Bv_1,%20v_%7B15%7D%5C%7D%20%5Csetminus%20x%5E%7B(1)%7D%20=%20%5Calpha(v)_1%20%20%5Csetminus%20x%5E%7B(1)%7D%20%5Cend%7Balign*%7D"></p></li>
<li><p>For <img src="https://latex.codecogs.com/png.latex?i"> in <img src="https://latex.codecogs.com/png.latex?1,%20%5Cdots,%206"> do: <img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Balign*%7Dx%5E%7B(i+1)%7D%20:=&amp;%20%5Cunderset%7By%20%5C,%20%5Cin%20%5C,%20%5Calpha(v)_%7Bi+1%7D%7D%7B%5Ctext%7Bargmin%7D%7D%0A%5Cleft%5C%7B%20%5C%7C%20x%5E%7B(i)%7D%20+%20d%20%20-%20y%20%5C%7C%20%5C;%20:%20%5C;%20d%20%5Cin%20%5Cdelta(v)_i%20%5Cright%5C%7D%5C%5C%0A%20%20=&amp;%20%5Cunderset%7By%20%5C,%20%5Cin%20%5C,%20%5C%7Bv_%7Bi+1%7D,%20v_%7B15-i%7D%5C%7D%7D%7B%5Ctext%7Bargmin%7D%7D%0A%5Cleft%5C%7B%20%5C%7C%20x%5E%7B(i)%7D%20+%20d%20%20-%20y%20%5C%7C%20%5C;%20:%20%5C;%20d%20%5Cin%20%5C%7Bv_%7Bi+1%7D%20-%20v_i,%20v_%7B15-i%7D%20-%20v_%7B16%20-%20i%7D%5C%7D%5Cright%5C%7D%5C%5C%0Ax%5E%7B(15-i)%7D%20:=&amp;%20%5Calpha(v)_%7Bi+1%7D%20%5Csetminus%20x%5E%7B(i+1)%7D%0A%5Cend%7Balign*%7D"></p></li>
<li><p>Insert <img src="https://latex.codecogs.com/png.latex?x%5E%7B(8)%7D"> from <img src="https://latex.codecogs.com/png.latex?%5Calpha(v)_8"> in the chain to obtain <img src="https://latex.codecogs.com/png.latex?x%5E%7B(1)%7D%20-%20%5Cdots%20-%20x%5E%7B(7)%7D%20-%20x%5E%7B(8)%7D%20-%20x%5E%7B(9)%7D%20%5Cdots%20-%20x%5E%7B(15)%7D"></p></li>
</ul>
<section id="correctness-uniqueness" class="level3">
<h3 class="anchored" data-anchor-id="correctness-uniqueness">Correctness &amp; Uniqueness</h3>
<p>The reconstruction is unique (up to the choice of <img src="https://latex.codecogs.com/png.latex?x%5E%7B(1)%7D%20%5Cin%20%5C%7Bv_1,%20v_%7Bn%7D%5C%7D">) as long as <img src="https://latex.codecogs.com/png.latex?v_i%20%5Cneq%20v_%7Bn%20+%201%20-%20i%7D"> and <img src="https://latex.codecogs.com/png.latex?v_i%20-%20v_%7Bn%20+%201%20-%20i%7D%20%5Cneq%20v_%7Bi%20+%201%7D%20-%20v_%7Bn%20-%20i%7D"> for <img src="https://latex.codecogs.com/png.latex?i%20%5Cin%20%5C%7B1,%20%5Cdots,%207%5C%7D."></p>
<p>On random float paths these conditions will never be violated; on streamline datasets (3D float) this is nearly impossible. If you apply this technique to data where the condition might not hold: You can extend the <img src="https://latex.codecogs.com/png.latex?%5Cdelta">-function to consider skip-neighbors as well.</p>
<section id="proof" class="level4">
<h4 class="anchored" data-anchor-id="proof">Proof</h4>
<p>Proof by induction.</p>
<ul>
<li>Path length = 1: <img src="https://latex.codecogs.com/png.latex?%5Calpha(v)%20=%20%5B%5C%7Ba_1%5C%7D%5D"> contains the only element.</li>
<li>Path length = 3: <img src="https://latex.codecogs.com/png.latex?%5Calpha(v)"> is of the form <img src="https://latex.codecogs.com/png.latex?%5B%5C%7Ba_1,%20a_2%5C%7D%20%5C%7Ba_3%5C%7D%5D">. Select <img src="https://latex.codecogs.com/png.latex?a_1-a_3-a_2"> or <img src="https://latex.codecogs.com/png.latex?a_2-a_3-a_1">.</li>
<li>Path length &gt; 3: <img src="https://latex.codecogs.com/png.latex?%5Calpha(v)"> is of the form <img src="https://latex.codecogs.com/png.latex?%5B%5C%7Ba_1,%20a_2%5C%7D%20%5C%7Ba_3,%20a_4%5C%7D%20%5Cdots%5D">. Without loss of generality we select <img src="https://latex.codecogs.com/png.latex?x%5E%7B(1)%7D:=a_1"> and <img src="https://latex.codecogs.com/png.latex?x%5E%7B(n)%7D:=a_2">. Further assume without loss of generality <img src="https://latex.codecogs.com/png.latex?%5C%7B(a_3%20-%20a_1),%20(a_4%20-%20a_2)%5C%7D%20=%20%5Cdelta(v)_1">. For <img src="https://latex.codecogs.com/png.latex?x%5E%7B(1)%7D=a_1"> we have</li>
</ul>
<p><img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Balign*%7D0&amp;%20%5Coverset%7B%5Cphantom%7B%5Ctext%7B1st%20condition%7D%7D%7D%7B=%7D%20&amp;%20%5C%7C%20a_1%20+%20(a_3%20-%20a_1)%20-%20a_3%20%5C%7C%20%5C%5C%0A0%20&amp;%5Coverset%7B%5Ctext%7B1st%20condition%7D%7D%7B%3C%7D%20&amp;%20%5C%7C%20a_1%20+%20(a_3%20-%20a_1)%20-%20a_4%20%5C%7C%5C%5C%0A0%20&amp;%5Coverset%7B%5Ctext%7B1st%20condition%7D%7D%7B%3C%7D%20&amp;%20%5C%7C%20a_1%20+%20(a_4%20-%20a_2)%20-%20a_4%20%5C%7C%5C%5C%0A0%20&amp;%5Coverset%7B%5Ctext%7B2nd%20condition%7D%7D%7B%3C%7D%20&amp;%20%5C%7C%20a_1%20+%20(a_4%20-%20a_2)%20-%20a_3%20%5C%7C%20%5Cend%7Balign*%7D"></p>
<p>Therefore, we can clearly identify <img src="https://latex.codecogs.com/png.latex?a_3"> as a successor of <img src="https://latex.codecogs.com/png.latex?x%5E%7B(1)%7D=a_1"> (the side of the inequality that is zero assumes the argmin). The same is true for <img src="https://latex.codecogs.com/png.latex?x%5E%7B(n)%7D=a_2">. Following the induction argument, the inner sequence is uniquely solved.</p>
<p>If this condition does not hold, for example because <img src="https://latex.codecogs.com/png.latex?v_2%20=%20v_%7B14%7D">, we have <img src="https://latex.codecogs.com/png.latex?v_3%20-%20v_2%20=%20v_3%20-%20v_%7B14%7D">, which implies that the reconstruction algorithm could end up with the following chains: <img src="https://latex.codecogs.com/png.latex?v_1%20-%20v_2%20-%20v_3%20-%20%5Cdots%20-%20v_%7B13%7D%20-%20v_%7B14%7D%20-%20v_%7B15%7D"> and <img src="https://latex.codecogs.com/png.latex?v_1%20-%20v_2%20-%20v_%7B13%7D%20-%20%5Cdots%20-%20v_3%20-%20v_%7B14%7D%20-%20v_%7B15%7D"></p>
</section>
</section>
<section id="sec-example-flip-inv-embedding" class="level3">
<h3 class="anchored" data-anchor-id="sec-example-flip-inv-embedding">Reconstructing the Embedding by Hand (Example)</h3>
<p>Take a look at a simple 1D chain with 7 elements: <img src="https://latex.codecogs.com/png.latex?v%20=%20%5Cleft%5B1,%204,%202,%20(-1),%201,%200,%204%20%5Cright%5D"></p>
<p><strong>Embedding:</strong></p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Calpha(v)%20=%20%5Cbegin%7Bbmatrix%7D%20%5C%7B%201,%204%20%5C%7D%20&amp;%20%5C%7B%200,%204%20%5C%7D%20&amp;%20%5C%7B%201,%202%20%5C%7D%20&amp;%20%5C%7B%20-1%20%5C%7D%20%5Cend%7Bbmatrix%7D"></li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cdelta%5C,(v)%20=%20%5Cbegin%7Bbmatrix%7D%20%5C%7B%20-4,%203%20%5C%7D%20&amp;%20%5C%7B-2,%201%5C%7D%20%5Cend%7Bbmatrix%7D"></li>
</ul>
<p><strong>Reconstruction</strong></p>
<ul>
<li>Let’s select <img src="https://latex.codecogs.com/png.latex?x%5E%7B(1)%7D%20:=%204,%20x%5E%7B(7)%7D%20:=%201"> from <img src="https://latex.codecogs.com/png.latex?%5Calpha(v)_1">.</li>
<li>Iteration <img src="https://latex.codecogs.com/png.latex?i=1">:
<ul>
<li>Calculate <img src="https://latex.codecogs.com/png.latex?4+3%20=%207"> and <img src="https://latex.codecogs.com/png.latex?4%20+%20(-4)%20=%200">.</li>
<li>Since <img src="https://latex.codecogs.com/png.latex?0%20%5Cin%20%5Calpha(v)_2%20=%20%5C%7B%200,%204%20%5C%7D"> and <img src="https://latex.codecogs.com/png.latex?7%5Cnotin%20%5C%7B%200,%204%20%5C%7D">, we select <img src="https://latex.codecogs.com/png.latex?x%5E%7B(2)%7D:=%200"> and <img src="https://latex.codecogs.com/png.latex?x%5E%7B(6)%7D:=%204">.</li>
<li>We can continue the chain to <img src="https://latex.codecogs.com/png.latex?4%20-%200%20-%20*%20-%20*%20-%20*%20-%204%20-%201"></li>
</ul></li>
<li>Iteration <img src="https://latex.codecogs.com/png.latex?i=2">:
<ul>
<li>Calculate <img src="https://latex.codecogs.com/png.latex?0%20+%20(-2)%20=%20-2"> and <img src="https://latex.codecogs.com/png.latex?0%20+%201%20=%201">.</li>
<li>Since <img src="https://latex.codecogs.com/png.latex?1%20%5Cin%20%5Calpha(v)_3%20=%20%20%5C%7B%201,%202%20%5C%7D">, we select <img src="https://latex.codecogs.com/png.latex?x%5E%7B(3)%7D:=%201"> and <img src="https://latex.codecogs.com/png.latex?x%5E%7B(5)%7D:=%202">.</li>
<li>We can continue the chain to <img src="https://latex.codecogs.com/png.latex?4%20-%200%20-%201%20-%20*%20-%202%20-%204%20-%201"></li>
</ul></li>
<li>The missing element <img src="https://latex.codecogs.com/png.latex?%5Calpha(v)_4%20=%20%5C%7B-1%5C%7D"> completes the sequence to <img src="https://latex.codecogs.com/png.latex?4%20-%200%20-%201%20-%20(-1)%20-%202%20-%204%20-%201"></li>
</ul>
<p><strong>Alternative Reconstruction: Choose Other End as Initial Value</strong></p>
<ul>
<li>Let’s select <img src="https://latex.codecogs.com/png.latex?x%5E%7B(1)%7D%20:=%201,%20x%5E%7B(7)%7D%20:=%204"> from <img src="https://latex.codecogs.com/png.latex?%5Calpha(v)_1">.</li>
<li>Iteration <img src="https://latex.codecogs.com/png.latex?i=1">:
<ul>
<li>Calculate <img src="https://latex.codecogs.com/png.latex?1+3%20=%204"> and <img src="https://latex.codecogs.com/png.latex?1%20+%20(-4)%20=%20-3">.</li>
<li>Since <img src="https://latex.codecogs.com/png.latex?4%20%5Cin%20%5Calpha(v)_2%20=%20%5C%7B%200,%204%20%5C%7D"> and <img src="https://latex.codecogs.com/png.latex?-3%5Cnotin%20%5C%7B%200,%204%20%5C%7D">, we select <img src="https://latex.codecogs.com/png.latex?x%5E%7B(2)%7D:=%204"> and <img src="https://latex.codecogs.com/png.latex?x%5E%7B(6)%7D:=%200">.</li>
<li>We can continue the chain to <img src="https://latex.codecogs.com/png.latex?1%20-%204%20-%20*%20-%20*%20-%20*%20-%200%20-%204"></li>
</ul></li>
<li>Iteration <img src="https://latex.codecogs.com/png.latex?i=2">:
<ul>
<li>Calculate <img src="https://latex.codecogs.com/png.latex?4%20+%20(-2)%20=%202"> and <img src="https://latex.codecogs.com/png.latex?4%20+%201%20=%205">.</li>
<li>Since <img src="https://latex.codecogs.com/png.latex?2%20%5Cin%20%5Calpha(v)_3%20=%20%20%5C%7B%201,%202%20%5C%7D">, we select <img src="https://latex.codecogs.com/png.latex?x%5E%7B(3)%7D:=%202"> and <img src="https://latex.codecogs.com/png.latex?x%5E%7B(5)%7D:=%201">.</li>
<li>We can continue the chain to <img src="https://latex.codecogs.com/png.latex?1%20-%204%20-%202%20-%20*%20-%201%20-%200%20-%204"></li>
</ul></li>
<li>The missing element <img src="https://latex.codecogs.com/png.latex?%5Calpha(v)_4%20=%20%5C%7B-1%5C%7D"> completes the sequence to <img src="https://latex.codecogs.com/png.latex?1%20-%204%20-%202%20-%20(-1)%20-%201%20-%200%20-%204"></li>
</ul>
</section>
</div>
</div>
</div>
<div class="callout callout-style-simple callout-note no-icon callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-4-contents" aria-controls="callout-4" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Flip-Invariant embedding: Code
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-4" class="callout-4-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<div id="ffe0486b" class="cell" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> math</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Union, Tuple</span>
<span id="cb1-4"></span>
<span id="cb1-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> lex_sign(v: torch.Tensor) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> torch.Tensor:</span>
<span id="cb1-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># more generalized version of sign(v_0) </span></span>
<span id="cb1-7">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># due to the fact that v_0 might be zero</span></span>
<span id="cb1-8">    first_nonzero <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>).to(torch.uint8).argmax(dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, keepdim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb1-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> torch.sign(v.gather(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, first_nonzero))</span>
<span id="cb1-10"></span>
<span id="cb1-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> flip_invariant_embedding(</span>
<span id="cb1-12">      paths: torch.Tensor, </span>
<span id="cb1-13">      concatenate_results: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb1-14">      ) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> Union[torch.Tensor, </span>
<span id="cb1-15">           Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]]:</span>
<span id="cb1-16">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Assumes path_len to be odd</span></span>
<span id="cb1-17">    n, path_len, dimension <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> paths.size()</span>
<span id="cb1-18">    </span>
<span id="cb1-19">    flipped_paths <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.flip(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">input</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>paths, dims<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb1-20"></span>
<span id="cb1-21">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Shape [n, half, dimension]</span></span>
<span id="cb1-22">    half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> math.ceil(path_len <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># = 8</span></span>
<span id="cb1-23">    alpha_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (paths[:, :half] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> flipped_paths[:, :half])</span>
<span id="cb1-24"></span>
<span id="cb1-25">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Shape [n, half -1, dimension]</span></span>
<span id="cb1-26">    alpha_abs_diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (paths[:, :half<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> flipped_paths[:, :half<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb1-27">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate the abs for dim 0, for the rest: use relative signing</span></span>
<span id="cb1-28">    alpha_abs_diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> alpha_abs_diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> lex_sign(alpha_abs_diff)</span>
<span id="cb1-29"></span>
<span id="cb1-30">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Shape [n,  (path_len-3) / 2, dimension]</span></span>
<span id="cb1-31">    delta_half_len <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (path_len <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb1-32">    delta_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (</span>
<span id="cb1-33">        paths[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> : delta_half_len <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb1-34">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> paths[:, : delta_half_len]</span>
<span id="cb1-35">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> flipped_paths[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> : delta_half_len <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb1-36">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> flipped_paths[:, : delta_half_len]</span>
<span id="cb1-37">    )</span>
<span id="cb1-38"></span>
<span id="cb1-39">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Shape [n,  (path_len-3) / 2, dimension]</span></span>
<span id="cb1-40">    delta_abs_diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (</span>
<span id="cb1-41">        paths[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> : delta_half_len <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb1-42">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> paths[:, : delta_half_len]</span>
<span id="cb1-43">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (flipped_paths[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> : delta_half_len <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb1-44">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> flipped_paths[:, : delta_half_len])</span>
<span id="cb1-45">    )</span>
<span id="cb1-46">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate the abs for dim 0, for the rest: use relative signing</span></span>
<span id="cb1-47">    delta_abs_diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> delta_abs_diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> lex_sign(delta_abs_diff)</span>
<span id="cb1-48">    </span>
<span id="cb1-49">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> concatenate_results:</span>
<span id="cb1-50">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> torch.cat(</span>
<span id="cb1-51">            (alpha_sum, alpha_abs_diff, delta_sum, delta_abs_diff), dim <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb1-52">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>: </span>
<span id="cb1-53">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> alpha_sum, alpha_abs_diff, delta_sum, delta_abs_diff</span></code></pre></div></div>
</div>
<div id="546f4293" class="cell" data-execution_count="2">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">####### Example Tensor #######</span></span>
<span id="cb2-2">paths <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.randn(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb2-3"></span>
<span id="cb2-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"If we embed a tensor of shape </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>paths<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>shape<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">,</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">we get "</span></span>
<span id="cb2-5">      <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"a tensor of shape </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>flip_invariant_embedding(paths)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>shape<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">. </span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb2-6"></span>
<span id="cb2-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">####### Test if flip invariant #######</span></span>
<span id="cb2-8">is_flip_invariant <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb2-9">  torch.allclose(</span>
<span id="cb2-10">    flip_invariant_embedding(paths), </span>
<span id="cb2-11">    flip_invariant_embedding(torch.flip(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">input</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>paths, dims<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])), </span>
<span id="cb2-12">    atol<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>, rtol<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-5</span>)</span>
<span id="cb2-13"></span>
<span id="cb2-14"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> is_flip_invariant:</span>
<span id="cb2-15">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"On random data, the embedding is flip invariant."</span>)</span>
<span id="cb2-16"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb2-17">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The embedding is not flip invariant on random data."</span>)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>If we embed a tensor of shape torch.Size([100, 15, 3]),
we get a tensor of shape torch.Size([100, 27, 3]). 

On random data, the embedding is flip invariant.</code></pre>
</div>
</div>
<div id="90138081" class="cell" data-execution_count="3">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">simple_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.tensor([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>]).reshape(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb4-2">result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> flip_invariant_embedding(simple_path).flatten()</span>
<span id="cb4-3"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"The simple 1D "</span></span>
<span id="cb4-4">      <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>simple_path<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>flatten()<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> has the embedding </span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> </span>
<span id="cb4-5">      <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"[</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">', '</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>join([<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2g}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> res <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> result])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">] </span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb4-6">      </span>
<span id="cb4-7">simple_path_flipped <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.flip(simple_path, dims<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb4-8">result_flipped <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> flip_invariant_embedding(simple_path_flipped).flatten()</span>
<span id="cb4-9"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"The flipped "</span></span>
<span id="cb4-10">      <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>simple_path_flipped<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>flatten()<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> has the embedding </span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> </span>
<span id="cb4-11">      <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"[</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">', '</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>join([<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2g}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> res <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> result_flipped])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">]"</span>)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>The simple 1D tensor([ 1,  4,  2, -1,  1,  0,  4]) has the embedding 
[2.5, 2, 1.5, -1, 1.5, 2, 0.5, -0.5, -0.5, 3.5, 1.5] 

The flipped tensor([ 4,  0,  1, -1,  2,  4,  1]) has the embedding 
[2.5, 2, 1.5, -1, 1.5, 2, 0.5, -0.5, -0.5, 3.5, 1.5]</code></pre>
</div>
</div>
<p>To get the representation used in Section&nbsp;2.0.2, we do some basic computations:</p>
<div id="e6447cef" class="cell" data-execution_count="4">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1">alpha_sum, alpha_abs_diff, delta_sum, delta_abs_diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb6-2">  flip_invariant_embedding(simple_path, concatenate_results<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb6-3"></span>
<span id="cb6-4">alpha_sum, alpha_abs_diff, delta_sum, delta_abs_diff <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb6-5">  alpha_sum.flatten(), alpha_abs_diff.flatten(), delta_sum.flatten(), delta_abs_diff.flatten()</span>
<span id="cb6-6"></span>
<span id="cb6-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">####### Important part #######</span></span>
<span id="cb6-8">alpha_1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> alpha_sum[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> alpha_abs_diff</span>
<span id="cb6-9">alpha_2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> alpha_sum[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> alpha_abs_diff</span>
<span id="cb6-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># alpha_sum[-1] is a single value, will be added later</span></span>
<span id="cb6-11"></span>
<span id="cb6-12">delta_1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> delta_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> delta_abs_diff</span>
<span id="cb6-13">delta_2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> delta_sum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> delta_abs_diff</span>
<span id="cb6-14"></span>
<span id="cb6-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">####### Code for pretty print outs: #######</span></span>
<span id="cb6-16">alpha_print <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb6-17"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> a1, a2 <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(alpha_1, alpha_2):</span>
<span id="cb6-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> a1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> a2: alpha_print.append(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(a1)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(a2)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"}"</span>)</span>
<span id="cb6-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>: alpha_print.append(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(a2)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(a1)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"}"</span>)</span>
<span id="cb6-20">alpha_print.append(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(alpha_sum[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"}"</span>)</span>
<span id="cb6-21"></span>
<span id="cb6-22">delta_print <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb6-23"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> d1, d2 <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(delta_1, delta_2):</span>
<span id="cb6-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> d1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> d2: delta_print.append(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(d1)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(d2)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"}"</span>)</span>
<span id="cb6-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>: delta_print.append(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(d2)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(d1)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"}"</span>)</span>
<span id="cb6-26"></span>
<span id="cb6-27"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"alpha: [</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'  '</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>join(alpha_print)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">]"</span>)</span>
<span id="cb6-28"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"delta: [</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'  '</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>join(delta_print)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">]"</span>)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>alpha: [{1, 4}  {0, 4}  {1, 2}  {-1}]
delta: [{-4, 3}  {-2, 1}]</code></pre>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="improvement-a-smooth-flip-invariant-embedding" class="level1">
<h1>Improvement: A Smooth Flip-Invariant Embedding</h1>
<p>The code above works as shown, but there is one issue with the flip-invariant method itself: Assume we have <img src="https://latex.codecogs.com/png.latex?v_1%20-%20v_%7B15%7D%20=%20(-0.0001,%202)%5ET">. But if we apply some augmentations first, we get <img src="https://latex.codecogs.com/png.latex?v'_1%20-%20v_%7B15%7D'%20=%20(0.0001,%202)%5ET">. If we now apply <img src="https://latex.codecogs.com/png.latex?%5Clvert%20%5Ccdot%20%5Crvert_%5Ctext%7Bentangle%7D"> we get <img src="https://latex.codecogs.com/png.latex?(0.0001,%20-2)%5ET"> or <img src="https://latex.codecogs.com/png.latex?(0.0001,%202)%5ET"> depending on whether the minor augmentation had been applied or not. These points are very far away from each other and we see that <img src="https://latex.codecogs.com/png.latex?%5Clvert%20x%20%5Crvert_%5Ctext%7Bentangle%7D"> might behave just as discontinuously as <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsign%7D(x)">.</p>
<p>The solution: Get rid of absolute value calculations altogether.</p>
<section id="smooth-flip-invariant-embedding" class="level2">
<h2 class="anchored" data-anchor-id="smooth-flip-invariant-embedding">Smooth Flip-Invariant Embedding</h2>
<p>In this section, we define <img src="https://latex.codecogs.com/png.latex?%5Cbar%7Bv%7D:=%20%5Ctext%7Bflip%7D(v)"> to improve readability. As above, we use the good parts of the midpoint formula:</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsym%7D(v)%20:=%20%5Cfrac%7B1%7D%7B2%7D(v%20+%20%5Cbar%7Bv%7D)"> symmetric part, flip-invariant</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Basym%7D(v)%20:=%20%5Cfrac%7B1%7D%7B2%7D(v%20-%20%5Cbar%7Bv%7D)"> anti-symmetric part, not flip-invariant</li>
</ul>
<p>Note:</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?v%20=%20%5Ctext%7Bsym%7D(v)%20+%20%5Ctext%7Basym%7D(v)"></li>
<li><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bflip%7D(v)%20=%20%5Ctext%7Bsym%7D(v)%20-%20%5Ctext%7Basym%7D(v)"></li>
<li><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsym%7D(v)"> is a palindrome (i.e., we only keep the first “half” in memory)</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Basym%7D(v)%20=%20%5Cfrac%7B1%7D%7B2%7D(v%20-%20%5Cbar%7Bv%7D)%20=%20-%5Cfrac%7B1%7D%7B2%7D(%5Cbar%7Bv%7D%20-%20v)%20=%20-%5Ctext%7Basym%7D(%5Cbar%7Bv%7D)"> is point-symmetric (i.e., we only keep the first “half” in memory)</li>
</ul>
<p>While <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsym%7D(v)"> is already flip-invariant, <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Basym%7D(v)"> is not. Therefore, we flatten it <img src="https://latex.codecogs.com/png.latex?a%20:=%20%5Ctext%7Bflatten%7D(%5Ctext%7Basym%7D(v))"> and then apply a normalized version of the outer product <img src="https://latex.codecogs.com/png.latex?o(a)%20:=%20%5Cfrac%7Ba%20%5Ccdot%20a%5ET%7D%7B%5C%7C%20a%20%5C%7C_2%20+%20%5Cvarepsilon%7D."> The outer product acts here as a fine-grained sign absorber (like <img src="https://latex.codecogs.com/png.latex?x%5E2%20=%20(-x)%5E2">) which does not discard the sign-interactions between components.</p>
<p>The resulting smooth flip-invariant embedding is: <img src="https://latex.codecogs.com/png.latex?f_%5Ctext%7Bsmooth%7D(v)%20:=%20%5Cbegin%7Bbmatrix%7D%20%5Ctext%7Bsym%7D(v)%20&amp;%20o(a)%20%5Cend%7Bbmatrix%7D"></p>
<p>Note:</p>
<ul>
<li>The embedding is flip invariant: As <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Basym%7D(v)%20=%20-%5Ctext%7Basym%7D(%5Cbar%7Bv%7D)"> we have <img src="https://latex.codecogs.com/png.latex?a%20=%20-%5Cbar%7Ba%7D"> where we define <img src="https://latex.codecogs.com/png.latex?%5Cbar%7Ba%7D%20:=%20%5Ctext%7Bflatten%7D(%5Ctext%7Basym%7D(%5Cbar%7Bv%7D))">. Therefore, we have <img src="https://latex.codecogs.com/png.latex?%5Cbegin%7Balign*%7D%0Ao(a)%20=%20%5Cfrac%7Ba%20%5Ccdot%20a%5ET%7D%7B%5C%7C%20a%20%5C%7C_2%20+%20%5Cvarepsilon%7D%20=%20%5Cfrac%7B-%5Cbar%7Ba%7D%20%5Ccdot%20(-%5Cbar%7Ba%7D)%5ET%7D%7B%5C%7C%20-%5Cbar%7Ba%7D%20%5C%7C_2%20+%20%5Cvarepsilon%7D%20=%20%5Cfrac%7B%5Cbar%7Ba%7D%20%5Ccdot%20%5Cbar%7Ba%7D%5ET%7D%7B%5C%7C%20%5Cbar%7Ba%7D%20%5C%7C_2%20+%20%5Cvarepsilon%7D%20%20=%20o(%5Cbar%7Ba%7D)%20%5Cend%7Balign*%7D"></li>
<li>We only have to store the upper triangle of <img src="https://latex.codecogs.com/png.latex?o(a)"> since the outer product is symmetric.</li>
</ul>
<p>Applying the smooth flip-invariant embedding to the example above, we get:</p>
<div id="fig-PCA-smooth-flip-inv" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-PCA-smooth-flip-inv-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/flip_inv_resources/3_PCA_smooth_flip_inv_embedding.webp" class="img-fluid figure-img" style="width:80.0%">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-PCA-smooth-flip-inv-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: Principal Component Analysis of 3 x 1200 streamlines taken from one HCP-subject - but now embedded using the smooth flip-invariant embedding from above. The streamlines are part of three anatomical sub-regions of the left superior longitudinal fasciculus (SLF I, SLF II and SLF III).
</figcaption>
</figure>
</div>
<div id="7fa218bb" class="cell" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> smooth_flip_invariant_embedding(</span>
<span id="cb8-2">      paths: torch.Tensor, </span>
<span id="cb8-3">      eps: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-8</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> torch.Tensor:</span>
<span id="cb8-4"></span>
<span id="cb8-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Assumes path_len to be odd.  </span></span>
<span id="cb8-6">    N, path_len, dimension <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> paths.size()</span>
<span id="cb8-7"></span>
<span id="cb8-8">    half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (path_len <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 8</span></span>
<span id="cb8-9">    flipped <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.flip(paths, dims<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb8-10"></span>
<span id="cb8-11">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Symmetric part: [N, 24]</span></span>
<span id="cb8-12">    sym <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (paths[:, :half] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> flipped[:, :half]).flatten(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb8-13"></span>
<span id="cb8-14">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Antisymmetric part: [N, 21]</span></span>
<span id="cb8-15">    asym <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (paths[:, :half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> flipped[:, :half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]).flatten(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb8-16"></span>
<span id="cb8-17">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Normalized outer product (upper triangle): [N, 231]</span></span>
<span id="cb8-18">    normalized_outer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.einsum(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bi,bj-&gt;bij"</span>, asym, asym) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (</span>
<span id="cb8-19">      asym.norm(dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, keepdim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>).unsqueeze(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> eps)</span>
<span id="cb8-20">    tri_indices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.triu_indices(</span>
<span id="cb8-21">      asym.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], asym.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>paths.device)</span>
<span id="cb8-22">    upper_triangle <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> normalized_outer[:, tri_indices[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], tri_indices[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]</span>
<span id="cb8-23"></span>
<span id="cb8-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> torch.cat([sym, upper_triangle], dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [N, 255]</span></span></code></pre></div></div>
</div>
<div id="9f8fce1e" class="cell" data-execution_count="6">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">####### Example Tensor #######</span></span>
<span id="cb9-2">paths <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.randn(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb9-3"></span>
<span id="cb9-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"If we embed a tensor of shape </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>paths<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>shape<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">,</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">we get "</span></span>
<span id="cb9-5">      <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"a tensor of shape </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>smooth_flip_invariant_embedding(paths)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>shape<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">. </span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb9-6"></span>
<span id="cb9-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">####### Test if flip invariant #######</span></span>
<span id="cb9-8">is_flip_invariant <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb9-9">  torch.allclose(</span>
<span id="cb9-10">    smooth_flip_invariant_embedding(paths), </span>
<span id="cb9-11">    smooth_flip_invariant_embedding(torch.flip(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">input</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>paths, dims<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])), </span>
<span id="cb9-12">    atol<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>, rtol<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-5</span>)</span>
<span id="cb9-13"></span>
<span id="cb9-14"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> is_flip_invariant:</span>
<span id="cb9-15">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"On random data, the embedding is flip invariant."</span>)</span>
<span id="cb9-16"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb9-17">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The embedding is not flip invariant on random data."</span>)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>If we embed a tensor of shape torch.Size([100, 15, 3]),
we get a tensor of shape torch.Size([100, 255]). 

On random data, the embedding is flip invariant.</code></pre>
</div>
</div>
<div class="callout callout-style-simple callout-note no-icon callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-5-contents" aria-controls="callout-5" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Reconstructing the Smooth Flip-Invariant Embedding
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-5" class="callout-5-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>Assume we have been given <img src="https://latex.codecogs.com/png.latex?f_%5Ctext%7Bsmooth%7D(v)%20:=%20%5Cbegin%7Bbmatrix%7D%20%5Ctext%7Bsym%7D(v)%20&amp;%20o(a)%20%5Cend%7Bbmatrix%7D"> and we want to reconstruct <img src="https://latex.codecogs.com/png.latex?v">. Therefore, we have to get <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsym%7D"> and <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Basym%7D"> back. Since <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsym%7D"> is part of <img src="https://latex.codecogs.com/png.latex?f_%5Ctext%7Bsmooth%7D(v)">, we only need to extract <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Basym%7D"> from <img src="https://latex.codecogs.com/png.latex?M:=o(a)%20=%20%5Cfrac%7Ba%20%5Ccdot%20a%5ET%7D%7B%5C%7C%20a%20%5C%7C%20+%20%5Cvarepsilon%7D"></p>
<p>We can construct <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Basym%7D"> using the following formulas:</p>
<ul>
<li><p>For any column index <img src="https://latex.codecogs.com/png.latex?k"> we have <img src="https://latex.codecogs.com/png.latex?M_%7B:,%20k%7D%20=%20%5Cfrac%7B1%7D%7B%5C%7Ca%5C%7C_2%20+%20%5Cvarepsilon%7D%20%5Cbegin%7Bbmatrix%7D%20a_1%20%5C,%20a_k%20%5C%5C%20a_2%20%5C,%20a_k%20%5C%5C%20%5Cvdots%20%5C%5C%20a_%7B21%7D%20%5C,%20a_k%20%5Cend%7Bbmatrix%7D%20=%20%5Cunderbrace%7B%5Cleft(%5Cfrac%7Ba_k%7D%7B%5C%7Ca%5C%7C_2%20+%20%5Cvarepsilon%7D%5Cright)%7D_%7Bc_k%7D%20%5Cbegin%7Bbmatrix%7D%20a_1%20%5C%5C%20a_2%20%5C%5C%20%5Cvdots%20%5C%5C%20a_%7B21%7D%20%5Cend%7Bbmatrix%7D%20=%20c_k%20%5Ccdot%20a."></p></li>
<li><p>For best numerical conditioning we choose the column with the biggest diagonal entry<sup>6</sup>, i.e., <img src="https://latex.codecogs.com/png.latex?k%20:=%20%5Cunderset%7Bi%7D%7B%5Ctext%7Bargmax%7D%7D%20%5C;%20M_%7Bii%7D."></p></li>
<li><p>To get the vector <img src="https://latex.codecogs.com/png.latex?a">, we use <img src="https://latex.codecogs.com/png.latex?%5Cfrac%7BM_%7B:,%20k%7D%7D%7B%5C%7CM_%7B:,%20k%7D%5C%7C_2%7D%20=%20%5Cfrac%7Bc_k%20%5Ccdot%20a%7D%7B%5C%7Cc_k%20%5Ccdot%20a%20%5C%7C_2%7D%20=%20%5Cfrac%7Bc_k%7D%7B%7Cc_k%7C%7D%20%5Ccdot%20%5Cfrac%7Ba%7D%7B%5C%7Ca%5C%7C_2%7D%20=%20%5Ctext%7Bsign%7D(a_k)%20%5C,%20%5Cfrac%7Ba%7D%7B%5C%7Ca%5C%7C_2%7D"></p></li>
<li><p>We can easily see that <img src="https://latex.codecogs.com/png.latex?%5C%7Ca%5C%7C_2%20=%20%5Cfrac%7B%5Ctext%7Btrace%7D(M)%20+%20%5Csqrt%7B%5Ctext%7Btrace%7D(M)%5E2%20+%204%5Cvarepsilon%5C,%5Ctext%7Btrace%7D(M)%7D%7D%7B2%7D"> if we remember that <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Btrace%7D(M)%20=%20%5Csum%20M_%7Bii%7D%20=%20%5Cfrac%7B%5ClVert%20a%20%5CrVert_2%5E2%7D%7B%5ClVert%20a%20%5CrVert_2%20+%20%5Cvarepsilon%7D."></p></li>
<li><p>Finally, we obtain <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsign%7D(a_k)%20%5Ccdot%20a%20=%20%5C%7Ca%5C%7C_2%20%5Ccdot%20%5Cfrac%7BM_%7B:,%20k%7D%7D%7B%5C%7CM_%7B:,%20k%7D%5C%7C_2%7D."> Remember, flipping the sign of <img src="https://latex.codecogs.com/png.latex?a"> corresponds to flipping the sign of <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Basym%7D"> and therefore just flipping <img src="https://latex.codecogs.com/png.latex?v"> one more time.</p></li>
<li><p>From <img src="https://latex.codecogs.com/png.latex?a"> we get <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Basym%7D"> by reshaping and therefore, we get the reconstructions <img src="https://latex.codecogs.com/png.latex?v%20=%20%5Ctext%7Bsym%7D(v)%20+%20%5Ctext%7Basym%7D(v)"> and <img src="https://latex.codecogs.com/png.latex?%5Cbar%7Bv%7D%20%20=%20%5Ctext%7Bsym%7D(v)%20-%20%5Ctext%7Basym%7D(v)">.</p></li>
</ul>
<div id="3da483de" class="cell" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> reconstruct_from_smooth_embedding(</span>
<span id="cb11-2">    emb: torch.Tensor,</span>
<span id="cb11-3">    path_len: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>,</span>
<span id="cb11-4">    dim: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,</span>
<span id="cb11-5">    eps: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-8</span>,</span>
<span id="cb11-6">    flip_orientation: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>,</span>
<span id="cb11-7">) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> torch.Tensor:</span>
<span id="cb11-8">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb11-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    Reconstructs 3D paths of shape [N, path_len, dim] from the smooth flip-invariant embedding.</span></span>
<span id="cb11-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb11-11">    N <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> emb.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb11-12">    half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (path_len <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 8</span></span>
<span id="cb11-13">    sym_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dim <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 24</span></span>
<span id="cb11-14">    asym_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dim <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 21</span></span>
<span id="cb11-15"></span>
<span id="cb11-16">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1. Split sym and upper-triangle entries</span></span>
<span id="cb11-17">    sym <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> emb[:, :sym_size].view(N, half, dim)</span>
<span id="cb11-18">    upper_tri_vals <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> emb[:, sym_size:]</span>
<span id="cb11-19"></span>
<span id="cb11-20">    normalized_outer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.zeros(N, asym_size, asym_size, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>emb.device, dtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>emb.dtype)</span>
<span id="cb11-21">    idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.triu_indices(asym_size, asym_size, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>emb.device)</span>
<span id="cb11-22">    normalized_outer[:, idx[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], idx[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> upper_tri_vals</span>
<span id="cb11-23">    normalized_outer[:, idx[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], idx[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> upper_tri_vals  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># symmetric filling</span></span>
<span id="cb11-24"></span>
<span id="cb11-25">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 2. Recover ||a||_2 from trace(normalized_outer)</span></span>
<span id="cb11-26">    diag <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.diagonal(normalized_outer, dim1<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, dim2<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [N, 21]</span></span>
<span id="cb11-27">    trace <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> diag.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, keepdim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [N, 1]</span></span>
<span id="cb11-28">    a_norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (trace <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> torch.sqrt(trace<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">4.0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> eps <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> trace)) </span>
<span id="cb11-29"></span>
<span id="cb11-30">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 3. Pick the column with the largest diagonal entry and normalize column k</span></span>
<span id="cb11-31">    k <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> diag.argmax(dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [N]</span></span>
<span id="cb11-32">    col_k <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> normalized_outer[torch.arange(N, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>emb.device), :, k] <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [N, 21]</span></span>
<span id="cb11-33">    col_norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> col_k.norm(dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, keepdim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb11-34"></span>
<span id="cb11-35">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Do a safe division: if col_norm == 0, the path is symmetric so a_recon stays 0</span></span>
<span id="cb11-36">    a_recon <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.where(</span>
<span id="cb11-37">        col_norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb11-38">        a_norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> col_k <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> col_norm.clamp_min(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>),</span>
<span id="cb11-39">        torch.zeros_like(col_k),</span>
<span id="cb11-40">    )</span>
<span id="cb11-41">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> flip_orientation:</span>
<span id="cb11-42">        a_recon <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>a_recon</span>
<span id="cb11-43"></span>
<span id="cb11-44">    asym_half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> a_recon.view(N, half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, dim)</span>
<span id="cb11-45"></span>
<span id="cb11-46">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 4. Reassemble full path = sym ± asym (midpoint formula)</span></span>
<span id="cb11-47">    first_half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sym[:, :half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> asym_half</span>
<span id="cb11-48">    middle <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sym[:, half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> : half]</span>
<span id="cb11-49">    second_half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.flip(sym[:, :half <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> asym_half, dims<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb11-50"></span>
<span id="cb11-51">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> torch.cat([first_half, middle, second_half], dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span></code></pre></div></div>
</div>
<div id="d5b10388" class="cell" data-execution_count="8">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">####### Embed Paths, reconstruct them, calculate error #######</span></span>
<span id="cb12-2">paths <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.randn(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb12-3">emb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> smooth_flip_invariant_embedding(paths)</span>
<span id="cb12-4">rec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> reconstruct_from_smooth_embedding(emb)</span>
<span id="cb12-5"></span>
<span id="cb12-6">err_orig <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (rec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> paths).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>().amax(dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [100]</span></span>
<span id="cb12-7">err_flip <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (rec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> torch.flip(paths, dims<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">abs</span>().amax(dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [100]</span></span>
<span id="cb12-8">max_min_flip_error <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.minimum(err_orig, err_flip).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>().item()</span>
<span id="cb12-9"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Max reconstruction error across 100 paths: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>max_min_flip_error<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2e}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb12-10"></span>
<span id="cb12-11">err_orig <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (rec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> paths).norm(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [100]</span></span>
<span id="cb12-12">err_flip <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (rec <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> torch.flip(paths, dims<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])).norm(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [100]</span></span>
<span id="cb12-13">mean_min_flip_error <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.minimum(err_orig, err_flip).mean().item()</span>
<span id="cb12-14"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Mean l2 reconstruction error across 100 paths: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>mean_min_flip_error<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2e}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>Max reconstruction error across 100 paths: 4.77e-07
Mean l2 reconstruction error across 100 paths: 4.60e-07</code></pre>
</div>
</div>
</div>
</div>
</div>
</section>
</section>
<section id="alternative-learned-flip-invariance-through-data-augmentation" class="level1">
<h1>Alternative: Learned Flip Invariance through Data Augmentation</h1>
<p>Data augmentation is a well-established method for telling a model what invariances the data should have. For example: A picture of a cow is still a picture of a cow if you flip it horizontally. Therefore, it is common to apply some random data augmentations to image classification training pipelines (<a href="https://docs.pytorch.org/vision/0.13/auto_examples/plot_transforms.html#sphx-glr-auto-examples-plot-transforms-py">PyTorch transforms gallery</a> lists some examples).</p>
<p>So in terms of streamline paths, randomly flipping them (i.e., reversing the order of supporting points from last to first) during training can teach the model that both forms represent the same streamline path.</p>
</section>
<section id="comparison-of-the-approaches" class="level1">
<h1>Comparison of the Approaches</h1>
<table class="caption-top table">
<colgroup>
<col style="width: 20%">
<col style="width: 20%">
<col style="width: 20%">
<col style="width: 20%">
<col style="width: 20%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: left;">Method</th>
<th style="text-align: left;">Output Size (for <img src="https://latex.codecogs.com/png.latex?15%20%5Ctimes%203">)</th>
<th style="text-align: left;">Flip-Invariant?</th>
<th style="text-align: left;">Preserves all Information?</th>
<th style="text-align: left;">Smooth? (w.r.t. <img src="https://latex.codecogs.com/png.latex?v">)</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">No Embedding</td>
<td style="text-align: left;">45</td>
<td style="text-align: left;">No</td>
<td style="text-align: left;">Yes</td>
<td style="text-align: left;">Yes</td>
</tr>
<tr class="even">
<td style="text-align: left;">9D Embedding</td>
<td style="text-align: left;">9</td>
<td style="text-align: left;">Yes</td>
<td style="text-align: left;">No</td>
<td style="text-align: left;">Yes</td>
</tr>
<tr class="odd">
<td style="text-align: left;">DeepWMA (FiberMap)</td>
<td style="text-align: left;">2,700</td>
<td style="text-align: left;">Depends on implementation</td>
<td style="text-align: left;">Usable through / after CNN</td>
<td style="text-align: left;">CNN: at least <img src="https://latex.codecogs.com/png.latex?C%5E0"></td>
</tr>
<tr class="even">
<td style="text-align: left;">Initial Embedding</td>
<td style="text-align: left;">81</td>
<td style="text-align: left;">Yes</td>
<td style="text-align: left;">Yes</td>
<td style="text-align: left;">No</td>
</tr>
<tr class="odd">
<td style="text-align: left;">Smooth Embedding</td>
<td style="text-align: left;">255</td>
<td style="text-align: left;">Yes</td>
<td style="text-align: left;">Yes</td>
<td style="text-align: left;">Yes<sup>7</sup></td>
</tr>
<tr class="even">
<td style="text-align: left;">Flip Augmentation</td>
<td style="text-align: left;">45</td>
<td style="text-align: left;">Not guaranteed</td>
<td style="text-align: left;">Yes</td>
<td style="text-align: left;">Yes</td>
</tr>
</tbody>
</table>
<section id="comparison-of-the-flip-invariant-embeddings" class="level2">
<h2 class="anchored" data-anchor-id="comparison-of-the-flip-invariant-embeddings">Comparison of the Flip-Invariant Embeddings</h2>
<p>As we can see in Figure&nbsp;5, using clustering without an embedding leads to no clear cluster separation. Using the initial flip-invariant embedding leads to a more distinct result. The smooth flip-invariant embedding yields the best results.</p>
<div id="fig-kmeans" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-kmeans-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/flip_inv_resources/KMeans_comparison.webp" class="img-fluid figure-img" style="width:100.0%">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-kmeans-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;5: Comparison of the flip-invariant embeddings using <img src="https://latex.codecogs.com/png.latex?k">-means clustering with <img src="https://latex.codecogs.com/png.latex?k=3">. The streamlines are part of three anatomical sub-regions of the left superior longitudinal fasciculus (SLF I, SLF II and SLF III).
</figcaption>
</figure>
</div>
</section>
<section id="flip-invariant-embedding-vs.-flip-augmentations" class="level2">
<h2 class="anchored" data-anchor-id="flip-invariant-embedding-vs.-flip-augmentations">Flip-Invariant Embedding vs.&nbsp;Flip Augmentations</h2>
<ul>
<li>Both flip-invariant embeddings from above guarantee flip invariance of the model in any case. They can be implemented in fast PyTorch code (see above).</li>
<li>The flip-augmentation-based approach is faster during inference time (no embedding calculations at all) and actually also very flip-stable (see paper).</li>
<li>During an earlier stage of RapidParc, we compared the (non-smooth) flip-invariant embedding with the flip augmentation approach. Unfortunately, I did not correctly extend the approach to 3D data (see Note&nbsp;1). This might be why the flip-invariant model performed a bit worse compared to the flip-augmented model in <a href="https://arxiv.org/pdf/2503.07104v1">this paper draft</a>. But since the augmentation-based method performed very well (and even a bit faster), there was no fundamental argument to introduce the novel concept of a flip-invariant embedding in the resulting RapidParc paper.</li>
</ul>


</section>
</section>


<div id="quarto-appendix" class="default"><section id="footnotes" class="footnotes footnotes-end-of-document"><h2 class="anchored quarto-appendix-heading">Footnotes</h2>

<ol>
<li id="fn1"><p>Valentin von Bornhaupt, Justus Bisten et al.&nbsp;RapidParc: A Global-Context Transformer for Parallel, Accurate, and Lesion-Robust Tractogram Parcellation, Imaging Neuroscience (2026) <a href="https://doi.org/10.1162/IMAG.a.1168">10.1162/IMAG.a.1168</a>↩︎</p></li>
<li id="fn2"><p>Anders Brun et al.&nbsp;Clustering Fiber Traces Using Normalized Cuts, Medical Image Computing and Computer-Assisted Intervention (MICCAI) (2004) <a href="https://doi.org/10.1007/978-3-540-30135-6_45">10.1007/978-3-540-30135-6_45</a>↩︎</p></li>
<li id="fn3"><p>Fan Zhang et al.&nbsp;Deep white matter analysis (DeepWMA): Fast and consistent tractography segmentation, Medical Image Analysis (2020) <a href="https://doi.org/10.1016/j.media.2020.101761">10.1016/j.media.2020.101761</a>↩︎</p></li>
<li id="fn4"><p><a href="https://github.com/zhangfanmark/DeepWMA/blob/master/src/nn_model.py">DeepWMA’s Implementation</a> uses zero-padding with <code>MaxPooling2D</code>. Note that this breaks the exact flip invariance of the network. For exact analytical flip invariance, the architecture must avoid boundary effects (such as zero-padding) and strided pooling misalignment. Note that this does not mean that the network is not able to learn to handle these ambiguities during training.↩︎</p></li>
<li id="fn5"><p>Tengfei Xue et al.&nbsp;TractCloud: Registration-Free Tractography Parcellation with a Novel Local-Global Streamline Point Cloud Representation, MICCAI (2023) <a href="https://doi.org/10.1007/978-3-031-43993-3_40">10.1007/978-3-031-43993-3_40</a>↩︎</p></li>
<li id="fn6"><p>All entries in <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bdiag%7D(a%20a%5ET)"> are non-negative. If they are all zero, then <img src="https://latex.codecogs.com/png.latex?a%20=%20%5Cvec%7B0%7D">.↩︎</p></li>
<li id="fn7"><p>The normalized outer product <img src="https://latex.codecogs.com/png.latex?o(a)%20=%20%5Cfrac%7Ba%20%5Ccdot%20a%5ET%7D%7B%5C%7Ca%5C%7C_2%20+%20%5Cvarepsilon%7D"> is at least in <img src="https://latex.codecogs.com/png.latex?C%5E2"> (in fact, <img src="https://latex.codecogs.com/png.latex?C%5E%5Cinfty"> everywhere except zero). Select <img src="https://latex.codecogs.com/png.latex?o%5E*(a)%20=%20%5Cfrac%7Ba%20%5Ccdot%20a%5ET%7D%7B%5Csqrt%7B%5C%7Ca%5C%7C_2%5E2%20+%20%5Cvarepsilon%5E2%7D%7D"> if you are aiming for <img src="https://latex.codecogs.com/png.latex?C%5E%5Cinfty">.↩︎</p></li>
</ol>
</section><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">BibTeX citation:</div><pre class="sourceCode code-with-copy quarto-appendix-bibtex"><code class="sourceCode bibtex">@online{von_bornhaupt2026,
  author = {von Bornhaupt, Valentin},
  title = {Smooth, {Invertible} {Flip-Invariant} {Vector} {Embeddings}
    for {Undirected} {3D} {Paths}},
  date = {2026-11-25},
  url = {https://vavobo.de/posts/flip_invariance.html},
  langid = {en}
}
</code></pre><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-von_bornhaupt2026" class="csl-entry quarto-appendix-citeas">
Bornhaupt, Valentin von. 2026. <span>“Smooth, Invertible Flip-Invariant
Vector Embeddings for Undirected 3D Paths.”</span> November 25. <a href="https://vavobo.de/posts/flip_invariance.html">https://vavobo.de/posts/flip_invariance.html</a>.
</div></div></section></div> ]]></description>
  <guid>https://vavobo.de/posts/flip_invariance.html</guid>
  <pubDate>Tue, 24 Nov 2026 23:00:00 GMT</pubDate>
</item>
<item>
  <title>Just Shuffle: Linear-Time Set Segmentation with Transformer Encoders</title>
  <dc:creator>Valentin von Bornhaupt</dc:creator>
  <link>https://vavobo.de/posts/monte_carlo_set_segmentation.html</link>
  <description><![CDATA[ 





<section id="tldr" class="level3">
<h3 class="anchored" data-anchor-id="tldr">TL;DR</h3>
<p>Classifying massive point clouds usually forces a painful tradeoff: either evaluate points locally and sacrifice global context, or preserve global context and face prohibitive <img src="https://latex.codecogs.com/png.latex?O(n%5E2)"> complexity of full-set methods. I developed a method that allows using random context as an approximation of the set distribution.</p>
<ul>
<li><strong>Divide and conquer</strong>: Randomly split your unordered point cloud into small stochastic bags of size&nbsp;<img src="https://latex.codecogs.com/png.latex?c">&nbsp;(e.g.,&nbsp;<img src="https://latex.codecogs.com/png.latex?c%20=%20256">); no need for pre-sorting, spatial indexing, or clustering.</li>
<li><strong>Capture global context</strong>: Each bag acts as a Monte Carlo approximation of the underlying point distribution, providing the model with enough contextual clues to segment each bag simultaneously.</li>
<li><strong>Linear complexity</strong>: Runtime drops to&nbsp;<img src="https://latex.codecogs.com/png.latex?O(n%20%5Ccdot%20c)">&nbsp;and memory footprint to&nbsp;<img src="https://latex.codecogs.com/png.latex?O(c%5E2)"> for any fixed bag size&nbsp;<img src="https://latex.codecogs.com/png.latex?c"> and sample set size <img src="https://latex.codecogs.com/png.latex?n">.</li>
<li><strong>Empirically resilient</strong>: Stable across different bag sizes&nbsp;<img src="https://latex.codecogs.com/png.latex?c">&nbsp;and spatial gaps in evaluation sets.</li>
<li><strong>Peer-reviewed &amp; verified</strong>: Powers whole-brain streamline segmentation in&nbsp;<a href="https://github.com/MedVisBonn/RapidParc">RapidParc</a>&nbsp;(<a href="https://doi.org/10.1162/IMAG.a.1168">published in&nbsp;<em>Imaging Neuroscience</em></a>), outperforming existing baselines on speed and accuracy while staying robust across severe anatomical alterations.</li>
</ul>
</section>
<section id="introduction" class="level1">
<h1>Introduction</h1>
<p>During my master’s thesis, I needed a way to classify massive point clouds based on their global behavior without hitting the memory limits of traditional full-set methods. The solution is a linear-time, Transformer-based Monte Carlo approach that scales exceptionally well.</p>
<p>This blog post should help you understand the method and its attributes to add it to your own ML-toolbox.</p>
<section id="motivation-static-scene-mlp-is-sufficient" class="level2">
<h2 class="anchored" data-anchor-id="motivation-static-scene-mlp-is-sufficient">Motivation – Static Scene: MLP is Sufficient</h2>
<p>Take a look at the famous <em>two spirals</em> classification problem. You can see samples of two spirals which are twisted into each other – a blue and an orange one. This is a classic benchmark for ML-models: These two spirals are not separable by a single straight line (i.e.&nbsp;not “linearly separable”).</p>
<div id="cell-fig-easy-example-samples" class="cell" data-execution_count="1">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> torch.nn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> nn</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> math</span>
<span id="cb1-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Tuple, List, Union</span>
<span id="cb1-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> matplotlib.pyplot <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> plt</span>
<span id="cb1-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> matplotlib.colors <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> LinearSegmentedColormap</span>
<span id="cb1-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> matplotlib.lines <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Line2D</span>
<span id="cb1-8"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pathlib <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Path</span>
<span id="cb1-9"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time</span>
<span id="cb1-10"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> os</span>
<span id="cb1-11"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> sys</span>
<span id="cb1-12"></span>
<span id="cb1-13">sys.path.append(Path(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>).resolve().parent)</span>
<span id="cb1-14"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.benchmark <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> measure_duration</span>
<span id="cb1-15"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.helper <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> get_device, to_rad, to_deg</span>
<span id="cb1-16"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.visualizations <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> create_sample_plot</span>
<span id="cb1-17"></span>
<span id="cb1-18"></span>
<span id="cb1-19"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_spiral_samples(size: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, </span>
<span id="cb1-20">                noise: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>,</span>
<span id="cb1-21">                num_twists: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>, </span>
<span id="cb1-22">                shuffle: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, </span>
<span id="cb1-23">                phase_shift_rad: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>,</span>
<span id="cb1-24">                is_reversed: Union[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>,</span>
<span id="cb1-25">                device: Union[torch.device, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.device(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cpu"</span>)</span>
<span id="cb1-26">                ) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> Tuple[torch.Tensor, torch.Tensor]:</span>
<span id="cb1-27">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Spiral 0</span></span>
<span id="cb1-28">    half_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 50:50 both spirals</span></span>
<span id="cb1-29">    t0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.rand(half_size, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># randoms in [0, …, 1], shape [half_size]</span></span>
<span id="cb1-30">    radius <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>  t0 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># randoms in [0, …, 1], shape [half_size]</span></span>
<span id="cb1-31">    t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ((<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>is_reversed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> math.pi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> num_twists) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> phase_shift_rad <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Circle parametrization, shape [half_size]</span></span>
<span id="cb1-32">    spiral0X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.stack([</span>
<span id="cb1-33">        radius <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.cos(t) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> torch.randn(half_size, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.sqrt(radius) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> noise <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> num_twists,</span>
<span id="cb1-34">        radius <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.sin(t) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> torch.randn(half_size, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.sqrt(radius) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> noise <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> num_twists</span>
<span id="cb1-35">        ], dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [half_size, 2]</span></span>
<span id="cb1-36"></span>
<span id="cb1-37">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Spiral 1</span></span>
<span id="cb1-38">    half_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> half_size <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># = half_size if size is even else half_size+1 </span></span>
<span id="cb1-39">    t0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.rand(half_size, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># randoms in [0, …, 1], shape [half_size]</span></span>
<span id="cb1-40">    radius <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>  t0 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># randoms in [0, …, 1], shape [half_size]</span></span>
<span id="cb1-41">    t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ((<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>is_reversed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> math.pi <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> num_twists) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> t0 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (phase_shift_rad <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> math.pi) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Circle parametrization, shape [half_size]</span></span>
<span id="cb1-42">    spiral1X <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.stack([</span>
<span id="cb1-43">        radius <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.cos(t) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> torch.randn(half_size, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.sqrt(radius) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> noise <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> num_twists, </span>
<span id="cb1-44">        radius <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.sin(t) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> torch.randn(half_size, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.sqrt(radius) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> noise <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> num_twists</span>
<span id="cb1-45">        ], dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [half_size, 2]</span></span>
<span id="cb1-46"></span>
<span id="cb1-47">    spiral_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.vstack([spiral0X, spiral1X]) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [size, 2]</span></span>
<span id="cb1-48">    spiral_labels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.tensor([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(spiral0X) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(spiral1X), device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [size]</span></span>
<span id="cb1-49"></span>
<span id="cb1-50">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> shuffle:</span>
<span id="cb1-51">        perm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.randperm(size, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [size]</span></span>
<span id="cb1-52">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> spiral_samples[perm], spiral_labels[perm] <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [size, 2], [size]</span></span>
<span id="cb1-53">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb1-54">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> spiral_samples, spiral_labels <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [size, 2], [size]</span></span>
<span id="cb1-55"></span>
<span id="cb1-56">                           </span>
<span id="cb1-57"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">################ Code: ################</span></span>
<span id="cb1-58">save_dir <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Path(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"two_spirals"</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"weights_and_statistics"</span></span>
<span id="cb1-59"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> save_dir.is_dir():</span>
<span id="cb1-60">    save_dir.mkdir()</span>
<span id="cb1-61"></span>
<span id="cb1-62">NUM_TWISTS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.75</span></span>
<span id="cb1-63">SAMPLE_NOISE <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.15</span></span>
<span id="cb1-64">DEVICE <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_device()</span>
<span id="cb1-65">cmap_blue_orange <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> LinearSegmentedColormap.from_list(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blue_orange"</span>, [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tab:blue"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tab:orange"</span>])</span>
<span id="cb1-66">create_sample_plot(num_samples<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5000</span>, num_twists<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>NUM_TWISTS, phase_shift_rad<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, noise<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>SAMPLE_NOISE)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-easy-example-samples" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-easy-example-samples-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-easy-example-samples-output-1.webp" width="434" height="432" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-easy-example-samples-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Samples of a static Two-Spirals instance
</figcaption>
</figure>
</div>
</div>
</div>
<p>A more sophisticated model – like a simple Multi-Layer-Perceptron (MLP) – can easily learn this static <em>two-spirals</em> scene (Figure&nbsp;2). My MLP here has a <img src="https://latex.codecogs.com/png.latex?%5C,%202-32-32-2"> architecture (i.e.&nbsp;<img src="https://latex.codecogs.com/png.latex?1218"> parameters) with LeakyReLU activations.</p>
<div id="cell-fig-contour-plot" class="cell" data-execution_count="2">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> f1_score, accuracy_score</span>
<span id="cb2-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb2-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pickle</span>
<span id="cb2-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.visualizations <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> plot_decision_boundary_for_mlp</span>
<span id="cb2-5"></span>
<span id="cb2-6"></span>
<span id="cb2-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> MLP(nn.Module): </span>
<span id="cb2-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, layers: List[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>], dropout_prob: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>): </span>
<span id="cb2-9">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>(MLP, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>).<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>()</span>
<span id="cb2-10">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.layers <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.ModuleList([</span>
<span id="cb2-11">            nn.Linear(in_feat, out_feat) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> in_feat, out_feat <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(layers[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], layers[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:])</span>
<span id="cb2-12">            ])</span>
<span id="cb2-13">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.activation <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.LeakyReLU()</span>
<span id="cb2-14">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.dropout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Dropout(dropout_prob)</span>
<span id="cb2-15">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># print(self)</span></span>
<span id="cb2-16">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># print(f"Number trainable parameters: {sum(p.numel() for p in self.parameters() if p.requires_grad)} \n")</span></span>
<span id="cb2-17"></span>
<span id="cb2-18">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> forward(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x: torch.Tensor) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> torch.Tensor: </span>
<span id="cb2-19">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> layer <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.layers[:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]:</span>
<span id="cb2-20">            x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.activation(layer(x))</span>
<span id="cb2-21">            x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.dropout(x)</span>
<span id="cb2-22">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.layers[<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>](x)</span>
<span id="cb2-23"></span>
<span id="cb2-24"></span>
<span id="cb2-25"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> train_mlp(model: nn.Module, </span>
<span id="cb2-26">          num_epochs: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, </span>
<span id="cb2-27">          batch_size: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>,</span>
<span id="cb2-28">          num_twists: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>, </span>
<span id="cb2-29">          device: Union[torch.device, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>], </span>
<span id="cb2-30">          sample_noise: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>, </span>
<span id="cb2-31">          lr: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.001</span>):</span>
<span id="cb2-32">    model.train()</span>
<span id="cb2-33">    criterion <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.CrossEntropyLoss()</span>
<span id="cb2-34">    optimizer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.optim.Adam(model.parameters(), lr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>lr)</span>
<span id="cb2-35"></span>
<span id="cb2-36">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> epoch <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(num_epochs):</span>
<span id="cb2-37">        x, y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_spiral_samples(size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>batch_size, num_twists<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_twists, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device, noise<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sample_noise)</span>
<span id="cb2-38">        optimizer.zero_grad()      </span>
<span id="cb2-39">        y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(x)</span>
<span id="cb2-40">        loss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> criterion(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">input</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_pred, target<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_true)</span>
<span id="cb2-41">        loss.backward()</span>
<span id="cb2-42">        optimizer.step()</span>
<span id="cb2-43"></span>
<span id="cb2-44">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># if epoch % (num_epochs // 10) == 0 or epoch == num_epochs-1:</span></span>
<span id="cb2-45">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> epoch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> num_epochs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:</span>
<span id="cb2-46">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> torch.inference_mode():</span>
<span id="cb2-47">                x, y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_spiral_samples(size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, num_twists<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_twists, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device, noise<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sample_noise)</span>
<span id="cb2-48">                model.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">eval</span>()</span>
<span id="cb2-49">                y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.argmax(model(x), dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>).cpu() <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># shape [2**12], values in {0,1}</span></span>
<span id="cb2-50">                model.train()</span>
<span id="cb2-51">                y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_true.cpu()</span>
<span id="cb2-52">                f1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> f1_score(y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_true, y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_pred, zero_division <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb2-53">                acc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> accuracy_score(y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_true, y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_pred)</span>
<span id="cb2-54">                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># print(f"Epoch {epoch + 1}/{num_epochs}, Train Loss: {loss.cpu().item():.4f}, Test F1: {100*f1:.2f} %, Test Acc: {100*acc:.2f} %")</span></span>
<span id="cb2-55"></span>
<span id="cb2-56">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> model, f1, acc</span>
<span id="cb2-57"></span>
<span id="cb2-58"></span>
<span id="cb2-59"></span>
<span id="cb2-60"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>: <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># …to open pretrained model</span></span>
<span id="cb2-61">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mlp_specs.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rb'</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb2-62">        mlp_specs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pickle.load(handle)</span>
<span id="cb2-63">    mlp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> MLP(layers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"layers"</span>])</span>
<span id="cb2-64">    mlp.load_state_dict(torch.load(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mlp.pth"</span>, weights_only<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, map_location<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cpu"</span>))</span>
<span id="cb2-65">    mlp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mlp.to(DEVICE)</span>
<span id="cb2-66"></span>
<span id="cb2-67"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> (<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">FileNotFoundError</span>, <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">RuntimeError</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> e:</span>
<span id="cb2-68">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Else: Train new MLP Model:</span></span>
<span id="cb2-69">    mlp_specs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>()</span>
<span id="cb2-70">    mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"layers"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">32</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">32</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb2-71">    mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"num_epochs"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30000</span></span>
<span id="cb2-72">    mlp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> MLP(layers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"layers"</span>])</span>
<span id="cb2-73">    mlp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mlp.to(DEVICE)</span>
<span id="cb2-74">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> measure_duration(DEVICE) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> t:</span>
<span id="cb2-75">        mlp, f1, acc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_mlp(</span>
<span id="cb2-76">            model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mlp,</span>
<span id="cb2-77">            num_epochs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"num_epochs"</span>], </span>
<span id="cb2-78">            batch_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>, </span>
<span id="cb2-79">            num_twists<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>NUM_TWISTS, </span>
<span id="cb2-80">            sample_noise<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>SAMPLE_NOISE, </span>
<span id="cb2-81">            device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE)</span>
<span id="cb2-82">    torch.save(obj<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mlp.state_dict(), f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mlp.pth"</span>)</span>
<span id="cb2-83">    mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"duration"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> t.duration</span>
<span id="cb2-84">    mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f1"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> f1</span>
<span id="cb2-85">    mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"acc"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> acc</span>
<span id="cb2-86">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mlp_specs.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wb"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb2-87">        pickle.dump(mlp_specs, handle)</span>
<span id="cb2-88"></span>
<span id="cb2-89"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"num_epochs"</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> epochs, Test F1: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f1"</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> %, Test Acc: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"acc"</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> %'</span>)</span>
<span id="cb2-90"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f'Training took </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>mlp_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"duration"</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">s on M2 MacBook Air'</span>)</span>
<span id="cb2-91">plot_decision_boundary_for_mlp(</span>
<span id="cb2-92">    model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mlp, </span>
<span id="cb2-93">    sample_noise<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>SAMPLE_NOISE, </span>
<span id="cb2-94">    num_points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, </span>
<span id="cb2-95">    num_twists<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>NUM_TWISTS, </span>
<span id="cb2-96">    device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>30000 epochs, Test F1: 97.22 %, Test Acc: 97.22 %
Training took 60.71s on M2 MacBook Air</code></pre>
</div>
<div class="cell-output cell-output-display">
<div id="fig-contour-plot" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-contour-plot-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-contour-plot-output-2.webp" width="675" height="524" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-contour-plot-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Result of a trained MLP on samples of a static two-spirals instance with 1.75 twists. The network learned the underlying class distribution quite well (plotted as a contour in the background).
</figcaption>
</figure>
</div>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Evaluating 1,048,576 samples took 0.037s.</code></pre>
</div>
</div>
</section>
<section id="dynamic-scene-mlp-is-not-sufficient-anymore" class="level2">
<h2 class="anchored" data-anchor-id="dynamic-scene-mlp-is-not-sufficient-anymore">Dynamic Scene: MLP is not Sufficient Anymore</h2>
<p>So far, so easy. But you could also define other variants of these two-spirals by changing the number of twists, rotating the spirals by a few degrees or reversing the spirals’ direction of rotation (Figure&nbsp;3).</p>
<div id="cell-fig-9-random-spirals" class="cell" data-execution_count="3">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.visualizations <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> plot_9_spirals</span>
<span id="cb5-2">    </span>
<span id="cb5-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">################ Code: ################</span></span>
<span id="cb5-4">plot_9_spirals(</span>
<span id="cb5-5">    twists <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.rand(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>), </span>
<span id="cb5-6">    phase_shifts_rad <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> to_rad(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">45</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">90</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.rand(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>)),</span>
<span id="cb5-7">    reverseds <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.bernoulli(torch.rand(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>)),</span>
<span id="cb5-8">    sample_noise <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> SAMPLE_NOISE</span>
<span id="cb5-9">)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-9-random-spirals" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-9-random-spirals-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-9-random-spirals-output-1.webp" width="800" height="916" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-9-random-spirals-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Samples of nine random two-spirals instances.
</figcaption>
</figure>
</div>
</div>
</div>
<p>Imagine now you want to write <em>a single model</em> to classify every configuration of <code>twists</code>, <code>rotation</code> and <code>is_reversed</code>.</p>
<p>In the simple scenario (with only a single (static) <em>two-spirals</em> configuration) the trained model is able to predict the class labels based on 2D coordinates. It learned that certain 2D-coordinates correspond to certain class-probabilities. Or, to be more precise, it <em>is</em> the approximation of the class distributions (as seen in the background coloring of Figure&nbsp;2).</p>
<p>The more general case is way more complex:</p>
<blockquote class="blockquote">
<p>Imagine a third person selects a two-spirals configuration, draws samples, hands you just the samples without their respective colors nor configuration, and you have to reassign the labels again.</p>
</blockquote>
<p>Just the position of a sample (2D coordinate) is not sufficient for reassigning the label anymore, since you don’t know the underlying two-spirals configuration. A single 2D coordinate could be part of the orange or the blue spiral, depending on the underlying two-spirals configuration (Compare Figure&nbsp;8 with <img src="https://latex.codecogs.com/png.latex?c=1">).</p>
<div class="callout callout-style-simple callout-note no-icon callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Problem complexity: A chicken-and-egg problem
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>We actually want to classify (blue/ orange) samples based on their underlying distribution (the parametrized two-spirals and noise). But the parameters of the distribution are unknown and vary. This creates a loop:</p>
<ul>
<li><p>If we <em>knew</em> the parameters of the underlying distribution during inference time, we could easily predict the colors. (Train a model with <code>twists</code>, <code>is_reversed</code> and <code>rotation</code> as additional inputs)</p></li>
<li><p>But for estimating these parameters using traditional regression methods, we need labeled / colored samples.</p></li>
</ul>
<p>We have neither of them. During inference time, we only have a bunch of unlabeled / uncolored samples of an unknown configuration. In the following, we handle both problems in parallel.</p>
</div>
</div>
</div>
</section>
</section>
<section id="method-transformer-encoder-monte-carlo" class="level1">
<h1>Method: Transformer Encoder + Monte Carlo</h1>
<div id="fig-method" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-method-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/two_spirals/evalMethod.svg" class="img-fluid figure-img" style="width:80.0%">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-method-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: Method’s three main steps: (a) dataset is split into bags. Each contains <img src="https://latex.codecogs.com/png.latex?c="><code>bag_size</code> samples (b) all bags are classified simultaneously (c) the output is combined
</figcaption>
</figure>
</div>
<p>We need parallel sample prediction and estimating of the underlying distribution.</p>
<p>How? As mentioned above, it is impossible to infer the label based on just a single 2D coordinate. But what if you were looking at a few hundred or thousand simultaneously? Instead of handling single samples, you could bag multiple samples together. These bags clearly contain valuable information about the two-spirals configurations. Let’s say you partition the samples into bags of size <img src="https://latex.codecogs.com/png.latex?c">. The most efficient way would clearly be a network architecture, which takes this bag of <img src="https://latex.codecogs.com/png.latex?c"> samples and directly predicts <img src="https://latex.codecogs.com/png.latex?c"> labels for them – in parallel.</p>
<div class="callout callout-style-simple callout-note no-icon callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-3-contents" aria-controls="callout-3" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>Why the Transformer Encoder is better than an MLP for this job
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-3" class="callout-3-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>So, we want a <img src="https://latex.codecogs.com/png.latex?c%20%5Cto%20c"> network for this approach. Meaning: <img src="https://latex.codecogs.com/png.latex?c"> 2D coordinates have to be mapped to their respective <img src="https://latex.codecogs.com/png.latex?c"> labels.</p>
<p>We could design an MLP which tries to solve this problem. MLPs are universal function approximators. They could do it. If we designed an MLP for this task, the inputs would be <img src="https://latex.codecogs.com/png.latex?2c"> dimensional vectors (<img src="https://latex.codecogs.com/png.latex?c"> points per bag, each 2D) and the outputs would be <img src="https://latex.codecogs.com/png.latex?2c"> dimensional vectors (<img src="https://latex.codecogs.com/png.latex?c"> points per bag in <em>class logits</em> style).</p>
<ul>
<li><p>First of all, having an MLP connecting <img src="https://latex.codecogs.com/png.latex?2c"> input nodes with <img src="https://latex.codecogs.com/png.latex?2c"> output nodes would require at least <img src="https://latex.codecogs.com/png.latex?4c%5E2"> weights. This would limit <img src="https://latex.codecogs.com/png.latex?c"> to be very small and could be a harsh contrast to <img src="https://latex.codecogs.com/png.latex?c"> being sufficiently big to describe the two-spirals parameters sufficiently (e.g., for <img src="https://latex.codecogs.com/png.latex?c=256">, an MLP would have <img src="https://latex.codecogs.com/png.latex?4c%5E2%20=%202%5E%7B18%7D"> vs.&nbsp;1858 parameters of the transformer in Figure&nbsp;5).</p></li>
<li><p>Secondly, while the order of entries within a vector (MLPs) is relevant, the order of 2D points within a bag is arbitrary. So the network would have to learn that the order of the <img src="https://latex.codecogs.com/png.latex?c">-2D coordinates is not relevant. We could teach the network this using augmentations. We could shuffle the input and the output vector in the same way using multiple, random permutations during training (data augmentation). There are <img src="https://latex.codecogs.com/png.latex?c!"> permutations of <img src="https://latex.codecogs.com/png.latex?c"> elements. We cannot show the model every permutation during training (since <img src="https://latex.codecogs.com/png.latex?c!"> is huge; e.g.&nbsp;<img src="https://latex.codecogs.com/png.latex?10!%20%3E%2010%5E6">, <img src="https://latex.codecogs.com/png.latex?100!%20%3E%2010%5E%7B157%7D">, <img src="https://latex.codecogs.com/png.latex?1000!%20%3E%2010%5E%7B2567%7D">). And after training, you would not have a guarantee that changing the order of bag-elements does not affect the label assignments. The underlying problem is: MLPs are not <em>permutation equivariant</em>.</p></li>
</ul>
<section id="permutation-equivari-what" class="level2">
<h2 class="anchored" data-anchor-id="permutation-equivari-what">Permutation Equivari-WHAT?</h2>
<p>We call a function <img src="https://latex.codecogs.com/png.latex?f:%20%5Cmathbb%7BR%7D%5E%7Bn%20%5Ctimes%20m%7D%20%5Cto%20%20%5Cmathbb%7BR%7D%5E%7Bn%20%5Ctimes%20m%7D"> <strong><em>permutation equivariant</em></strong>, if for any permutation matrix <img src="https://latex.codecogs.com/png.latex?P%20%5Cin%20%5Cmathbb%7BR%7D%5E%7Bn%20%5Ctimes%20n%7D"> and any input matrix <img src="https://latex.codecogs.com/png.latex?X%20%5Cin%20%5Cmathbb%7BR%7D%5E%7Bn%20%5Ctimes%20m%7D"> , we have <img src="https://latex.codecogs.com/png.latex?f%5Cleft(P%5Ccdot%20X%5Cright)%20=%20P%5Ccdot%20f(X)%5C;."></p>
<div class="callout callout-style-default callout-tip callout-titled" title="Intuition Behind Permutation Equivariance">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Tip</span>Intuition Behind Permutation Equivariance
</div>
</div>
<div class="callout-body-container callout-body">
<p>Shuffling the inputs does automatically shuffle the outputs in the same way. The function’s output is the same – but it changed its order as the input did. For getting this behavior, no data augmentation during training or further tricks are needed – this behavior is just a property of <img src="https://latex.codecogs.com/png.latex?f">.</p>
</div>
</div>
<section id="examples-of-permutation-equivariant-functions" class="level4">
<h4 class="anchored" data-anchor-id="examples-of-permutation-equivariant-functions">Examples of Permutation Equivariant Functions</h4>
<ul>
<li>A function that is applied to every element in the bag independently is always permutation equivariant.
<ul>
<li>Applying an MLP to a batch of samples is permutation equivariant in the batch dimension.</li>
<li>Layer Normalization is applied to each sample independently and therefore permutation equivariant.</li>
</ul></li>
<li>Multi-head self-attention layers are permutation equivariant (if no positional encodings are used). This is a well known fact and easy to prove.</li>
</ul>
<p>So if we use the attention mechanism, we get this property for free and we overcome the <img src="https://latex.codecogs.com/png.latex?n!"> <em>permutation complexity</em> we had with MLPs.</p>
<blockquote class="blockquote">
<p>Attention layers are like magic: Every input token can influence every output token, the number of weights does not depend on the number of tokens <img src="https://latex.codecogs.com/png.latex?n">, and attention layers are permutation equivariant.</p>
</blockquote>
</section>
</section>
</div>
</div>
</div>
<section id="sec-apply-method" class="level2">
<h2 class="anchored" data-anchor-id="sec-apply-method">Applying the Method</h2>
<section id="model-architecture" class="level3">
<h3 class="anchored" data-anchor-id="model-architecture">Model Architecture</h3>
<p>This small 1,858-parameter model is a standard Transformer Encoder acting as a sequence-to-sequence map. It maps <img src="https://latex.codecogs.com/png.latex?%5Cmathbb%7BR%7D%5E%7Bc%20%5Ctimes%20d_%7B%5Ctext%7Bin%7D%7D%7D"> to class logits <img src="https://latex.codecogs.com/png.latex?%5Cmathbb%7BR%7D%5E%7Bc%20%5Ctimes%20d_%5Ctext%7Bout%7D%7D">.</p>
<ul>
<li><strong>Transformer Encoder:</strong> Three standard multi-head self-attention layers (<code>d_model = 8</code>, <code>nhead = 2</code>, <code>dim_feedforward = 16</code>)</li>
<li><strong>Input and Output Layers:</strong> Linear mappings (<img src="https://latex.codecogs.com/png.latex?d_%7B%5Ctext%7Bin%7D%7D%20%5Cto%20d_%5Ctext%7Bmodel%7D"> and <img src="https://latex.codecogs.com/png.latex?d_%5Ctext%7Bmodel%7D%20%5Cto%20d_%7B%5Ctext%7Bout%7D%7D">)</li>
<li><strong>No positional encodings:</strong> Since they break permutation equivariance.</li>
</ul>
</section>
<section id="training" class="level3">
<h3 class="anchored" data-anchor-id="training">Training</h3>
<ul>
<li><strong>Heavy Data Augmentations:</strong> For each bag, generate <img src="https://latex.codecogs.com/png.latex?c"> samples. Select for every bag a new random configuration:
<ul>
<li><code>num_twists</code><img src="https://latex.codecogs.com/png.latex?%5Csim%20%5Ctextit%7BUnif%7D(%5B0.5,%5C,%203.5%5D)"></li>
<li><code>rotation</code><img src="https://latex.codecogs.com/png.latex?%5Csim%20%5Ctextit%7BUnif%7D(%5B-45%5E%7B%5Ccirc%7D,%20%5C,%2045%5E%7B%5Ccirc%7D%5D)"></li>
<li><code>is_reversed</code> <img src="https://latex.codecogs.com/png.latex?%5Csim%20%5Ctextit%7BBer%7D(0.5)"></li>
</ul></li>
<li><strong>Batching:</strong> Combine <img src="https://latex.codecogs.com/png.latex?B"> independent bags into a tensor of shape <img src="https://latex.codecogs.com/png.latex?%5BB,%20c,%20d_%7B%5Ctext%7Bin%7D%7D%5D">.</li>
<li><strong>Loss:</strong> Point-wise cross-entropy applied to whole batch</li>
</ul>
</section>
<section id="inference-pipeline-for-arbitrary-set-size-n" class="level3">
<h3 class="anchored" data-anchor-id="inference-pipeline-for-arbitrary-set-size-n">Inference Pipeline (for Arbitrary Set Size <img src="https://latex.codecogs.com/png.latex?n">)</h3>
<div class="callout callout-style-simple callout-note no-icon">
<div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-body-container">
<pre><code>[Unordered Set: n points]
       │
       ▼  Step 1: Random Shuffle (π)
[Permuted Set]
       │
       ▼  Step 2: Partition into bags of size c (pad residual bag)
[Bags: ⌈n/c⌉ × c × d_in]
       │
       ▼  Step 3: Batched Forward Pass (Transformer Encoder)
[Bag Logits: ⌈n/c⌉ × c × d_out]
       │
       ▼  Step 4: Unpad, Argmax, and Invert Permutation (π⁻¹)
[Final Predictions: n labels]
</code></pre>
</div>
</div>
</div>
<ol type="1">
<li><strong>Global Permutation:</strong> Shuffle the <img src="https://latex.codecogs.com/png.latex?n"> input points using a random permutation <img src="https://latex.codecogs.com/png.latex?%5Cpi">. This breaks any spatial or sequential sorting artifacts present in the raw data.</li>
<li><strong>Bag Partitioning:</strong> Reshape the array into bags of size <img src="https://latex.codecogs.com/png.latex?c">. If <img src="https://latex.codecogs.com/png.latex?n"> is not divisible by <img src="https://latex.codecogs.com/png.latex?c">, pad the residual bag by recycling points from another bag. This guarantees the last bag to have the same context quality as all other bags.</li>
<li><strong>Batched Forward Pass:</strong> Pass the bags through the encoder in mini-batches.</li>
<li><strong>Reassembly:</strong> Flatten the predicted labels, discard the padded samples (from step 2), and apply the inverse permutation <img src="https://latex.codecogs.com/png.latex?%5Cpi%5E%7B-1%7D"> to restore the original input order.</li>
</ol>
<div id="cell-fig-loss-curve" class="cell" data-execution_count="4">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.visualizations <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> plot_loss_curve</span>
<span id="cb7-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb7-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sklearn.metrics <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> f1_score, accuracy_score</span>
<span id="cb7-4"></span>
<span id="cb7-5">RANGE_NUM_TWISTS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.5</span>]</span>
<span id="cb7-6">RANGE_ROTATIONS <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>math.pi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, math.pi<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>] <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ± 45°</span></span>
<span id="cb7-7">SAMPLE_NOISE <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.12</span></span>
<span id="cb7-8"></span>
<span id="cb7-9"></span>
<span id="cb7-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Model</span></span>
<span id="cb7-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> TransformerEncoder(nn.Module):</span>
<span id="cb7-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(</span>
<span id="cb7-13">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>,</span>
<span id="cb7-14">        input_dim: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>,</span>
<span id="cb7-15">        output_dim: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>,</span>
<span id="cb7-16">        d_model: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>,</span>
<span id="cb7-17">        nhead: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>,</span>
<span id="cb7-18">        num_layers: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>,</span>
<span id="cb7-19">        dim_feedforward: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>,</span>
<span id="cb7-20">        dropout: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>,</span>
<span id="cb7-21">    ):</span>
<span id="cb7-22">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>().<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>()</span>
<span id="cb7-23">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> d_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span> nhead <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"nhead = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>nhead<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> has to be a divisor of d_model = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>d_model<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> but is not."</span></span>
<span id="cb7-24">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.input_layer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(input_dim, d_model)</span>
<span id="cb7-25">        layer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.TransformerEncoderLayer(</span>
<span id="cb7-26">            d_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>d_model,</span>
<span id="cb7-27">            nhead<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>nhead,</span>
<span id="cb7-28">            dim_feedforward<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dim_feedforward,</span>
<span id="cb7-29">            dropout<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dropout,</span>
<span id="cb7-30">            activation<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"relu"</span>,</span>
<span id="cb7-31">            batch_first<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb7-32">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># norm_first=True,</span></span>
<span id="cb7-33">        )</span>
<span id="cb7-34">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.encoder <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.TransformerEncoder(</span>
<span id="cb7-35">            encoder_layer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> layer,</span>
<span id="cb7-36">            num_layers <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> num_layers,</span>
<span id="cb7-37">            norm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.LayerNorm(d_model),</span>
<span id="cb7-38">            enable_nested_tensor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>,</span>
<span id="cb7-39">        )</span>
<span id="cb7-40">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.output_layer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Linear(d_model, output_dim)</span>
<span id="cb7-41">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._reset_parameters()</span>
<span id="cb7-42">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># print(self)</span></span>
<span id="cb7-43">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># print(f"Number of trainable parameters: {sum(p.numel() for p in self.parameters() if p.requires_grad)} \n")</span></span>
<span id="cb7-44"></span>
<span id="cb7-45">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _reset_parameters(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb7-46">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Recommended by warning on https://docs.pytorch.org/docs/stable/generated/torch.nn.modules.transformer.TransformerEncoder.html</span></span>
<span id="cb7-47">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> module <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.modules():</span>
<span id="cb7-48">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(module, nn.Linear):</span>
<span id="cb7-49">                nn.init.xavier_uniform_(module.weight)</span>
<span id="cb7-50">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> module.bias <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb7-51">                    nn.init.zeros_(module.bias)</span>
<span id="cb7-52"></span>
<span id="cb7-53">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(module, nn.LayerNorm):</span>
<span id="cb7-54">                nn.init.ones_(module.weight)</span>
<span id="cb7-55">                nn.init.zeros_(module.bias)</span>
<span id="cb7-56"></span>
<span id="cb7-57">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> forward(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x):</span>
<span id="cb7-58">        x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.input_layer(x)</span>
<span id="cb7-59">        x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.encoder(x)</span>
<span id="cb7-60">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.output_layer(x)</span>
<span id="cb7-61"></span>
<span id="cb7-62"></span>
<span id="cb7-63"></span>
<span id="cb7-64"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> train_transformer():</span>
<span id="cb7-65">    model_specs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb7-66">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input_dim"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb7-67">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"output_dim"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb7-68">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"d_model"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>,</span>
<span id="cb7-69">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nhead"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb7-70">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"num_layers"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,</span>
<span id="cb7-71">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dim_feedforward"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>,</span>
<span id="cb7-72">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dropout"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>,</span>
<span id="cb7-73">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"RANGE_NUM_TWISTS"</span>: RANGE_NUM_TWISTS,</span>
<span id="cb7-74">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"RANGE_ROTATIONS"</span>: RANGE_ROTATIONS,</span>
<span id="cb7-75">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SAMPLE_NOISE"</span>: SAMPLE_NOISE,</span>
<span id="cb7-76">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"num_epochs"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150000</span>,</span>
<span id="cb7-77">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"batch_size"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>,</span>
<span id="cb7-78">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"training_bag_size"</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>      </span>
<span id="cb7-79">    }</span>
<span id="cb7-80">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Enclosure for batch wise sampling</span></span>
<span id="cb7-81">    sample_generator <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> num_twists, phase, is_reversed: get_spiral_samples(</span>
<span id="cb7-82">        size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"training_bag_size"</span>], </span>
<span id="cb7-83">        num_twists<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_twists, </span>
<span id="cb7-84">        device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE, </span>
<span id="cb7-85">        noise<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SAMPLE_NOISE"</span>], </span>
<span id="cb7-86">        phase_shift_rad<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>phase,</span>
<span id="cb7-87">        is_reversed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>is_reversed)</span>
<span id="cb7-88">    batched_sample_generator <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.func.vmap(sample_generator, randomness<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"different"</span>)</span>
<span id="cb7-89"></span>
<span id="cb7-90">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TransformerEncoder(</span>
<span id="cb7-91">        input_dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input_dim"</span>],</span>
<span id="cb7-92">        output_dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"output_dim"</span>],</span>
<span id="cb7-93">        d_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"d_model"</span>],</span>
<span id="cb7-94">        nhead<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nhead"</span>],</span>
<span id="cb7-95">        num_layers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"num_layers"</span>],</span>
<span id="cb7-96">        dim_feedforward<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dim_feedforward"</span>],</span>
<span id="cb7-97">        dropout<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dropout"</span>])</span>
<span id="cb7-98">    model.train()</span>
<span id="cb7-99">    criterion <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.CrossEntropyLoss()</span>
<span id="cb7-100">    optimizer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.optim.Adam(model.parameters(), lr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.001</span>)</span>
<span id="cb7-101">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.to(DEVICE)</span>
<span id="cb7-102"></span>
<span id="cb7-103">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">######### Do training #########</span></span>
<span id="cb7-104">    epoch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb7-105">    loss_curve <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb7-106">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> measure_duration(DEVICE) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> t:</span>
<span id="cb7-107">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> epoch <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"num_epochs"</span>]):</span>
<span id="cb7-108">            x, y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> batched_sample_generator(</span>
<span id="cb7-109">                RANGE_NUM_TWISTS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (RANGE_NUM_TWISTS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> RANGE_NUM_TWISTS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.rand  (model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"batch_size"</span>], device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE), </span>
<span id="cb7-110">                RANGE_ROTATIONS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (RANGE_ROTATIONS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> RANGE_ROTATIONS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.rand (model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"batch_size"</span>], device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE),</span>
<span id="cb7-111">                torch.bernoulli(torch.rand(model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"batch_size"</span>], device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE)))</span>
<span id="cb7-112">            optimizer.zero_grad()</span>
<span id="cb7-113">            y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(x)</span>
<span id="cb7-114">            loss <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> criterion(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">input</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_pred.reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), target<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_true.flatten())</span>
<span id="cb7-115">            loss.backward()</span>
<span id="cb7-116">            optimizer.step()</span>
<span id="cb7-117">            loss_curve.append(loss.item())</span>
<span id="cb7-118">    model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"loss_curve"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> loss_curve</span>
<span id="cb7-119">    model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"duration"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> t.duration</span>
<span id="cb7-120">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> model_specs, model</span>
<span id="cb7-121"></span>
<span id="cb7-122"></span>
<span id="cb7-123"></span>
<span id="cb7-124"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@torch.inference_mode</span>()</span>
<span id="cb7-125"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> eval_transformer(</span>
<span id="cb7-126">        model: nn.Module, </span>
<span id="cb7-127">        x: torch.Tensor, </span>
<span id="cb7-128">        eval_bag_size: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, </span>
<span id="cb7-129">        eval_batch_size: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># if not defined: take all</span></span>
<span id="cb7-130">        return_duration: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb7-131">    ):</span>
<span id="cb7-132">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb7-133"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">        Eval Function for the Transformer Encoder. Important are the sample shuffling and the filling up of the last bag (if necessary).</span></span>
<span id="cb7-134"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">    """</span></span>
<span id="cb7-135">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span>(model.parameters()).device <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> x.device, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb7-136">        <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"The model's device </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span>(model.parameters())<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>device<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> and the data's </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>x<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>device<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> differ."</span></span>
<span id="cb7-137">    device <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x.device</span>
<span id="cb7-138">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(x.shape) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> x.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb7-139">        <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Assumed x to have shape [num_samples, 2], but got </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>x<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>shape<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb7-140"></span>
<span id="cb7-141">    model.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">eval</span>()</span>
<span id="cb7-142">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> measure_duration(device) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> t:</span>
<span id="cb7-143">        perm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.randperm(x.shape[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device) </span>
<span id="cb7-144">        inv_perm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.empty_like(perm)</span>
<span id="cb7-145">        inv_perm[perm] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.arange(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(perm), device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>device)</span>
<span id="cb7-146">        x_perm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x[perm] </span>
<span id="cb7-147">        original_num_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(x)</span>
<span id="cb7-148">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(x_perm) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> eval_bag_size:</span>
<span id="cb7-149">            x_bags <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x_perm.unsqueeze(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Shape [1, num_samples, 2]</span></span>
<span id="cb7-150">            <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Warning: You wanted to evaluate the model with eval_bag_size: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>eval_bag_size<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> "</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+\</span></span>
<span id="cb7-151">                  <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"but just handed in </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(x_perm)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> samples. The prediction now uses "</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+\</span></span>
<span id="cb7-152">                  <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"only eval_bag_size </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(x_perm)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> instead."</span>)</span>
<span id="cb7-153">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb7-154">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># =&gt; There is at least one full bag. </span></span>
<span id="cb7-155">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> original_num_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span> eval_bag_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:</span>
<span id="cb7-156">                x_bags <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x_perm.reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, eval_bag_size, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb7-157">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb7-158">                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># What if the last bag is too small? </span></span>
<span id="cb7-159">                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># -&gt; Fill up last bag with samples of first bag:</span></span>
<span id="cb7-160">                residual <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> eval_bag_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> original_num_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span> eval_bag_size</span>
<span id="cb7-161">                x_bags <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.vstack([x_perm, x_perm[:residual]])</span>
<span id="cb7-162">                x_bags <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x_bags.reshape(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, eval_bag_size, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb7-163"></span>
<span id="cb7-164">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Eval model</span></span>
<span id="cb7-165">        y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb7-166">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(math.ceil(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(x_bags) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> eval_batch_size)):</span>
<span id="cb7-167">            logits <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model(x_bags[i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> eval_batch_size : (i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> eval_batch_size])</span>
<span id="cb7-168">            y_pred.append(</span>
<span id="cb7-169">                torch.argmax(logits, dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>).flatten()</span>
<span id="cb7-170">            )</span>
<span id="cb7-171"></span>
<span id="cb7-172">        y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.hstack(y_pred)</span>
<span id="cb7-173">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Discard the added samples</span></span>
<span id="cb7-174">        y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_pred[:original_num_samples] </span>
<span id="cb7-175">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Do unshuffling:</span></span>
<span id="cb7-176">        y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_pred[inv_perm]</span>
<span id="cb7-177">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> (y_pred, t.duration) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> return_duration <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> y_pred</span>
<span id="cb7-178"></span>
<span id="cb7-179"></span>
<span id="cb7-180"></span>
<span id="cb7-181"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">############# Code: #############</span></span>
<span id="cb7-182"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>: <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#... to load trained model and specs</span></span>
<span id="cb7-183">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"transformer_model_specs.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rb'</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb7-184">        model_specs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pickle.load(handle)</span>
<span id="cb7-185">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TransformerEncoder(</span>
<span id="cb7-186">        input_dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input_dim"</span>],</span>
<span id="cb7-187">        output_dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"output_dim"</span>],</span>
<span id="cb7-188">        d_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"d_model"</span>],</span>
<span id="cb7-189">        nhead<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nhead"</span>],</span>
<span id="cb7-190">        num_layers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"num_layers"</span>],</span>
<span id="cb7-191">        dim_feedforward<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dim_feedforward"</span>],</span>
<span id="cb7-192">        dropout<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dropout"</span>])</span>
<span id="cb7-193">    model.load_state_dict(torch.load(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"transformer_model.pth"</span>, weights_only<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, map_location<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cpu"</span>))</span>
<span id="cb7-194">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.to(DEVICE)</span>
<span id="cb7-195"></span>
<span id="cb7-196"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> (<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">FileNotFoundError</span>, <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">RuntimeError</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> e:</span>
<span id="cb7-197">    model_specs, model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_transformer()</span>
<span id="cb7-198">    torch.save(obj<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model.state_dict(), f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"transformer_model.pth"</span>)</span>
<span id="cb7-199">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"transformer_model_specs.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wb"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb7-200">        pickle.dump(model_specs, handle)</span>
<span id="cb7-201"></span>
<span id="cb7-202"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Training </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'num_epochs'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> epochs with bag size </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'training_bag_size'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> took </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'duration'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">s on M2 MacBook Air"</span>)</span>
<span id="cb7-203">plot_loss_curve(model_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"loss_curve"</span>])</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>Training 150000 epochs with bag size 256 took 2268.83s on M2 MacBook Air</code></pre>
</div>
<div class="cell-output cell-output-display">
<div id="fig-loss-curve" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-loss-curve-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-loss-curve-output-2.webp" width="664" height="451" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-loss-curve-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;5: The loss curve on the Transformer Encoder: Stable convergence
</figcaption>
</figure>
</div>
</div>
</div>
</section>
</section>
<section id="visual-results" class="level2">
<h2 class="anchored" data-anchor-id="visual-results">Visual Results</h2>
<p>Now that our model is trained, we can inspect some visual results.</p>
<section id="try-the-transformer-encoder-model-in-your-browser" class="level3">
<h3 class="anchored" data-anchor-id="try-the-transformer-encoder-model-in-your-browser">Try the Transformer Encoder Model in your Browser</h3>
<p>Click on the widget below or <a href="two_spirals/interactive_spirals.html">open it in a new tab</a>. Play with the parameters. Your CPU will calculate each forward pass in real-time.</p>
<div id="f811ecbd" class="cell" data-execution_count="5">
<div class="cell-output cell-output-display">

    <div id="facade-wrapper-3ea56f09" style="
        position: relative;
        width: 100%;
        aspect-ratio: 1904 / 1400; /* Replaced fixed height */
        border: 1px solid #dee2e6;
        border-radius: 8px;
        overflow: hidden;
        background-color: #f8f9fa;
        margin: 1.5rem 0;
    ">
        <!-- Blurred Poster Image -->
        <div style="
            position: absolute;
            inset: 0;
            background-image: url('two_spirals/interactive_spirals_dummy.webp');
            background-size: cover;
            background-position: center;
            filter: blur(5px) brightness(0.92);
            transform: scale(1.05);
            pointer-events: none;
        "></div>

        <!-- Overlay & Click Target -->
        <div id="facade-trigger-3ea56f09" tabindex="0" style="
            position: absolute;
            inset: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: rgba(0, 0, 0, 0.32);
            cursor: pointer;
            z-index: 10;
            user-select: none;
        ">
            <div style="
                background: #ffffff;
                color: #212529;
                padding: 12px 26px;
                border-radius: 30px;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                font-size: 1rem;
                font-weight: 600;
                box-shadow: 0 4px 14px rgba(0, 0, 0, 0.3);
                pointer-events: none;
            ">
                Click here to test the algorithm
            </div>
            <span style="
                color: #ffffff;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                font-size: 0.85rem;
                margin-top: 10px;
                text-shadow: 0 1px 3px rgba(0, 0, 0, 0.7);
                pointer-events: none;
            ">Interactive real-time widget</span>
        </div>
    </div>

    <script>
    (function() {
        function initFacade() {
            const trigger = document.getElementById("facade-trigger-3ea56f09");
            const wrapper = document.getElementById("facade-wrapper-3ea56f09");

            if (!trigger || !wrapper) return;

            function loadFrame(e) {
                if (e.type === 'keydown' && e.key !== 'Enter' && e.key !== ' ') return;
                e.preventDefault();

                const iframe = document.createElement("iframe");
                iframe.src = "two_spirals/interactive_spirals.html";
                iframe.style.width = "100%";
                iframe.style.height = "100%";
                iframe.style.border = "none";
                iframe.style.display = "block";

                wrapper.innerHTML = "";
                wrapper.appendChild(iframe);
            }

            trigger.addEventListener("click", loadFrame);
            trigger.addEventListener("keydown", loadFrame);
        }

        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", initFacade);
        } else {
            initFacade();
        }
    })();
    </script>
    
</div>
</div>
</section>
<section id="precomputed-visual-results" class="level3">
<h3 class="anchored" data-anchor-id="precomputed-visual-results">Precomputed Visual Results</h3>
<p>If your browser blocks JavaScript, the live widget above might not work. For that case, I generated some static precomputed examples: I combined three <em>number of twists</em> <code>[1, 2, 3]</code> with three <em>rotations</em> <code>[-30°, 0°, 30°]</code> to create 9 two-spirals instances. Below, you can see the model’s respective predictions:</p>
<div id="cell-fig-vis-results-1" class="cell" data-execution_count="6">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.visualizations <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> plot_visual_results</span>
<span id="cb9-2"></span>
<span id="cb9-3">plot_visual_results(</span>
<span id="cb9-4">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model, </span>
<span id="cb9-5">    eval_bag_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb9-6">    num_twists_arr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>], </span>
<span id="cb9-7">    rotations <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> to_rad(np.array([<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10e-4</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10e-4</span>)])), </span>
<span id="cb9-8">    is_reversed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>,</span>
<span id="cb9-9">    device <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DEVICE,</span>
<span id="cb9-10">    sample_noise <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> SAMPLE_NOISE,</span>
<span id="cb9-11">    evaluate_model_function <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> eval_transformer)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-vis-results-1" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-vis-results-1-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-vis-results-1-output-1.webp" width="912" height="1001" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-vis-results-1-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;6: Visual results for the trained Monte Carlo Attention model for various number of twists and rotations. The dot color corresponds to the model prediction. If the border color is red, the model prediction is wrong.
</figcaption>
</figure>
</div>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Evaluating 9 x 8,192 samples, each with evaluation bag size 1024 
and batch size 8 took 0.41s in total on M2.</code></pre>
</div>
</div>
<p>We get similarly good results if we reverse the spirals (i.e.&nbsp;changed twist direction):</p>
<div id="cell-fig-vis-results-2" class="cell" data-execution_count="7">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">plot_visual_results(</span>
<span id="cb11-2">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model, </span>
<span id="cb11-3">    eval_bag_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>,</span>
<span id="cb11-4">    num_twists_arr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>], </span>
<span id="cb11-5">    rotations <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> to_rad(np.array([<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10e-4</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10e-4</span>)])), </span>
<span id="cb11-6">    is_reversed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb11-7">    device <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DEVICE,</span>
<span id="cb11-8">    sample_noise <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> SAMPLE_NOISE,</span>
<span id="cb11-9">    evaluate_model_function <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> eval_transformer)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-vis-results-2" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-vis-results-2-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-vis-results-2-output-1.webp" width="917" height="1001" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-vis-results-2-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;7: Visual results for the trained Monte Carlo Attention model for various number of twists and rotations. But this time the spirals are reverse twisted. The dot color corresponds to the model prediction. If the border color is red, the model prediction is wrong.
</figcaption>
</figure>
</div>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Evaluating 9 x 8,192 samples, each with evaluation bag size 1024 
and batch size 8 took 0.33s in total on M2.</code></pre>
</div>
</div>
</section>
</section>
</section>
<section id="analysis-of-the-monte-carlo-behavior" class="level1">
<h1>Analysis of the Monte Carlo Behavior</h1>
<section id="robustness-to-bag-size-selection" class="level2">
<h2 class="anchored" data-anchor-id="robustness-to-bag-size-selection">Robustness to Bag Size Selection</h2>
<p>As you might know, one big advantage of the Transformer architecture is that it is independent of the number of input samples. Thus, when we train a Transformer using a certain bag size we can evaluate it later using any other bag size. Maybe you noticed that I trained the Transformer Encoder in Section&nbsp;2.2 with <code>training_bag_size = 256</code> while I evaluated it in Figure&nbsp;6 and Figure&nbsp;7 with <code>eval_bag_size = 1024</code>. The classification result does of course depend somehow on the bag size <img src="https://latex.codecogs.com/png.latex?c">. If <img src="https://latex.codecogs.com/png.latex?c"> is large, the model should get more valuable context and thus, be more accurate. But can we quantify this influence?</p>
<p>Let’s take our trained model from Section&nbsp;2.2 and do the following: We take <img src="https://latex.codecogs.com/png.latex?2%5E%7B20%7D%20%E2%89%88%201"> million samples from 32 random configurations and classify them using bag sizes <img src="https://latex.codecogs.com/png.latex?c%20=%201,%202,%204,%208,%20%E2%80%A6%20,%204096"> (each 20 times).</p>
<div id="cell-fig-boxplot" class="cell" data-execution_count="8">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> math</span>
<span id="cb13-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> collections <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> defaultdict</span>
<span id="cb13-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb13-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> seaborn <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> sns</span>
<span id="cb13-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.visualizations <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> create_robustness_boxplots</span>
<span id="cb13-6"></span>
<span id="cb13-7"></span>
<span id="cb13-8"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@torch.inference_mode</span>()</span>
<span id="cb13-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> compute_monte_carlo_statistics(</span>
<span id="cb13-10">    num_samples: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Approx. 1 million samples each</span></span>
<span id="cb13-11">    num_runs: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># For testing random bagging</span></span>
<span id="cb13-12">    num_configurations: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">32</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Random Spirals each</span></span>
<span id="cb13-13">    bag_sizes: List[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>)]</span>
<span id="cb13-14">    ):</span>
<span id="cb13-15"></span>
<span id="cb13-16">    f1_scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>)</span>
<span id="cb13-17">    label_toggle_statistics <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(defaultdict(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>).copy) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># see next sub-section</span></span>
<span id="cb13-18">    timings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>)</span>
<span id="cb13-19"></span>
<span id="cb13-20">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _ <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(num_configurations):</span>
<span id="cb13-21">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Randomly choose new configuration and sample</span></span>
<span id="cb13-22">        num_twists <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> RANGE_NUM_TWISTS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (RANGE_NUM_TWISTS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> RANGE_NUM_TWISTS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.rand(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE)</span>
<span id="cb13-23">        phase_shift_rad <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> RANGE_ROTATIONS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (RANGE_ROTATIONS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> RANGE_ROTATIONS[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> torch.rand(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE)</span>
<span id="cb13-24">        is_reversed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.bernoulli(torch.rand(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE))</span>
<span id="cb13-25">        x, y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_spiral_samples(size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_samples, </span>
<span id="cb13-26">                            num_twists<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_twists, </span>
<span id="cb13-27">                            phase_shift_rad<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>phase_shift_rad,</span>
<span id="cb13-28">                            is_reversed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>is_reversed,</span>
<span id="cb13-29">                            device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE, </span>
<span id="cb13-30">                            noise<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>SAMPLE_NOISE,</span>
<span id="cb13-31">                            shuffle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Happens in the eval function every call</span></span>
<span id="cb13-32">        y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_true.cpu().numpy()</span>
<span id="cb13-33">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> c <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> bag_sizes:</span>
<span id="cb13-34">            y_preds <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb13-35">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _ <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(num_runs):</span>
<span id="cb13-36">                y_pred, duration <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> eval_transformer(</span>
<span id="cb13-37">                    model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>model, </span>
<span id="cb13-38">                    x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>x, </span>
<span id="cb13-39">                    eval_bag_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>c, </span>
<span id="cb13-40">                    eval_batch_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>((<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(bag_sizes) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span> (c <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># I want to use ≤ 4 GB Unified Mem for this process</span></span>
<span id="cb13-41">                    return_duration<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span></span>
<span id="cb13-42">                )</span>
<span id="cb13-43">                timings[c] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> duration</span>
<span id="cb13-44">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(y_pred) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(x), <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb13-45">                    <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Shape y_pred: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>y_pred<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>shape<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, but there are </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(x)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> samples"</span></span>
<span id="cb13-46">                y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_pred.cpu().numpy()</span>
<span id="cb13-47">                y_preds.append(y_pred)</span>
<span id="cb13-48">                f1_scores[c].append(f1_score(y_true<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_true, y_pred<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_pred))</span>
<span id="cb13-49"></span>
<span id="cb13-50">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Calculate: How often did the label assignment of samples change during num_runs baggings of the same samples?</span></span>
<span id="cb13-51">            y_preds <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.array(y_preds)</span>
<span id="cb13-52">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (y_preds.shape <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> np.array([num_runs, num_samples])).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">all</span>(), <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb13-53">                <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"y_preds: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>y_preds<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>shape<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, but num_runs: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>num_runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, num_samples: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>num_samples<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb13-54"></span>
<span id="cb13-55">            toggles <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(y_preds <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> y_true[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, :], axis<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [num_runs, num_samples]</span></span>
<span id="cb13-56">            toggles <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.fmin(toggles, num_runs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> toggles) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [num_samples]</span></span>
<span id="cb13-57">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (toggles.shape <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> np.array(num_samples)).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">all</span>(), <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb13-58">                <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"toggles: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>toggles<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>shape<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, but num_samples: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>num_samples<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb13-59"></span>
<span id="cb13-60">            values, counts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> np.unique(toggles, return_counts<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb13-61">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> value, count <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">zip</span>(values, counts):</span>
<span id="cb13-62">                label_toggle_statistics[c][<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(value)] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(count)</span>
<span id="cb13-63">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> f1_scores, timings, label_toggle_statistics</span>
<span id="cb13-64"></span>
<span id="cb13-65"></span>
<span id="cb13-66"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb13-67">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f1_scores.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rb'</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb13-68">        f1_scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pickle.load(handle)</span>
<span id="cb13-69">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"timings.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rb'</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb13-70">        timings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pickle.load(handle)</span>
<span id="cb13-71">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label_toggle_statistics.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'rb'</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb13-72">        label_toggle_statistics <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pickle.load(handle)</span>
<span id="cb13-73"></span>
<span id="cb13-74"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">FileNotFoundError</span> <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> e:</span>
<span id="cb13-75">    f1_scores, timings, label_toggle_statistics <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> compute_monte_carlo_statistics()</span>
<span id="cb13-76">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f1_scores.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wb"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb13-77">        pickle.dump(f1_scores, handle)</span>
<span id="cb13-78">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"timings.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wb"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb13-79">        pickle.dump(timings, handle)</span>
<span id="cb13-80">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"label_toggle_statistics.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wb"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb13-81">        pickle.dump(label_toggle_statistics, handle)</span>
<span id="cb13-82"></span>
<span id="cb13-83"></span>
<span id="cb13-84">create_robustness_boxplots(f1_scores)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-boxplot" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-boxplot-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-boxplot-output-1.webp" width="671" height="510" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-boxplot-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;8: The classification f1 score depends on the bag size <img src="https://latex.codecogs.com/png.latex?c">. If the bag size increases we see better results. Note that the x-axis uses a logarithmic scale: <img src="https://latex.codecogs.com/png.latex?c"> can be chosen to be relatively small (256 or greater) to get results comparable to the MLP from Figure&nbsp;2.
</figcaption>
</figure>
</div>
</div>
</div>
<p>As you can see, we get very good results if the bag size <img src="https://latex.codecogs.com/png.latex?c"> is selected big enough for our needs. Note furthermore that the variance of the f1-scores does also decrease for increasing <img src="https://latex.codecogs.com/png.latex?c">.</p>
<p>The curve behaves somehow as expected for a Monte Carlo method. Single samples behave randomly (f1 score <img src="https://latex.codecogs.com/png.latex?%5Capprox%2050%20%5C%25"> corresponds to coin flipping in this class-balanced setup). Larger bags provide a more representative empirical approximation of the underlying distribution (see law of large numbers). Empirically, the performance stabilizes as <img src="https://latex.codecogs.com/png.latex?c"> increases.</p>
<p>But with larger bag size <img src="https://latex.codecogs.com/png.latex?c">, the runtime also increases:</p>
<div id="cell-fig-eval-timing" class="cell" data-execution_count="9">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.visualizations <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> create_timing_barplot</span>
<span id="cb14-2">create_timing_barplot(total_num_runs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(f1_scores[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]), timings<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>timings)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-eval-timing" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-eval-timing-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-eval-timing-output-1.webp" width="663" height="510" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-eval-timing-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;9: Duration for predicting <img src="https://latex.codecogs.com/png.latex?2%5E%7B20%7D"> ≈ 1 million samples depending on the bag size during evaluation. The values are averages of 20 x 32 runs. Note that the x-axis uses a logarithmic scale: The duration increases linearly in <img src="https://latex.codecogs.com/png.latex?c">. All measurements are made on an M2 MacBook Air.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The runtime increases in <img src="https://latex.codecogs.com/png.latex?c"> in a linear way: It roughly doubles if <img src="https://latex.codecogs.com/png.latex?c"> doubles (see Section&nbsp;4). As with many other Monte Carlo methods, it is up to you to balance accuracy with resource usage.</p>
</section>
<section id="sec-robustness-random-part" class="level2">
<h2 class="anchored" data-anchor-id="sec-robustness-random-part">Robustness to Random Partitioning</h2>
<p>Furthermore, if we randomly partition the dataset into bags and classify each bag independently, the classification result of a specific sample might change, depending on whether it is randomly bagged into one or another bag (one bag may provide more informative context than others). This is why I ran the experiment above 20 times: each time with a new random partition. I calculated how often the model changed its classification decision during the 20 runs for each of the <img src="https://latex.codecogs.com/png.latex?32%20%5Ctimes%202%5E%7B20%7D%20%5Capprox%2033.5"> million samples:</p>
<div id="cell-fig-mc-random-bagging" class="cell" data-execution_count="10">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.visualizations <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> create_consistency_plot</span>
<span id="cb15-2">create_consistency_plot(label_toggle_statistics)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-mc-random-bagging" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-mc-random-bagging-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-mc-random-bagging-output-1.webp" width="750" height="559" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-mc-random-bagging-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;10: What is the influence of random bagging? During 20 independent random partitions on the same <img src="https://latex.codecogs.com/png.latex?32"> x <img src="https://latex.codecogs.com/png.latex?2%5E%7B20%7D"> samples set: How consistently did the model predict each sample? I call the model 100 % consistent on a certain sample if it predicts in all 20 times the same label. If it predicts on a certain sample 10 times orange and 10 times blue depending on the other samples in its bag I call it 0 % consistent. Note that the x-axis uses a logarithmic scale. The model is very consistent for surprisingly small bag sizes.
</figcaption>
</figure>
</div>
</div>
</div>
<p>Some notes on the graphic:</p>
<ul>
<li>Edge case <img src="https://latex.codecogs.com/png.latex?c=1">: Every bag has only one sample inside. Therefore, there is no random context inside a bag and thus, the model is 100 % consistent in its answers. Note that this does not mean the model predicts correctly (compare Figure&nbsp;8) – it’s just consistent.</li>
<li>The model rapidly gains consistency as <img src="https://latex.codecogs.com/png.latex?c"> increases. The law of large numbers is on our side again. Sure, this result is compatible with Figure&nbsp;8 above.</li>
</ul>
<section id="consistency-benchmarking-as-trustworthiness-measure" class="level3">
<h3 class="anchored" data-anchor-id="consistency-benchmarking-as-trustworthiness-measure">Consistency Benchmarking as Trustworthiness Measure</h3>
<p>Applying random partitioning and evaluating the model multiple times does not involve any target values. Meaning: This test is always possible during inference time. - This test can be used to check if a bag size <img src="https://latex.codecogs.com/png.latex?c"> is chosen large enough. If the model swaps too often, try to choose a larger bag size <img src="https://latex.codecogs.com/png.latex?c">. - When you want to apply the trained model to a similar, unseen data set, this test can signal how well the model describes the data. Low consistency could be an indicator for out-of-distribution behavior.</p>
</section>
</section>
<section id="robustness-to-spatially-missing-regions" class="level2">
<h2 class="anchored" data-anchor-id="robustness-to-spatially-missing-regions">Robustness to Spatially Missing Regions</h2>
<p>Let’s draw spirals and punch some holes into the datasets to account for missing regions (without training on this new problem). How stable is the model w.r.t. this perturbation?</p>
<div id="cell-fig-hole-perturbation" class="cell" data-fig-format="svg" data-execution_count="11">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@torch.inference_mode</span>()</span>
<span id="cb16-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> plot_missing_region_results(</span>
<span id="cb16-3">        model: nn.Module, </span>
<span id="cb16-4">        num_twists_array: List[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>], </span>
<span id="cb16-5">        holes: List[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>], </span>
<span id="cb16-6">        eval_bag_size: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>,</span>
<span id="cb16-7">        num_samples: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>,</span>
<span id="cb16-8">        is_reversed: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>):</span>
<span id="cb16-9"></span>
<span id="cb16-10">    num_effective_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb16-11">    duration <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span></span>
<span id="cb16-12"></span>
<span id="cb16-13">    model.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">eval</span>()</span>
<span id="cb16-14">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model.to(DEVICE)</span>
<span id="cb16-15">    fig, axes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> plt.subplots(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(holes), <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(num_twists_array), figsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">4.34</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(holes))) </span>
<span id="cb16-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, (hole_x, hole_y, hole_radius) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(holes):</span>
<span id="cb16-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> j, num_twists <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(num_twists_array):</span>
<span id="cb16-18">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># is_reversed = (i + j) % 2 == 0</span></span>
<span id="cb16-19">            ax <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> axes[i, j]</span>
<span id="cb16-20">            x, y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_spiral_samples(size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_samples, </span>
<span id="cb16-21">                                      noise<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>SAMPLE_NOISE, </span>
<span id="cb16-22">                                      device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE,</span>
<span id="cb16-23">                                      num_twists<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>num_twists, </span>
<span id="cb16-24">                                      phase_shift_rad<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span>,</span>
<span id="cb16-25">                                      is_reversed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>is_reversed,</span>
<span id="cb16-26">                                      shuffle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb16-27"></span>
<span id="cb16-28">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">############# Perturb: Delete circle and eval model #############</span></span>
<span id="cb16-29">            outside_hole_mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (x[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> hole_x) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (x[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> hole_y) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> hole_radius <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb16-30">            x, y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x[outside_hole_mask], y_true[outside_hole_mask]</span>
<span id="cb16-31">            num_effective_samples <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(x)</span>
<span id="cb16-32">            y_pred, duration_run <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> eval_transformer(</span>
<span id="cb16-33">                model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model, </span>
<span id="cb16-34">                x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x, </span>
<span id="cb16-35">                eval_bag_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> eval_bag_size, </span>
<span id="cb16-36">                eval_batch_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># just do all in one pass</span></span>
<span id="cb16-37">                return_duration <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb16-38">            y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_pred.cpu()</span>
<span id="cb16-39">            y_true <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y_true.cpu()</span>
<span id="cb16-40">            duration <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> duration_run</span>
<span id="cb16-41"></span>
<span id="cb16-42">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">############# Create Plot #############</span></span>
<span id="cb16-43">            incorrect <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (y_pred <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> y_true)</span>
<span id="cb16-44">            edge_colors <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"red"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> wrong <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"black"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> wrong <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> incorrect]</span>
<span id="cb16-45">            line_widths <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> wrong <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.02</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> wrong <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> incorrect]</span>
<span id="cb16-46"></span>
<span id="cb16-47">            ax.scatter(</span>
<span id="cb16-48">                x[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>].cpu(), </span>
<span id="cb16-49">                x[:, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>].cpu(), </span>
<span id="cb16-50">                c<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_pred, </span>
<span id="cb16-51">                cmap<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>cmap_blue_orange, </span>
<span id="cb16-52">                s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, </span>
<span id="cb16-53">                edgecolors<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>edge_colors, </span>
<span id="cb16-54">                linewidths<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>line_widths,</span>
<span id="cb16-55">                alpha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span></span>
<span id="cb16-56">            )</span>
<span id="cb16-57"></span>
<span id="cb16-58">            ax.set_aspect(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"equal"</span>, adjustable<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"box"</span>)</span>
<span id="cb16-59">            ax.set_xlim([<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.2</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.2</span>])</span>
<span id="cb16-60">            ax.set_ylim([<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.2</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.2</span>])</span>
<span id="cb16-61">            reversal_text <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">", reversed"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> is_reversed <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span></span>
<span id="cb16-62">            acc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> accuracy_score(y_true<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_true, y_pred<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>y_pred)</span>
<span id="cb16-63">            f1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> f1_score(y_true, y_pred)</span>
<span id="cb16-64">            ax.set_title(</span>
<span id="cb16-65">                <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>num_twists<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> twist(s) </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>reversal_text<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> Hole at </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>(hole_x, hole_y)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> with radius </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>hole_radius<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb16-66">                <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"F1: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>f1<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> %, Acc: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>acc<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> %"</span></span>
<span id="cb16-67">                )</span>
<span id="cb16-68">            ax.get_xaxis().set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb16-69">            ax.get_yaxis().set_visible(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb16-70">    plt.show()</span>
<span id="cb16-71">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Evaluating </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>num_effective_samples<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:,d}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> samples with evaluation bag size </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>eval_bag_size<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> took </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>duration<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">s in total on M2."</span>)</span>
<span id="cb16-72"></span>
<span id="cb16-73"></span>
<span id="cb16-74"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">########### Code ###########</span></span>
<span id="cb16-75">plot_missing_region_results(</span>
<span id="cb16-76">    model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> model, </span>
<span id="cb16-77">    num_twists_array <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>], </span>
<span id="cb16-78">    holes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>), (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>), (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>), (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>)], </span>
<span id="cb16-79">    eval_bag_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb16-80">)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-display">
<div id="fig-hole-perturbation" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-hole-perturbation-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-hole-perturbation-output-1.webp" width="912" height="1342" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-hole-perturbation-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;11: Spirals with holes: You can see 12 two-spirals instances where I deleted all samples inside a certain area (large circle). I used the trained model from above to classify the remaining samples (dot content = model prediction; red border = prediction is wrong). Even if I did not train the model again the model still performs reliably.
</figcaption>
</figure>
</div>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Evaluating 88,612 samples with evaluation bag size 1024 took 0.46s in total on M2.</code></pre>
</div>
</div>
<p>Remember: The model has not seen these perturbations during training – complete <em>out-of-distribution</em> test set. The model still performs pretty well (<img src="https://latex.codecogs.com/png.latex?%5Capprox%2090%20%5C%25"> accuracy and higher). This is due to the fact that the model is trained to handle only fractions (bags) of the whole set. If regions are missing in the whole sample set, the model might interpret the missing values as just not included in the observed random bag. Bags which do not contain any information of certain areas are unlikely, but possible.</p>
<p>I could also argue that the wrong predictions in Figure&nbsp;11 are actually markers where the model would have needed samples in the missing region.</p>
</section>
</section>
<section id="sec-runtime-analysis" class="level1">
<h1>Linear Runtime and Memory Complexity</h1>
<p>If <img src="https://latex.codecogs.com/png.latex?n"> is the number of samples and <img src="https://latex.codecogs.com/png.latex?c"> the bag size, the resulting runtime complexity is <img src="https://latex.codecogs.com/png.latex?O%5Cleft(%5Cfrac%7Bn%7D%7Bc%7D%20%5Ccdot%20c%5E2%20%5Cright)%20=%20O%5Cleft(n%20%5Ccdot%20c%20%5Cright)"> because we have <img src="https://latex.codecogs.com/png.latex?%5Clceil%5Cfrac%7Bn%7D%7Bc%7D%20%5Crceil"> bags and calculating attention to each bag is in <img src="https://latex.codecogs.com/png.latex?O(c%5E2)">. If <img src="https://latex.codecogs.com/png.latex?c"> is a small constant, this algorithm runs in <img src="https://latex.codecogs.com/png.latex?O(n)">.</p>
<p>The memory complexity is <img src="https://latex.codecogs.com/png.latex?O%5Cleft(c%5E2%20%5Cright)"> if we handle the data as streams.</p>
</section>
<section id="comparison-to-other-architectures" class="level1">
<h1>Comparison to other Architectures</h1>
<div class="callout callout-style-simple callout-note no-icon callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-4-contents" aria-controls="callout-4" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>PointTransformer v3 and LitePT vs.&nbsp;higher dimensions
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-4" class="callout-4-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>PointTransformer v3 and LitePT are very advanced Transformer and Convolution-based methods for 3D-Point clouds. They first discretize the space and then use space-filling curves for defining local neighborhood orders. These orders result in a 1D vector. Then, a U-Net like network structure is applied on local windows of this 1D vector to generate a global-local segmentation method for the point cloud.</p>
<p>But: I created the MC-method because I needed to segment 45 dimensional point clouds (RapidParc). Applying the method of space filling curves to 45 dimensions is not practical:</p>
<ul>
<li><p><strong>Grid representation issues:</strong> Calculating space filling curves in 3D can be done efficiently using bit acrobatics. Applying this method to higher dimensions results in headaches. Using <code>uint64</code> would give you only 1 bit per axis (i.e.&nbsp;only two values per axis <img src="https://latex.codecogs.com/png.latex?%5Cto"> bad resolution). If we chose 10 bits per axis (1024 positions per axis) we would need a 450-bit global index. 450 bit cannot be computed efficiently on standard hardware. Therefore, the efficiency gains of PTv3 and LitePT do not hold anymore.</p></li>
<li><p><strong>Many dimensions = many neighbors:</strong> The idea of Morton codes is based on the idea that if two points are close to each other in a grid space, they are close to each other in the 1D order of the space-filling curve. This argument fails in 45 dimensional space. While a point in a 3D grid has 26 neighbors, it has <img src="https://latex.codecogs.com/png.latex?3%5E%7B45%7D-1%20%5Capprox%202.9%5Ctimes%2010%5E%7B21%7D"> neighbors in a 45 dimensional grid. Therefore, any possible window size would be too small to capture all neighbors. Or: A small window size could include the wrong neighbors. Furthermore, as there are so many neighbors in 45D, we cannot utilize sparse convolutions as these methods did.</p></li>
<li><p><strong>CUDA implementation:</strong> The implementation of these methods uses CUDA kernels. I currently don’t have NVIDIA Accelerators for testing.</p></li>
</ul>
</div>
</div>
</div>
<div class="callout callout-style-simple callout-note no-icon callout-titled">
<div class="callout-header d-flex align-content-center collapsed" data-bs-toggle="collapse" data-bs-target=".callout-5-contents" aria-controls="callout-5" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>PointNet struggles with complexity
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-5" class="callout-5-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>PointNet is a pioneering MLP-based point cloud segmentation method. It combines shared MLPs with pooling layers for global feature extraction. This global information is concatenated to every point feature vector. Another shared MLP classifies each vector separately.</p>
<div class="cell" data-execution_count="12">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.pointnet <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> PointNetSeg, train_pointnet</span>
<span id="cb18-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> two_spirals.visualizations <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> plot_visual_results, plot_loss_curve</span>
<span id="cb18-3"></span>
<span id="cb18-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- Train or Load Pretrained Weights ---</span></span>
<span id="cb18-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb18-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pointnet_model_specs.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rb"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb18-7">        pn_specs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pickle.load(handle)</span>
<span id="cb18-8">    pn_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> PointNetSeg(</span>
<span id="cb18-9">        input_dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pn_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input_dim"</span>],</span>
<span id="cb18-10">        output_dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pn_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"output_dim"</span>],</span>
<span id="cb18-11">        feat_dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pn_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"feat_dim"</span>],</span>
<span id="cb18-12">    )</span>
<span id="cb18-13">    pn_model.load_state_dict(torch.load(save_dir <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pointnet_model.pth"</span>, weights_only<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, map_location<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cpu"</span>))</span>
<span id="cb18-14">    pn_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pn_model.to(DEVICE)</span>
<span id="cb18-15"></span>
<span id="cb18-16"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> (<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">FileNotFoundError</span>, <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">RuntimeError</span>):</span>
<span id="cb18-17">    pn_specs, pn_model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> train_pointnet(</span>
<span id="cb18-18">        DEVICE<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE, </span>
<span id="cb18-19">        RANGE_NUM_TWISTS<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>RANGE_NUM_TWISTS, </span>
<span id="cb18-20">        RANGE_ROTATIONS<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>RANGE_ROTATIONS, </span>
<span id="cb18-21">        SAMPLE_NOISE<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>SAMPLE_NOISE)</span>
<span id="cb18-22">    torch.save(obj<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pn_model.state_dict(), f<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>save_dir <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pointnet_model.pth"</span>)</span>
<span id="cb18-23">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(save_dir <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pointnet_model_specs.pickle"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wb"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> handle:</span>
<span id="cb18-24">        pickle.dump(pn_specs, handle)</span>
<span id="cb18-25"></span>
<span id="cb18-26"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>pn_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'num_epochs'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> epochs took </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>pn_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'duration'</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">s"</span>)</span>
<span id="cb18-27"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Trainable parameters: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(p.numel() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> p <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> pn_model.parameters() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> p.requires_grad)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb18-28">plot_loss_curve(pn_specs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"loss_curve"</span>])</span>
<span id="cb18-29"></span>
<span id="cb18-30"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># --- Visual Inspection ---</span></span>
<span id="cb18-31">plot_visual_results(</span>
<span id="cb18-32">    model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pn_model,</span>
<span id="cb18-33">    num_samples<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># results in [1, 2**13, 2] model input</span></span>
<span id="cb18-34">    eval_bag_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># same as num_samples =&gt; only one bag, no random bagging</span></span>
<span id="cb18-35">    num_twists_arr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>],</span>
<span id="cb18-36">    rotations<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>to_rad(np.array([<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10e-4</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10e-4</span>)])),</span>
<span id="cb18-37">    is_reversed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>,</span>
<span id="cb18-38">    device<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEVICE,</span>
<span id="cb18-39">    sample_noise<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>SAMPLE_NOISE,</span>
<span id="cb18-40">    evaluate_model_function<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>eval_transformer <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># possible due to eval_bag_size=num_samples =&gt; no random bagging</span></span>
<span id="cb18-41">)</span></code></pre></div></div>
</details>
<div class="cell-output cell-output-stdout">
<pre><code>100000 epochs took 717.55s
Trainable parameters: 2898</code></pre>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Evaluating 9 x 8,192 samples, each with evaluation bag size 8192 
and batch size 1 took 0.03s in total on M2.</code></pre>
</div>
<div id="fig-pointnet-results" class="cell quarto-float quarto-figure quarto-figure-center anchored" data-execution_count="12">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-pointnet-results-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<div class="cell-output cell-output-display">
<div id="fig-pointnet-results-1" class="quarto-float quarto-figure quarto-figure-center anchored">
<figure class="quarto-float quarto-subfloat-fig figure">
<div aria-describedby="fig-pointnet-results-1-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-pointnet-results-output-2.webp" data-ref-parent="fig-pointnet-results" width="667" height="455" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-subfloat-caption quarto-subfloat-fig" id="fig-pointnet-results-1-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
(a) Training and evaluating a PointNet baseline on the dynamic two-spirals task using the same stochastic bag setup as with the Transformer Encoder + Monte Carlo Approach
</figcaption>
</figure>
</div>
</div>
<div class="cell-output cell-output-display">
<div id="fig-pointnet-results-2" class="quarto-float quarto-figure quarto-figure-center anchored" height="998" width="912">
<figure class="quarto-float quarto-subfloat-fig figure">
<div aria-describedby="fig-pointnet-results-2-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://vavobo.de/posts/monte_carlo_set_segmentation_files/figure-html/fig-pointnet-results-output-3.webp" id="fig-pointnet-results-2" data-ref-parent="fig-pointnet-results" width="912" height="998" class="figure-img">
</div>
<figcaption class="quarto-float-caption-bottom quarto-subfloat-caption quarto-subfloat-fig" id="fig-pointnet-results-2-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
(b)
</figcaption>
</figure>
</div>
</div>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig quarto-uncaptioned" id="fig-pointnet-results-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;12
</figcaption>
</figure>
</div>
</div>
<p>The result? It fails entirely. Because all of these dynamic spirals occupy roughly the same noisy 2D disk, PointNet’s global max-pooling discards the fine-grained relational structure needed to infer twists, rotation, and direction—it looks at the overall geometry, shrugs, and decides everything is just a very confusing circle.</p>
</div>
</div>
</div>
</section>
<section id="final-notes" class="level1">
<h1>Final Notes</h1>
<ul>
<li>This method is easy to understand and fast to implement.</li>
<li>It is highly accurate (see <a href="https://github.com/MedVisBonn/RapidParc">RapidParc</a>&nbsp;(<a href="https://doi.org/10.1162/IMAG.a.1168">published in&nbsp;<em>Imaging Neuroscience</em></a>)).</li>
<li>It has a fast <img src="https://latex.codecogs.com/png.latex?O(n%5Ccdot%20c)"> runtime and a small memory footprint <img src="https://latex.codecogs.com/png.latex?O(c%5E2)">.</li>
<li>It does not require discretization.</li>
<li>It is very stable to missing values in the evaluation set; even if whole areas are missing.</li>
<li>But: Is the pipeline as a whole now permutation equivariant? Well yes and no: The computations within each bag are permutation equivariant. But the whole pipeline is in theory not. But, the model learned via random bagging (as data augmentation) that it should behave in a permutation-equivariant way (which it does quite well, see Figure&nbsp;8 &amp; Figure&nbsp;10).</li>
</ul>


</section>

<div id="quarto-appendix" class="default"><section class="quarto-appendix-contents" id="quarto-citation"><h2 class="anchored quarto-appendix-heading">Citation</h2><div><div class="quarto-appendix-secondary-label">BibTeX citation:</div><pre class="sourceCode code-with-copy quarto-appendix-bibtex"><code class="sourceCode bibtex">@online{von_bornhaupt2026,
  author = {von Bornhaupt, Valentin},
  title = {Just {Shuffle:} {Linear-Time} {Set} {Segmentation} with
    {Transformer} {Encoders}},
  date = {2026-11-25},
  url = {https://vavobo.de/posts/monte_carlo_set_segmentation.html},
  langid = {en}
}
</code></pre><div class="quarto-appendix-secondary-label">For attribution, please cite this work as:</div><div id="ref-von_bornhaupt2026" class="csl-entry quarto-appendix-citeas">
Bornhaupt, Valentin von. 2026. <span>“Just Shuffle: Linear-Time Set
Segmentation with Transformer Encoders.”</span> November 25. <a href="https://vavobo.de/posts/monte_carlo_set_segmentation.html">https://vavobo.de/posts/monte_carlo_set_segmentation.html</a>.
</div></div></section></div> ]]></description>
  <guid>https://vavobo.de/posts/monte_carlo_set_segmentation.html</guid>
  <pubDate>Tue, 24 Nov 2026 23:00:00 GMT</pubDate>
</item>
</channel>
</rss>
