<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Archive Fever - Blog</title>
        <link>https://www.edwinwenink.xyz/posts/</link>
        <description>Recent posts on Archive Fever</description>
        <language>en</language>
        <lastBuildDate>Wed, 02 Dec 2026 21:18:32 +0000</lastBuildDate>
        <atom:link href="https://www.edwinwenink.xyz/posts/index.xml" rel="self" type="application/rss+xml"/>
        
        <item>
            <title>Idiot&#39;s guide to resource migration in Terraform</title>
            <link>https://www.edwinwenink.xyz/posts/73-terraform_migration_guide/</link>
            <guid>https://www.edwinwenink.xyz/posts/73-terraform_migration_guide/</guid>
            <pubDate>Fri, 15 Mar 2024 12:21:46 +0100</pubDate>
            <description>&lt;p&gt;Sometimes we need to migrate resources that are managed in Terraform.
Terraform is a declarative language to manage cloud infrastructure from code, which allows you to reliably automate your deployments and put your infrastructure configuration under version control.
We call this Infrastructure as Code (IaC).&lt;/p&gt;
&lt;p&gt;When moving resources in your IaC, Terraform will by default delete the resource and re-create it at the new path.
In the best case this is relatively harmless, depending on whether some downtime is acceptable, but nevertheless wasted effort because we already know the recreated resource will be identical to the removed resource.
Worst case, we absolutely do not want to delete and recreate the resource, for example because it holds data (think: storage accounts, databases).
Another reason you do not want to recreate resources is if they use on system-assigned identities for connecting to other resources (role-based access that is tied to the lifecycle of the resource itself).
In that case, recreating the resource will likely break functionality.&lt;/p&gt;
&lt;p&gt;So how do we &lt;em&gt;properly&lt;/em&gt; migrate cloud resources managed by Terraform?
Properly means that Terraform will update its pointer to the remote resource and that the remote resource itself remains unaffected.
There are various scenarios in which you need to migrate Terraform resources:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A. Moving resource blocks within the same Terraform state, for example to a child module.&lt;/li&gt;
&lt;li&gt;B. Moving a resource block to another module altogether, for example because over time you have developed dependency cycles and refactoring is overdue.&lt;/li&gt;
&lt;li&gt;C. Removing a resource from Terraform management altogether without deleting the resource.&lt;/li&gt;
&lt;li&gt;D. Bring an existing resource under Terraform management without Terraform trying to create a resource that already exists&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Scenario A and B are the most interesting scenarios.
In particular scenario B is a superset of scenarios C and D, so they are discussed in one go.&lt;/p&gt;
&lt;h2&gt;Scenario A: moving resources within the same Terraform state&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Make the refactor in your IaC&lt;/li&gt;
&lt;li&gt;In a Terraform plan, observe which resources are deleted and then recreated at the new path&lt;/li&gt;
&lt;li&gt;For each resource, define a &lt;code&gt;moved&lt;/code&gt; block.&lt;/li&gt;
&lt;li&gt;You can do this in a separate file, or keep the &lt;code&gt;moved&lt;/code&gt; blocks next to the moved resource.&lt;/li&gt;
&lt;li&gt;Verify that in the final Terraform plan there are no creations and deletions. If there are in-place updates, verify that they are intended.&lt;/li&gt;
&lt;li&gt;For example, if you accidentally import the right resource but from the wrong subscription (for example your staging environment instead of your dev environment) this may show up as an in-place update, depending on if that particular field forces replacement for that given resource.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After moving, it is optional to keep the move statements around.
I tend to keep them around until everything has been working great for a while, because the &lt;code&gt;moved&lt;/code&gt; blocks are essentially an explicit history of how you manipulated the Terraform state.&lt;/p&gt;
&lt;h2&gt;Scenario B: moving a resource to another Terraform state&lt;/h2&gt;
&lt;p&gt;This scenario is a lot more tricky!
This is because a failure to correctly remove blocks from the Terraform state will &lt;em&gt;trigger deletion&lt;/em&gt; of those resources.&lt;/p&gt;
&lt;p&gt;Always carefully inspect your plans before applying anything.&lt;/p&gt;
&lt;p&gt;In this example, we will move one resource from module A to module B.
Module A and B each have their own backend and Terraform state.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Remove the resource from the IaC of module A&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Record this removal with a &lt;code&gt;removed&lt;/code&gt; block (available since Terraform 1.7+ )&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Prior to Terraform 1.7, this requires you to manually run &lt;code&gt;terraform state rm&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Include the resource in the IaC of module B&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;Record an &lt;code&gt;import&lt;/code&gt; block that maps the existing resource to the new location
block that maps the existing resource to the new location&lt;/li&gt;
&lt;li&gt;Ensure that the Terraform plan for &lt;em&gt;both modules&lt;/em&gt; do not include deletions and creations. Carefully inspect possible in-place updates and ensure they are innocent.&lt;ul&gt;
&lt;li&gt;An innocent example of an in-place update is capitalization in a resource group name if the resource name is case insensitive.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;What can go wrong?&lt;/h2&gt;
&lt;h3&gt;Importing without removing&lt;/h3&gt;
&lt;p&gt;A lot of extra complexity arises from the fact that during your refactor, your teammates will probably happily keep on working in another branch.
During the migration, it is absolutely necessary to communicate this with teammates and do not make any other infra changes in the same Terraform states in the meantime.&lt;/p&gt;
&lt;p&gt;We have to deploy module A first because it contains fundamental resources (such as networking: VNets, subnets, endpoints) that all subsequent modules depend on.
So the deployment order is: &lt;code&gt;A -&amp;gt; B&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Let&#39;s consider two scenarios.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Migrate a resource from A to B&lt;/li&gt;
&lt;li&gt;Migrate a resource from B to A&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Let&#39;s say you migrate a resource &lt;em&gt;from module A to B&lt;/em&gt;.
First you remove the resource block from the infrastructure as code.
If you forget to correctly remove the resource from the Terraform state with a &lt;code&gt;removed&lt;/code&gt; block in A, applying the Terraform plan will delete the resource and then re-create it at B.
In this case you have &lt;em&gt;de facto&lt;/em&gt; migrated, but if your resources contains data you have just messed up.&lt;/p&gt;
&lt;p&gt;Let&#39;s say you migrate a resource &lt;em&gt;from module B to A&lt;/em&gt;.
If you forget to make and inspect a Terraform plan for &lt;em&gt;all involved modules&lt;/em&gt; and find out too late that your &lt;code&gt;removed&lt;/code&gt; blocks from the Terraform state of B contain mistakes, you wil happily delete the resources that you have just imported in the state of A.
This scenario is even more nasty, because at the end of the pipeline you have not only possibly thrown away data or identities tied to that specific resources, but also end up without that resource altogether.
This requires manual intervention to fix.&lt;/p&gt;
&lt;h3&gt;Do not apply IaC from different branches&lt;/h3&gt;
&lt;p&gt;When you are migrating resources from a refactoring branch, it&#39;s very important to communicate with your teammates when the actual migration starts in order to ensure nobody manipulates the Terraform states from another branch with different IaC.&lt;/p&gt;
&lt;p&gt;Some important safeguards should be in place:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;main&lt;/code&gt; branch is the single source of truth, do not deploy any infrastructure (except for your dev environment) from other branches. Enforce this in your deployment pipelines.&lt;/li&gt;
&lt;li&gt;In staging and production environments, &lt;em&gt;nobody&lt;/em&gt; should be able to manually deploy infrastructure using a &lt;code&gt;terraform apply&lt;/code&gt;, but nevertheless you may have forgotten to deactivate an older deployment pipeline that &lt;em&gt;can&lt;/em&gt; apply changes and may automatically trigger. If the previous safeguard is in place you should nevertheless only be able to deploy from the main branch.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If these guardrails are in place, you can only mess up on the development environment.
For the sake of argument, let&#39;s think through what happens if multiple people apply different IaC on the development environment.&lt;/p&gt;
&lt;figure style=&#34;width: 50%; margin-left: 20px; margin-bottom: 10px; float: right;&#34;&gt;
&lt;img src=&#34;https://upload.wikimedia.org/wikipedia/en/d/db/Hank_Schrader_S5B.png&#34; alt=&#34;Hank&#34; /&gt;
&lt;figcaption&gt;Hank, looking worried&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;This is Hank.
Hank was living the good life and followed this migration guide.
In the &lt;code&gt;A -&amp;gt; B&lt;/code&gt; scenario he is doing a dry run of his migration by applying the infra changes on the development environment before merging his IaC to the main branch and committing to the whole migration.&lt;/p&gt;
&lt;p&gt;But now he found out that someone he thought he knew well is not who he seemed to be.
That persons is applying old IaC to the development environment and on top of that, is &lt;em&gt;breaking bad&lt;/em&gt; completely because they didn&#39;t even check the Terraform plan before applying.
Now Hank is worried and wondering why his database disappeared on dev.&lt;/p&gt;
&lt;p&gt;What happened?&lt;/p&gt;
&lt;p&gt;Hank migrated a database from Terraform state B to state A on his development branch.
During his testing run on dev, he rolled out these changes.
Our bad guy rolls out the old IaC from another branch.
Terraform notices that there is a database in state A that is not in the IaC, so will happily generate a plan to throw away the database.&lt;/p&gt;
&lt;p&gt;An optional guardrail is to use &lt;code&gt;data&lt;/code&gt; blocks for resources that actually contain data, such as databases or critical storage accounts.
It depends really on whether you want to live dangerously or not:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;For believe me: the secret for harvesting from existence the greatest fruitfulness and greatest enjoyment is —- to live dangerously. - Friedrich Nietzsche&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Disaster recovery&lt;/h2&gt;
&lt;p&gt;Before doing a migration, make a backup of your terraform states.
You can use &lt;code&gt;terraform state pull&lt;/code&gt; for this.&lt;/p&gt;
&lt;p&gt;What do you do when things go wrong anyways?
At this point, you have to accept shit is FUBAR and that you have to make manual interventions without making further mistakes under stress.&lt;/p&gt;
&lt;p&gt;Honestly, this is context dependent, but it&#39;s not as simple as just reverting the IaC changes and restoring the old Terraform state (you could use &lt;code&gt;terraform state push&lt;/code&gt;, which has some safeguards built-in).
If things went bad, your infrastructure has probably changed so your old Terraform states are outdated.
If it&#39;s possible to recover deleted or changed infrastructure (e.g. if you have soft deletes and recovery procedures) to exactly match the old IaC, you could try to revert IaC changes and restore the old state to reach a point where you end up with a neutral Terraform plan.
The downside? Not only have you possibly thrown away data, you are back to square one with the migration.&lt;/p&gt;
&lt;p&gt;Instead, I&#39;d personally adopt a &#34;fix forward&#34; strategy: accept you messed up, make sure all resources are rolled out like they were supposed to, and make ad-hoc changes to the Terraform states using imports and removals.&lt;/p&gt;
&lt;h2&gt;Some Terraform gotchas (as of March 2024)&lt;/h2&gt;
&lt;p&gt;To conclude, some gotchas I encountered during a migration I performed recently.&lt;/p&gt;
&lt;p&gt;Import blocks still do not support the &lt;code&gt;count&lt;/code&gt; keyword, but since recently they do support &lt;code&gt;for_each&lt;/code&gt;.
Resources created with a count parameter are &lt;em&gt;indexed&lt;/em&gt; with an integer value, like &lt;code&gt;azurerm_storage_account.storage_account[0]&lt;/code&gt;.
This index &lt;em&gt;must&lt;/em&gt; be numerical and cannot be a string.
If you have a high count (let&#39;s say 100) or the amount of resources is non-static because it depends on a variable that&#39;s different for each deployment environment, you do not want to manually type 100 import blocks.
What you want to do instead is create a list or mapping that you can pass to &lt;code&gt;for_each&lt;/code&gt; such that you can create a numerical range.
You can pass a list to &lt;code&gt;for_each&lt;/code&gt;, but this will implicitly create a map with identical keys and values.
Be careful with Terraform map objects, because the &lt;em&gt;key is always a string&lt;/em&gt; even if you try to cast it to a number.
You will end up with &lt;code&gt;azurerm_storage_account.storage_account[&#34;0&#34;]&lt;/code&gt; and this will not work for obvious reasons.
Instead, just use the &lt;code&gt;range&lt;/code&gt; function and use &lt;code&gt;each.value&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Also don&#39;t forget to update to the latest Terraform version, because the  &lt;code&gt;for_each&lt;/code&gt; argument to &lt;code&gt;import&lt;/code&gt; and &lt;code&gt;removed&lt;/code&gt; blocks are only available since 1.7.&lt;/p&gt;
&lt;p&gt;Related notes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://www.edwinwenink.xyz/202403130820-terraform_migration_guide.html&#34;&gt;Terraform migration guide&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</description>
        </item>
        
        <item>
            <title>Self portraits using stable diffusion</title>
            <link>https://www.edwinwenink.xyz/posts/72-stable_diffusion_portraits/</link>
            <guid>https://www.edwinwenink.xyz/posts/72-stable_diffusion_portraits/</guid>
            <pubDate>Sat, 09 Sep 2023 16:21:46 +0100</pubDate>
            <description>&lt;p&gt;I was in need of a head shot, but I don&#39;t like taking pictures.
Being a programmer I figured, why not let AI magically turn a messy selfie into a proper professional head shot?
As it turns out, there&#39;s quite a market for AI tools that generate professional portraits that are suitable for LinkedIn and such, but they were requesting fees I wasn&#39;t willing to pay.
I hoped to do some experiments on a Midjourney trial license instead, but they discontinued those.
&lt;em&gt;No problemo&lt;/em&gt;, this is how this post was conceived: let&#39;s see how far we get with a pretrained &lt;em&gt;stable diffusion&lt;/em&gt; model without further fine-tuning on my face.&lt;/p&gt;
&lt;p&gt;I used &lt;a href=&#34;https://huggingface.co/CompVis/stable-diffusion&#34;&gt;CompVis/stable-diffusion-v1-4&lt;/a&gt;, which was initially trained on 256x256 images from &lt;a href=&#34;https://laion.ai/blog/laion-aesthetics/&#34;&gt;laion-aesthetic&lt;/a&gt; data sets and further fine-tuned on 512x512 images.
This is a text-to-image model trained to generate images based on a text prompt describing the scene, but it&#39;s also possible to initialize the inference process with a reference picture.
It&#39;s possible to tweak the relative strength of the reference image and the &#34;hallucination&#34; of the model based on the prompt.
I played around with two selfies that I cropped to a 1:1 ratio and then resized to 512x512.
The first reference picture was a selfie with my &lt;em&gt;huge&lt;/em&gt; Monstera in the background.
The &#34;head and shoulders&#34; setup is also quite common for portraits so I expected this layout to be well represented in the training data.&lt;/p&gt;
&lt;figure style=&#34;width: 50%; margin-left: 20px; margin-bottom: 10px; float: right;&#34;&gt;
&lt;img src=&#34;https://www.edwinwenink.xyz/images/diffusion/not_quite_edwin.jpg&#34; alt=&#34;Dreams of Edwin.&#34; /&gt;
&lt;figcaption&gt;Dreams of Edwin.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;It&#39;s not hard to generate stunning pictures if you let the model hallucinate.
The top two pictures are very loosely inspired by the reference picture (the green from the Monstera subtly returns in the background; heavy mustache) but don&#39;t look like me at all.
The next two pictures attribute more importance to the reference picture and stay close to the original layout of the scene and main characteristics of my face (mainly my hair and beard style), but other than that didn&#39;t look like me at all.
My main observation at this point is that ...&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;trying to stay close to a reference portrait without fine-tuning on the subject is a one-way ticket to the &lt;em&gt;uncanny valley&lt;/em&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I was initially sceptical, but by now I&#39;m convinced that using generative AI in this manner to create a specific picture you have in mind truly is a creative process.
It is similar to how a professional photographer sets up the environment for the right snapshot: the art is not in the pressing of the button, but on using the tools available to materialize something that only existed in your mind&#39;s eye so far.
Similarly, prompt engineering is an art in the sense that over time you start to get a feeling for which prompts are successful for manipulating this stochastic &#34;obscene hallucination machine&#34; in a desired direction.&lt;/p&gt;
&lt;figure style=&#34;width: 50%; margin-left: 20px; margin-bottom: 10px; float: right;&#34;&gt;
&lt;img src=&#34;https://www.edwinwenink.xyz/images/diffusion/edwin_alphone_mucha.jpg&#34; alt=&#34;Edwin interpreted in jugendstil à la Alphone Mucha.&#34; /&gt;
&lt;figcaption&gt;Edwin interpreted in jugendstil à la Alphone Mucha.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;figure style=&#34;width: 50%; margin-left: 20px; margin-bottom: 10px; float: right;&#34;&gt;
&lt;img src=&#34;https://www.edwinwenink.xyz/images/diffusion/edwin_and_vincent.jpg&#34; alt=&#34;Edwin and Vincent.&#34; /&gt;
&lt;figcaption&gt;Edwin and Vincent.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Only after including the names of painters and artists I started seeing results that I liked.
For example, I added jugendstil artist Alphone Mucha to the prompt.
These results are obviously not &#34;realistic,&#34; but in for example the top left picture I started recognizing a bit of myself in the glance of the eyes.
The style worked really well with the Monstera in the background.&lt;/p&gt;
&lt;p&gt;I tend to be compared to Vincent van Gogh and you can probably see why in the final results.
These are based on a different picture that I sent to my better half when I was, quite frankly, done with my day.
When I threw Vincent van Gogh and Edvard Munch in the mix, I finally managed to produce a stylized version of a picture that actually looked like me.
Lo and behold, the top left picture is a stylized and &#34;painted&#34; version of what I actually look like.
Everyone that knows me will immediately recognize me in this picture.&lt;/p&gt;
&lt;p&gt;To achieve the goal of getting a professional looking head shot, the next step is to finetune a stable diffusion model on pictures of my own face.
This should make it possible to let the model do its magic on the background and the styling, but stay closer to my actual face.&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>My Vinyl Record Collection</title>
            <link>https://www.edwinwenink.xyz/posts/70-my_vinyl_record_collection/</link>
            <guid>https://www.edwinwenink.xyz/posts/70-my_vinyl_record_collection/</guid>
            <pubDate>Tue, 29 Aug 2023 12:03:02 +0200</pubDate>
            <description>&lt;figure style=&#34;width: 50%; margin-left: 20px; margin-bottom: 10px; float: right;&#34;&gt;
&lt;img src=&#34;https://thevinylwall.com/cdn/shop/files/head_alternate_edit.jpg?v=1613523692&#34; alt=&#34;Vinyl wall mount&#34; /&gt;
&lt;figcaption&gt;&lt;a href=&#34;https://thevinylwall.com/&#34;&gt;Analog example&lt;/a&gt;&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;I added a digital &lt;a href=&#34;https://www.edwinwenink.xyz/records/&#34;&gt;vinyl record display&lt;/a&gt; to this website, have a look!&lt;/p&gt;
&lt;p&gt;The idea was to digitally reproduce one of those fancy wall mounts for displaying records in your room.
You can click on each record to see some basic information.&lt;/p&gt;
&lt;p&gt;All vinyl records I physically own are registered on &lt;a href=&#34;https://www.discogs.com/&#34;&gt;Discogs&lt;/a&gt;.
I used the Discogs API to automatically retrieve my collection, parse the information I want, and store all results in Markdown files that can be consumed on this website.&lt;/p&gt;
&lt;p&gt;If you like what you see, I &lt;a href=&#34;https://github.com/EdwinWenink/discogs_vinyl_record_display&#34;&gt;open sourced my code&lt;/a&gt; to reproduce these results so you can make your own digital wall too.
The project&#39;s README explains how to run the project using your own Discogs collection.
The only thing you need is a Discogs user name, Python, and optionally an authentication token to get links to cover images.
Also note that Discogs throttles requests per minute, so check out my tip on deployment too.&lt;/p&gt;
&lt;p&gt;If you like this project, give it a star on Github and share a link to your digital record collection.
I&#39;d love to see it!&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>Version control on notebooks using pre-commit and Jupytext</title>
            <link>https://www.edwinwenink.xyz/posts/71-version_control_on_notebooks_with_precommit_and_jupytext/</link>
            <guid>https://www.edwinwenink.xyz/posts/71-version_control_on_notebooks_with_precommit_and_jupytext/</guid>
            <pubDate>Sun, 29 Jan 2023 16:21:46 +0100</pubDate>
            <description>&lt;p&gt;Notebooks have a place and a time.
They are suitable for sharing the insights of an exploratory data analysis, but not so convenient for collaborating with multiple people whilst having the notebook code under version control.
Generally speaking notebooks do not promote good coding habits, for example because people tend to duplicate code by copying cells.
People typically also don&#39;t use supportive tooling such as code linters and type checkers.
But one of the most nasty problems with notebooks is that version control is hard, for several reasons.
Running a diff on notebooks simply sucks.
The piece of text we care about when reviewing - the code - is hidden in a JSON-style data structure that is interleaved with base-64 encoded blobs for images or binary cell outputs.
Particularly these blobs will clutter up your diffs and make it very hard to review code.
So how can we use notebooks with standard versioning tools such as Git?
This post explains an automated workflow for good version control on Jupyter and Jupyter Lab notebooks using Git, the pre-commit framework, and Jupytext.
The final pre-commit configuration can be found &lt;a href=&#39;#putting-it-all-together&#39;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Which type of notebooks need a version control workflow?&lt;/h2&gt;
&lt;p&gt;But let&#39;s first take a step back.
Whether we actually need version control depends on what the purpose of the notebook is.
We can roughly distinguish two types of notebooks.&lt;/p&gt;
&lt;p&gt;Firstly, we have exploratory notebooks that can be used for experimentation, early development, and exploration.
This type of notebook should be treated as a historical and dated (possibly outdated!) record of some analysis that provided insights at some moment in a project.
In this sense the notebook code does not have to be up to date with the latest changes.
For this type of &#34;lab&#34; notebook, most difficulties concerning version control can be avoided by following these recommendations:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Exploratory notebooks should have a &lt;em&gt;single&lt;/em&gt; author who is the owner of the analysis&lt;/li&gt;
&lt;li&gt;A minimal version control approach is possible: others do not push changes in that notebook, unless explicitly coordinated with the owner of the notebook.&lt;/li&gt;
&lt;li&gt;This should avoid having to review unreadable diffs&lt;/li&gt;
&lt;li&gt;And also avoid merge conflicts altogether&lt;/li&gt;
&lt;li&gt;Mention the &lt;em&gt;date&lt;/em&gt; and the &lt;em&gt;author name&lt;/em&gt; of the analysis in the file name to make the historical character and owner explicit&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Secondly, in some workflows one may want to collaborate with multiple people on the same notebook or even have notebooks in production (looking at you, Databricks).
In these cases, notebooks store the most up-to-date and polished up output of some analysis that can be presented to stakeholders.
But the most notable difference is that this type of notebook is the responsibility of the &lt;em&gt;whole&lt;/em&gt; data science team.
As a result, the notebook workflow should support more advanced version control, such as the code review process via pull requests and handling merge conflicts.
The rest of this post explains such a workflow.&lt;/p&gt;
&lt;h2&gt;General recommendations&lt;/h2&gt;
&lt;p&gt;To start, I make these general recommendations for all notebooks that are committed to a Git repository:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Clear all cell outputs before committing a notebook to the repository&lt;ul&gt;
&lt;li&gt;This avoids cluttering Git diffs with anything other than code, although this will not prevent changes in metadata to be pushed.&lt;/li&gt;
&lt;li&gt;If notebook output has to be put under version control, convert the notebook to html (using &#34;save as&#34; or &lt;code&gt;nbconvert&lt;/code&gt;) and commit the html instead.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Store notebooks apart from the main source code of a project. I personally use a dedicated &lt;code&gt;notebooks&lt;/code&gt; folder.&lt;ul&gt;
&lt;li&gt;This also allows you to more easily trigger a separate workflow for notebooks (see below).&lt;/li&gt;
&lt;li&gt;This keeps the main source code of a project uncluttered with dated notebooks.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Motivation of the chose workflow&lt;/h2&gt;
&lt;p&gt;The core idea of this workflow is to &lt;em&gt;convert&lt;/em&gt; notebooks to regular scripts and use these to create meaningful diffs for reviewing.
This basic workflow &lt;em&gt;could&lt;/em&gt; work something like this:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;When you need to diff a notebook, export to Python using &lt;code&gt;jupyter nbconvert&lt;/code&gt; and diff the Python file instead.&lt;/li&gt;
&lt;li&gt;When you need output, use &lt;code&gt;nbconvert&lt;/code&gt; to execute the notebook and convert the output to html&lt;/li&gt;
&lt;li&gt;Before committing a notebook, clear the outputs to minimize unreadable blobs&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;To convert to HTML: &lt;code&gt;jupyter nbconvert /notebooks/example.ipnb --output-dir=&#34;/results&#34; --output=&#34;example.html&#34;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;To convert to Python: &lt;code&gt;jupyter nbconvert /notebooks/example.ipnb --to=&#34;python&#34; --output-dir=&#34;/results&#34; --output=&#34;example&#34;&lt;/code&gt; or the newer syntax &lt;code&gt;jupyter nbconvert --to script notebook.ipynb&lt;/code&gt;.
Notice the absence of the &lt;code&gt;.py&lt;/code&gt; extension if you specify a &lt;code&gt;to&lt;/code&gt; argument.
Multiple notebooks can be converted using a wildcard.&lt;/p&gt;
&lt;p&gt;If you want to have executed notebooks in your production environment, you can 1) commit the Python version of the notebook and 2) execute the notebook with a call to &lt;code&gt;nbconvert&lt;/code&gt; in a pipeline, such as Github Actions (&lt;a href=&#34;https://github.com/dliden-bitdotio/bls-notebook&#34;&gt;example GitHub Actions workflow&lt;/a&gt;).
This allows you to execute a notebook without opening the notebook in your browser.
You execute a notebook with cleared outputs as such:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;jupyter nbconvert --to notebook --execute notebook_cleared.ipynb --output notebook_executed&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;However, a downside of &lt;code&gt;nbconvert&lt;/code&gt; is that the conversion is uni-directional from notebook to script, so one cannot reconstruct the notebook after making changes in the generated script.
In other words, the corresponding script would be used strictly for reviewing purposes, but the notebook would stay the single source of truth.
The &lt;code&gt;jupytext&lt;/code&gt; tool solves this problem by doing a bi-directional synchronization between a notebook and its corresponding script.&lt;/p&gt;
&lt;p&gt;We should also note that this workflow requires several &lt;em&gt;manual&lt;/em&gt; steps that can be easily forgotten and messed up.
It is possible to write post-save Jupyter hooks to automate these steps, but a limitation is that such a configuration would be user-specific.
It is also possible to use Git hooks, but these are project-specific and would require all team members to copy in the correct scripts in a project&#39;s &lt;code&gt;.git&lt;/code&gt; folder.
Instead, we&#39;d like to describe a workflow that can be installed in a new project in a uniform manner, such that each team member is guaranteed to use the same workflow.
We&#39;ll use the multi-language &lt;code&gt;pre-commit&lt;/code&gt; framework to install a &lt;code&gt;jupytext&lt;/code&gt; synchronization hook.&lt;/p&gt;
&lt;h2&gt;What is Jupytext?&lt;/h2&gt;
&lt;p&gt;Jupytext is a tool for two-way synchronization between a Jupyter notebook and a paired script in &lt;a href=&#34;https://jupytext.readthedocs.io/en/latest/languages.html&#34;&gt;many languages&lt;/a&gt;.
In this post we only consider the &lt;code&gt;.ipynb&lt;/code&gt; and &lt;code&gt;.py&lt;/code&gt; extensions.
It can be used as a standalone command line tool or as a plugin for Jupyter Notebooks or Jupyter Lab.
To save information on notebook cells Jupytext either uses a minimalistic &#34;light&#34; encoding or a &#34;percent&#34; encoding (the default).
We will use the percent encoding.
The following subsections are applicable only if you want to be able to use Jupytext as a standalone tool.
If not, skip ahead to &lt;a href=&#34;combining-jupytext-with-pre-commit&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Installation and pairing&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Install as standalone command using pip&lt;/li&gt;
&lt;li&gt;&lt;code&gt;pip install jupytext --upgrade&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Handy! Can be included in requirements.txt&lt;/li&gt;
&lt;li&gt;Install as Jupyter notebook extension&lt;/li&gt;
&lt;li&gt;&lt;code&gt;jupyter nbextension install --py jupytext [--user]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Follow by: &lt;code&gt;jupyter nbextension enable --py jupytext [--user]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Notebook: File -&amp;gt; Jupytext -&amp;gt; Pair Notebook with light (fewer markers) or percent (explicit cell delimiters) script&lt;/li&gt;
&lt;li&gt;If you now save the notebook, a corresponding .py version will be updated automatically!&lt;/li&gt;
&lt;li&gt;Install as Jupyter lab extension&lt;/li&gt;
&lt;li&gt;&lt;code&gt;jupyter labextension install jupyterlab-jupytext&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Lab: View -&amp;gt; Activate Command Palette (Ctrl+Shift+C) -&amp;gt; Pair Notebook with ...&lt;/li&gt;
&lt;li&gt;If you now save the notebook, a corresponding .py version will be updated automatically!&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Basic usage&lt;/h3&gt;
&lt;p&gt;When you save a paired notebook in Jupyter, both the &lt;code&gt;.ipynb&lt;/code&gt; file and the script version are updated on disk.&lt;/p&gt;
&lt;p&gt;On the command line, you can update paired notebooks using &lt;code&gt;jupytext --sync notebook.ipynb&lt;/code&gt; or &lt;code&gt;jupytext --sync notebook.py&lt;/code&gt;.
If you run this on a new script, Jupytext will encode the script and define cells using some basic rules (e.g. delimited by newlines), then convert it to a paired notebook.&lt;/p&gt;
&lt;p&gt;When a paired notebook is opened or reloaded in Jupyter, the input cells are loaded from the text file, and combined with the output cells from the &lt;code&gt;.ipynb&lt;/code&gt; file.
This also means that when you edit the &lt;code&gt;.py&lt;/code&gt; file, you can update the notebook simply by &lt;em&gt;reloading&lt;/em&gt; it.&lt;/p&gt;
&lt;p&gt;You can specify a project specific configuration in &lt;code&gt;jupytext.toml&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;formats = &amp;quot;ipnb,py:percent&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To convert a notebook to a notebook &lt;em&gt;without outputs&lt;/em&gt;, use &lt;code&gt;jupytext --to notebook notebook.py&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;Combining Jupytext with pre-commit&lt;/h2&gt;
&lt;p&gt;Okay, so Jupytext handles the two-way synchronization between scripts and outputs, which is an improvement compared to Jupyter&#39;s native &lt;code&gt;nbconvert&lt;/code&gt; command.
The basic idea is still that when you want notebook code reviewed, collaborators can instead read and comment on the paired script.
It is now also possible to incorporate the feedback directly in the script if we wish to do so, because the notebook will be updated accordingly.&lt;/p&gt;
&lt;p&gt;Our broader goal was to completely remove any need for manual steps.
We will automate the synchronization step using a pre-commit hook, which means that we check the synchronization status before allowing work to be committed.
This is a safeguard to avoid to avoid that out of sync notebooks and scripts are committed.&lt;/p&gt;
&lt;p&gt;Git hooks are very handy, but they go in &lt;code&gt;.git/hooks&lt;/code&gt; and are therefore not easily shared across projects.
The &lt;code&gt;pre-commit&lt;/code&gt; package is designed as a multi-language package manager for pre-commit hooks and can be installed using pip: &lt;code&gt;pip install pre-commit&lt;/code&gt;.
It allows you to specify pre-commit hooks in a declarative style and also manages dependencies, so if we declare a hook that uses Jupytext we do not even have to manually install Jupytext.
We declare the hooks in a configuration file.
We also automate the &#34;clear output cells&#34; step mentioned above using &lt;code&gt;nbstripout&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;My &lt;code&gt;.pre-commit-config.yaml&lt;/code&gt; for syncing notebooks and their script version looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-yaml&#34;&gt;repos:
-   repo: https://github.com/kynan/nbstripout
    rev: 0.6.1
    hooks:
    -   id: nbstripout
-   repo: https://github.com/mwouts/jupytext
    rev: v1.14.1
    hooks:
      - id: jupytext
        name: jupytext
        description: Runs jupytext on all notebooks and paired files
        language: python
        entry: jupytext --pre-commit-mode --set-formats &amp;quot;ipynb,py:percent&amp;quot;
        require_serial: true
        types_or: [jupyter, python]
        files: ^notebooks/  # Only apply this under notebooks/
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After setting up a config, you have to &lt;em&gt;install&lt;/em&gt; the hook as a git hook: &lt;code&gt;pre-commit install&lt;/code&gt;.
This clones Jupytext and sets up the git hook using it.
Now the defined commit wil run when you &lt;code&gt;git commit&lt;/code&gt; and you have defined the hook in a language agnostic way!
In this configuration, you manually specify the &lt;code&gt;rev&lt;/code&gt; which is the tag of the specifiek &lt;code&gt;repo&lt;/code&gt; to clone from.
You can test if the hook runs by running it on a specific file or on all files with &lt;code&gt;pre-commit run --all-files&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;Explanation and possible issues&lt;/h3&gt;
&lt;p&gt;There are some important details when using Jupytext as a pre-commit hook.
The first &lt;em&gt;gotcha&lt;/em&gt; is that when checking whether paired notebooks and scripts are in sync, it actually runs Jupytext and synchronizes paired scripts and notebooks.
If the paired notebooks and scripts were out of sync, running the hook will thus &lt;em&gt;introduce unstaged changes&lt;/em&gt;!
These unstaged changes also need to be committed in Git before the hook passes and it is recognized that the files are in sync.&lt;/p&gt;
&lt;p&gt;The second gotcha is that the &lt;code&gt;--pre-commit-mode&lt;/code&gt; flag is important to avoid a subtle but very nasty loop.
The standard behavior of &lt;code&gt;jupytext --sync&lt;/code&gt; is to see which two of the paired files (notebook or script) was most recently edited and has to be taken as the ground truth for the two way synchronization.
This is problematic because this causes a loop when used in the pre-commit framework.
For example, let&#39;s say that we have a paired notebook and script and that we edit the script.
When we commit the changes in the script, the pre-commit hook will first run Jupytext.
In this case the script is the &#34;source of truth&#34; for the synchronization such that the notebook needs to be updated.
The Jupytext pre-commit hook check will fail because we now have unstaged changed in the updated notebook that we need to commit to Git.
When we commit the changes in the updated notebook, however, the notebook becomes the most recently edited file, such that Jupytext complains that it is now unclear whether the notebook or the script is the source of truth.&lt;/p&gt;
&lt;p&gt;The good news is that Jupytext is smart enough to raise an error and requires you to manually specify which changes to keep.
The bad news is that in this specific case, this manual action does not prevent the loop: we&#39;re in a Catch 22 of sorts!
The &lt;code&gt;--pre-commit-mode&lt;/code&gt; fixes this nasty issue by making sure that Jupytext does not always consider the most recently edited file as the ground truth.&lt;/p&gt;
&lt;p&gt;Within the pre-commit framework you almost certainly also want to specify other hooks.
For example, I want to make sure my code is &lt;code&gt;PEP8&lt;/code&gt; compliant by running &lt;code&gt;flake8&lt;/code&gt; or some other linter on the changes that are to be committed.
The pre-commit framework itself also offers hooks for fixing common code issues such as trailing whitespaces or left-over merge conflict markers.
But this is where I&#39;ve encountered another nasty issue that prevented the Jupytext hook from correctly syncing.&lt;/p&gt;
&lt;p&gt;Let&#39;s take a hook that removes trailing white spaces as an example.
This hook works as intended on Python scripts, but the hook does not actually remove trailing white spaces &lt;em&gt;in the code&lt;/em&gt; because source code of notebook cells are encapsulated in a JSON field as follows:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-json&#34;&gt;{
 &amp;quot;cell_type&amp;quot;: &amp;quot;code&amp;quot;,
 &amp;quot;execution_count&amp;quot;: null,
 &amp;quot;id&amp;quot;: &amp;quot;361b20cc&amp;quot;,
 &amp;quot;metadata&amp;quot;: {
  &amp;quot;gather&amp;quot;: {
   &amp;quot;logged&amp;quot;: 1671533986727
  },
  &amp;quot;jupyter&amp;quot;: {
   &amp;quot;outputs_hidden&amp;quot;: false,
   &amp;quot;source_hidden&amp;quot;: false
  },
  &amp;quot;nteract&amp;quot;: {
   &amp;quot;transient&amp;quot;: {
    &amp;quot;deleting&amp;quot;: false
   }
  }
 },
 &amp;quot;outputs&amp;quot;: [],
 &amp;quot;source&amp;quot;: [
  &amp;quot;#### pre-processing\n&amp;quot;,
  &amp;quot;from src.preprocessing import preprocess_and_split\n&amp;quot;,
  &amp;quot;\n&amp;quot;,
  &amp;quot;df_indirect, df_direct, df_total = preprocess_and_split(df)&amp;quot;
 ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This means that if you commit a notebook with trailing white spaces in the cells, the following happens and will prevent the paired notebook and script from ever syncing:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The Jupytext hook synchronizes the notebook with a paired Python script.&lt;/li&gt;
&lt;li&gt;Trailing whitespaces are removed from the Python script and the &lt;em&gt;plain text&lt;/em&gt; representation of the notebook (i.e. it removes trailing white space after the closing brackets)&lt;/li&gt;
&lt;li&gt;When translating the notebook to code or vice versa, one version still includes trailing white spaces in the code cells and the other not.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is something to be wary of and needs to be solved on a case to case basis.
I have solved this specific issue by adding all notebooks in the &lt;code&gt;notebooks&lt;/code&gt; folder as per my recommendation and then not running the trailing whitespace hook in the &lt;code&gt;notebooks&lt;/code&gt; folder.&lt;/p&gt;
&lt;h2&gt;Putting it all together&lt;/h2&gt;
&lt;p&gt;The following is a &lt;code&gt;.pre-commit-config.yaml&lt;/code&gt; that synchronizes all notebooks with Python scripts under &lt;code&gt;notebooks&lt;/code&gt; and plays nice with other pre-commit hooks:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-yaml&#34;&gt;# Install the pre-commit hooks below with
# &#39;pre-commit install&#39;

# Run the hooks on all files with
# &#39;pre-commit run --all&#39;

repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    # See: https://pre-commit.com/hooks.html
    hooks:
    -   id: trailing-whitespace
        types: [python]
        exclude: ^notebooks/  # Avoids Jupytext sync problems
    -   id: end-of-file-fixer
    -   id: check-merge-conflict
    -   id: check-added-large-files
        args: [&#39;--maxkb=5000&#39;]
    -   id: end-of-file-fixer
    -   id: mixed-line-ending
    # Run flake8. Give warnings, but do not reject commits
-   repo: https://github.com/PyCQA/flake8
    rev: 6.0.0
    hooks:
    -   id: flake8
        args: [--exit-zero]  # Do not reject commit because of linting
        verbose: true
    # Enforce that notebooks outputs are cleared
-   repo: https://github.com/kynan/nbstripout
    rev: 0.6.1
    hooks:
    -   id: nbstripout
    # Synchronize notebooks and paired script versions
-   repo: https://github.com/mwouts/jupytext
    rev: v1.14.1
    hooks:
      - id: jupytext
        name: jupytext
        description: Runs jupytext on all notebooks and paired files
        language: python
        entry: jupytext --pre-commit-mode --set-formats &amp;quot;ipynb,py:percent&amp;quot;
        require_serial: true
        types_or: [jupyter, python]
        files: ^notebooks/  # Only apply this under notebooks/
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The final workflow for version control on notebooks is as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Install Git pre-commit hooks in your project based on the declarative config using &lt;code&gt;pre-commit install&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Save notebooks under the &lt;code&gt;notebooks&lt;/code&gt; folder&lt;/li&gt;
&lt;li&gt;Work on your Jupyter notebooks as usual&lt;/li&gt;
&lt;li&gt;Commit your work. This triggers the pre-commit hook&lt;/li&gt;
&lt;li&gt;If the pre-commit hook fails and introduces new changes, commit those changes too for the hook checks to pass&lt;/li&gt;
&lt;li&gt;Now all checks should pass and you are free to commit and push!&lt;/li&gt;
&lt;li&gt;When you make a PR, collaborators can now provide comments on the paired script&lt;/li&gt;
&lt;li&gt;Feedback can be incorporated either in the notebook or the script since they are synchronized anyways&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here we have assumed you have created and specified &lt;code&gt;.pre-commit-config.yaml&lt;/code&gt; and &lt;code&gt;jupytext.toml&lt;/code&gt; in your project root.&lt;/p&gt;
&lt;h2&gt;Further reading&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://jupytext.readthedocs.io/en/latest/index.html&#34;&gt;Jupytext docs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://jupytext.readthedocs.io/en/latest/examples.html&#34;&gt;Jupytext docs on collaborating on notebooks&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;There are some notebook aware tools for diffing and merging&lt;/li&gt;
&lt;li&gt;E.g. &lt;code&gt;nbdiff&lt;/code&gt; and &lt;code&gt;nbmerge&lt;/code&gt; commands from &lt;a href=&#34;https://nbdime.readthedocs.io/en/latest/&#34;&gt;nbdime&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;ReviewNB GitHub app&lt;/li&gt;
&lt;li&gt;Neptune&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://www.svds.com/jupyter-notebook-best-practices-for-data-science/&#34;&gt;https://www.svds.com/jupyter-notebook-best-practices-for-data-science/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;http://timstaley.co.uk/posts/making-git-and-jupyter-notebooks-play-nice/&#34;&gt;http://timstaley.co.uk/posts/making-git-and-jupyter-notebooks-play-nice/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://innerjoin.bit.io/automate-jupyter-notebooks-on-github-9d988ecf96a6&#34;&gt;https://innerjoin.bit.io/automate-jupyter-notebooks-on-github-9d988ecf96a6&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://nextjournal.com/schmudde/how-to-version-control-jupyter&#34;&gt;https://nextjournal.com/schmudde/how-to-version-control-jupyter&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</description>
        </item>
        
        <item>
            <title>Overgeven of Sneuvelen: De Atjeh-oorlog</title>
            <link>https://www.edwinwenink.xyz/posts/69-de_atjeh_oorlog/</link>
            <guid>https://www.edwinwenink.xyz/posts/69-de_atjeh_oorlog/</guid>
            <pubDate>Sun, 13 Nov 2022 12:03:02 +0100</pubDate>
            <description>&lt;blockquote&gt;
&lt;p&gt;In 1873 valt Nederland de zelfstandige staat Atjeh binnen, gelegen op de noordpunt van Sumatra.
De Nederlanders verwachten Atjeh snel te kunnen onderwerpen.
Dat blijkt een illusie te zijn.
Ze belanden in een oorlog die de langste en bloedigste uit de Nederlandse koloniale geschiedenis zal worden: de Atjeh-oorlog.&lt;br&gt;
&lt;br&gt;
&lt;em&gt;Overgeven of sneuvelen&lt;/em&gt; is de enige roman in de Nederlandse literatuur die de volledige Atjeh-oorlog beschrijft.
Ik vraag de auteur, Bert Wenink, wat hem heeft gedreven vijf jaar aan dit boek te werken.
Bestel het boek via &lt;a href=&#34;https://bertwenink.nl/bestellen&#34;&gt;zijn website&lt;/a&gt; of via &lt;a href=&#34;https://www.boekenbestellen.nl/boek/overgeven-of-sneuvelen/9789083254203&#34;&gt;boekenbestellen.nl&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;EW: Waarom heb je een boek over de Atjeh-oorlog geschreven?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;BW: Als ik het over de Atjeh-oorlog heb zie je mensen denken: wat voor een fascinatie heeft een witte man zonder Indische connecties, zonder voorvaderen die in de Oost hebben gevochten, met de Atjeh-oorlog? Mijn antwoord is dan: verwondering, sentiment en inbeelding.
Als kind logeerde ik regelmatig bij mijn oma.
Ze woonde in Arnhem, in een zijstraat van de Velperweg, dezelfde weg waaraan ook Bronbeek ligt, het museum van de Nederlandse geschiedenis in Indië en rusthuis voor veteranen die in het Koninklijk Nederlands Indisch Leger hadden gediend.
Daar zaten ze met goed weer in de tuin: de oude mannetjes in uniform met lange grijze baarden, de ex-KNILers.
Met die bijzondere, toen al anachronistische verschijning zijn waarschijnlijk de eerste zaadjes van fascinatie geplant.
Later bezocht ik met mijn vader het museum.
Ik kan me er weinig van herinneren, maar het moet indruk gemaakt hebben.
Het was nog de tijd van het tentoonstellen van exotische trofeeën, van krissen, speren en klewangs aan de muren en buitgemaakte kanonnen in de gangen.&lt;/p&gt;
&lt;!--![Kaart van Atjeh](/images/69/atjeh.png)--&gt;
&lt;figure&gt;
 &lt;img align=&#34;right&#34; alt=&#34;Kaart van Atjeh&#34; style=&#34;width:50%; margin-left: 20px&#34; src=&#34;https://www.edwinwenink.xyz/images/69/atjeh.png&#34; /&gt;
&lt;/figure&gt;

&lt;p&gt;Nog weer later, veel later, ben ik drijvend op die sentimenten zelf terug gegaan, en toen begon de verwondering.
Daar in Bronbeek hing in de gang aan de muur een fragment uit de Atjeh-oorlog, geschreven door een zekere Schoemaker, een echte nationalist is me later gebleken toen ik meer van hem las.
Iemand die kritiekloos de heldendaden van &#39;onze&#39; jongens ophemelde, maar wel gezegend met een uitstekende pen waarmee hij taferelen levensecht tevoorschijn toverde.
Ik wilde steeds meer weten van die exotische, verbijsterende wereld die de Atjeh-oorlog is.
Nieuwsgierigheid doet de rest.
Waarom wagen jonge mannen zich in de hel van Indië? Wat deed één van Nederlands grootste geleerden uit de 19e eeuw op het slagveld van Atjeh, in een tijd dat de meeste geleerden gewoon achter hun bureau bleven zitten? En waarom vochten inheemse soldaten, in dienst van het KNIL, zo fanatiek voor de Nederlanders, waarom stormden die het eerst tegen de wand van een benteng op met het risico ook als eerste te sneuvelen? Al die vragen, waarbij de antwoorden je van de ene in de andere verbazing doen belanden, waren de drijfveren om steeds meer over de oorlog te lezen en er een roman over te schrijven.
Het schrijven was een soort ouderwetse negentiende-eeuwse ontdekkingstocht.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;EW: Is het boek historisch verantwoord?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;BW: Overgeven of sneuvelen geeft een prima overzicht van de belangrijkste gebeurtenissen uit de Atjeh-oorlog.
Bij de historische personen heb ik mijn fantasie zo weinig mogelijk de ruimte gegeven.
Anders gezegd: ik laat Van Heutsz, Van Daalen, Sjech Saman di Tiro of Colijn geen verzonnen fratsen uithalen.
De echte romanpersonages hebben niet bestaan, maar hun belevenissen spelen zich af in een historische context en zouden echt zo gebeurd kunnen zijn.
Ik heb me zeer uitgebreid gedocumenteerd.
In mijn boek, en ook op mijn website, heb ik een lijst van ruim honderd geraadpleegde boeken en artikelen opgenomen.
Daarnaast heb ik een zeer uitvoerige correspondentie met een militair deskundige en Atjeh-kenner gevoerd.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;EW: Je hebt dus veel historisch onderzoek gedaan. Waarom heb je dan toch de vorm van een roman gekozen?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;BW: Dat heeft met inbeelding te maken, en natuurlijk met mijn achtergrond; ik ben neerlandicus.
Ik zou zelf niet graag meemaken wat de KNIL-soldaten moesten doorstaan, maar meeleven in de vorm van literatuur is veilig genoeg om jezelf onder te dompelen in die ongelofelijke wereld.
Ik wilde de hele Atjeh-oorlog beschrijven, en dan met name door de ogen van personages en er ook nog een spannend verhaal met een plot van  maken.
Een ambitieus plan.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;EW: Kunnen we tegenwoordig nog iets leren van de Atjeh-oorlog?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;BW: Hoe vecht je tegen een vijand waarbij burgers en strijders nauwelijks te onderscheiden zijn? Waar kan een overhaast ten strijde trekken toe leiden? Vragen die nog steeds actueel zijn.
Het Atjese verzet was, net zoals in veel tegenwoordige oorlogen, islamitisch geïnspireerd.
De strategische lessen uit de Atjeh-oorlog gelden onverminderd voor hedendaagse oorlogen.
En wat mij betreft wierp het geweld uit de Atjeh-oorlog zijn schaduwen vooruit op de koloniale strijd na de Tweede Wereldoorlog.
Ik zou bijna zeggen: de Atjeh-oorlog is gruwelijk actueel.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;EW: De koloniale geschiedenis van Nederland in Indonesië staat momenteel volop in de aandacht. Recent onderzoek bevestigde bijvoorbeeld dat Nederland na WOII excessief geweld heeft gebruikt tijdens de Indonesische Onafhankelijkheidsoorlog. Jouw roman laat wellicht zien dat dat niet zo&#39;n verrassing is gezien de gruwelijkheden van de Atjeh-oorlog.
Wat is jouw morele oordeel over de Atjeh-oorlog?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;BW: Verwondering en verbazing waren mijn drijfveren om steeds meer over de oorlog te lezen en er een roman over te schrijven.
Pas nadat ik &#39;m af had kwamen andere, meer rationele vragen.
Over de lessen die we van de Atjeh-oorlog kunnen leren, over de beschaving die de Nederlanders wilden brengen, over de morele aspecten.
Mijn blik was – denk ik – niet oordelend, eerder met een zekere compassie voor de militairen, maar zeker niet vergoelijkend.
De lezer trekt zelf wel zijn conclusies.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;EW: De roman neemt inderdaad geen stelling en biedt de lezer ruimte een eigen oordeel te vellen. Toch is het zo dat de roman vanuit het historische perspectief van Nederland is geschreven.
Is dat iets waar je mee hebt geworsteld tijdens het schrijven?
In hoeverre is het nodig en mogelijk het perspectief en de beweegredenen van de Atjeeërs te vertolken, of blijven zij toch de stemlozen van de koloniale geschiedenis?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;BW: Ik ben me er zeker van bewust dat de roman vanuit Nederlands perspectief is geschreven, al was het maar omdat ik was aangewezen op Nederlandse boeken, waarvan ook nog eens vaak voormalige officieren de auteurs waren.
Voor zover mij bekend is er trouwens nauwelijks documentatie van Atjese kant, en mocht die er zijn dan kan ik er niet mee uit de voeten, omdat ik de taal niet machtig ben.
De rol om de oorlog vanuit Atjees perspectief te belichten zou ik me trouwens sowieso niet graag toe-eigenen.
Ik pretendeer daarom zeker niet de Atjese kant van de oorlog goed te vertolken.
Toch hoop ik er wel indirect aan bij te dragen de Atjeeërs een stem te geven.
Te zorgen dat de oorlog niet vergeten wordt, lijkt me daarbij een eerste stap.&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>On circular imports in Python</title>
            <link>https://www.edwinwenink.xyz/posts/68-python_circular_imports/</link>
            <guid>https://www.edwinwenink.xyz/posts/68-python_circular_imports/</guid>
            <pubDate>Sat, 24 Sep 2022 14:00:45 +0200</pubDate>
            <description>&lt;p&gt;It has happened in the past that I&#39;ve been sloppy with programming and took some shortcuts just to &#34;get things done,&#34; and that I encountered an error like the following: &lt;code&gt;AttributeError: module &#39;X&#39; has no attribute &#39;call&#39;&lt;/code&gt;.
This was quite baffling because module X &lt;em&gt;did&lt;/em&gt; have the attribute &lt;code&gt;call&lt;/code&gt;.
It turned out that I had accidentally did a very bad thing, namely to use a circular import that caused a function call to module X before that function was properly defined.
I knew I messed up, but in this post I dive deeper into &lt;em&gt;how&lt;/em&gt; I messed up.&lt;/p&gt;
&lt;h2&gt;Example&lt;/h2&gt;
&lt;p&gt;Let&#39;s say we have a module X importing module Y:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;# module X
import Y

print(&amp;quot;Name:&amp;quot;, __name__)
print(&amp;quot;X start&amp;quot;)


def call():
    print(&amp;quot;You are calling a function of module X.&amp;quot;)


if __name__ == &#39;__main__&#39;:
    print(&amp;quot;X main&amp;quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When we call this script, we call the &lt;code&gt;import Y&lt;/code&gt; statement first, which executes the code in module &lt;code&gt;Y&lt;/code&gt;.
Now let&#39;s define module &lt;code&gt;Y&lt;/code&gt; with a circular import:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;# module Y
import X

print(&amp;quot;Name:&amp;quot;, __name__)
print(&amp;quot;Y start&amp;quot;)

X.call()


def call():
    print(&amp;quot;You are calling a function of module Y.&amp;quot;)


if __name__ == &#39;__main__&#39;:
    print(&amp;quot;Y main&amp;quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now if we open an interactive terminal and import X, we run into trouble:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; import X
Name: Y
Y start
Traceback (most recent call last):
  File &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 1, in &amp;lt;module&amp;gt;
  File &amp;quot;C:\Users\Edwin Wenink\Documents\programming-practice\Python\circular_import\X.py&amp;quot;, line 2, in &amp;lt;module&amp;gt;
    import Y
  File &amp;quot;C:\Users\Edwin Wenink\Documents\programming-practice\Python\circular_import\Y.py&amp;quot;, line 6, in &amp;lt;module&amp;gt;
    X.call()
AttributeError: module &#39;X&#39; has no attribute &#39;call&#39;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is what happens:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;We import module X&lt;/li&gt;
&lt;li&gt;The first line of module X import Y&lt;/li&gt;
&lt;li&gt;This executes the code in module Y&lt;/li&gt;
&lt;li&gt;Python sees X is already (partially being) imported, so the &lt;code&gt;import X&lt;/code&gt; statement in &lt;code&gt;Y&lt;/code&gt; will not trigger compilation of the content of X.&lt;/li&gt;
&lt;li&gt;This will print  &#34;Name: Y&#34; and &#34;Y start&#34;&lt;/li&gt;
&lt;li&gt;Then it will run &lt;code&gt;X.call()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;But the &lt;code&gt;def call()&lt;/code&gt; statement in module &lt;code&gt;X&lt;/code&gt; has not been run yet, so we run into this error!&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Understanding the problem&lt;/h2&gt;
&lt;p&gt;A possible solution could be to run &lt;code&gt;import Y&lt;/code&gt; only &lt;em&gt;after&lt;/em&gt; declaring the functions that are needed by module &lt;code&gt;Y&lt;/code&gt;.
If we do this, we get the following output without error:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; import X
X start
Y start
You are calling a function of module X.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that importing Y with the above code gives no problems because X is defined before &lt;code&gt;X.call()&lt;/code&gt; runs, but &lt;em&gt;only&lt;/em&gt; because in this toy example X does currently not use the imported module Y:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; import Y
Name: X
X start
Name: Y
Y start
You are calling a function of module X.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In both cases, we see that the main function does not run because neither module is invoked as the main module.
The current situation is that importing X throws an error, but importing Y does not.
When &lt;em&gt;directly invoking&lt;/em&gt; the scripts as the main module, we see the opposite!
Calling X:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt; python X.py
Name: X
X start
Name: Y
Y start
You are calling a function of module X.
Name: __main__
X start
X main
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It took me a bit to understand why this does work now.
The difference is that now we do not start our execution with an &lt;code&gt;import X&lt;/code&gt; statement, so that in the first line of &lt;code&gt;Y.py&lt;/code&gt; the &lt;code&gt;import X&lt;/code&gt; line actually triggers a full run over &lt;code&gt;X&lt;/code&gt;.
This means that &lt;code&gt;X.call()&lt;/code&gt; is defined after all before it&#39;s called in &lt;code&gt;Y&lt;/code&gt;!
Another detail we notice now is that &lt;code&gt;Y&lt;/code&gt; calls the module X; but when the executing of the main file continues, we are running the &lt;code&gt;__main__&lt;/code&gt; object.&lt;/p&gt;
&lt;p&gt;Now let&#39;s see what happens when calling Y as the main function:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt; python Y.py
Name: Y
Y start
Traceback (most recent call last):
  File &amp;quot;Y.py&amp;quot;, line 2, in &amp;lt;module&amp;gt;
    import X
  File &amp;quot;C:\Users\Edwin Wenink\Documents\programming-practice\Python\circular_import\X.py&amp;quot;, line 2, in &amp;lt;module&amp;gt;
    import Y
  File &amp;quot;C:\Users\Edwin Wenink\Documents\programming-practice\Python\circular_import\Y.py&amp;quot;, line 6, in &amp;lt;module&amp;gt;
    X.call()
AttributeError: module &#39;X&#39; has no attribute &#39;call&#39;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, executing &lt;code&gt;Y&lt;/code&gt; triggers &lt;code&gt;import X&lt;/code&gt;.
This in turn, will trigger &lt;code&gt;import Y&lt;/code&gt;.
Because &lt;code&gt;Y&lt;/code&gt; is not in the list of modules yet (we haven&#39;t run &lt;code&gt;import Y&lt;/code&gt;), Y will be compiled and we&#39;ll encounter &lt;code&gt;X.call()&lt;/code&gt; before this function is defined.&lt;/p&gt;
&lt;p&gt;Things get even more complicated when &lt;code&gt;Y&lt;/code&gt; is also called from &lt;code&gt;X&lt;/code&gt;.
Even when you can postpone some imports to quickly fix the situation, it&#39;s better to avoid this situation altogether by refactoring your code.
Otherwise, your code will break if a colleague wonders why there&#39;s an import statement at the bottom of the file and moves it up.&lt;/p&gt;
&lt;p&gt;TLDR; &lt;em&gt;avoid circular imports!&lt;/em&gt;&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>Initializing nested lists correctly</title>
            <link>https://www.edwinwenink.xyz/posts/67-initializing_nested_lists_correctly/</link>
            <guid>https://www.edwinwenink.xyz/posts/67-initializing_nested_lists_correctly/</guid>
            <pubDate>Wed, 27 Jul 2022 11:16:50 +0200</pubDate>
            <description>&lt;p&gt;If you want to initialize a list with a certain size in Python, you can use the following clean syntax:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr = [None]*3
&amp;gt;&amp;gt;&amp;gt; arr
[None, None, None]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can then fill the list with elements:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr[1] = 1
&amp;gt;&amp;gt;&amp;gt; arr
[None, 1, None]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But watch what happens when we try to use the same syntax for declaring a 2D dynamic array:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr2 = [[]]*3
&amp;gt;&amp;gt;&amp;gt; arr2
[[], [], []]
&amp;gt;&amp;gt;&amp;gt; arr2[1].append(1)
&amp;gt;&amp;gt;&amp;gt; arr2
[[1], [1], [1]]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The desired result here was the ragged array &lt;code&gt;[[], [1], []]&lt;/code&gt;, but instead we accidentally filled &lt;em&gt;all&lt;/em&gt; nested lists...
What happened?!
Well, we observe here that the &lt;code&gt;*&lt;/code&gt; operator creates a list where the elements reference the same underlying object!&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; id(arr2[0])
1474142748360
&amp;gt;&amp;gt;&amp;gt; id(arr2[1])
1474142748360
&amp;gt;&amp;gt;&amp;gt; id(arr2[2])
1474142748360
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So that explains why adjusting one sublist affects all sublists: they are the same object.
But why did we then not have the same issue when initializing the flat empty list with None objects?
Actually, the &lt;code&gt;*&lt;/code&gt; operator works exactly the same here and &lt;em&gt;also&lt;/em&gt; creates a reference to the same object.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; id(arr[0])
140720689536224
&amp;gt;&amp;gt;&amp;gt; id(arr[2])
140720689536224
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But if we inspect the element where we filled in a value, we &lt;em&gt;do&lt;/em&gt; see that it is a new object:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; id(arr[1])
140720690012576
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The crucial difference is that this &lt;code&gt;NoneType&lt;/code&gt; object is &lt;em&gt;immutable&lt;/em&gt;.
The referenced object &lt;em&gt;cannot be changed&lt;/em&gt; but is rather replaced with a new object.
The same reasoning holds when we have a list of integers or strings.
In case of a list of lists, or a list of dictionaries (any mutable data structure) however, we &lt;em&gt;can&lt;/em&gt; adjust the referenced object and then the change will reflect onto all sublists.
Because something like &lt;code&gt;[1]*3&lt;/code&gt; works as expected, it can be hard to spot the difference in behavior when working with nested mutable data structures.&lt;/p&gt;
&lt;p&gt;If we explicitly replace a whole sublist with a new object, there&#39;s no issue:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr2[1] = [2]
&amp;gt;&amp;gt;&amp;gt; arr2
[[1], [2], [1]]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is not a practical solution though, because we want to be able to use functions like &lt;code&gt;append()&lt;/code&gt; on sublists correctly.
The general solution is to force Python to make a new object for each sublist, which means - however nice and clean the syntax looks - we have to avoid using &lt;code&gt;*&lt;/code&gt; for this!
Instead, create the sublists in an explicit loop or for example a list comprehension:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr3 = [[] for _ in range(3)]
&amp;gt;&amp;gt;&amp;gt; arr3
[[], [], []]
&amp;gt;&amp;gt;&amp;gt; arr3[1].append(1)
&amp;gt;&amp;gt;&amp;gt; arr3
[[], [1], []]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This way each of the sublists is its own object, rather than being a reference to the same list, because we force Python to evaluate &lt;code&gt;[]&lt;/code&gt; 3 times instead of only once.&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>Regular expressions with optional starting or ending groups</title>
            <link>https://www.edwinwenink.xyz/posts/66-regex_with_starting_and_ending_optional_groups/</link>
            <guid>https://www.edwinwenink.xyz/posts/66-regex_with_starting_and_ending_optional_groups/</guid>
            <pubDate>Thu, 10 Feb 2022 10:29:34 +0100</pubDate>
            <description>&lt;p&gt;I&#39;m currently working on a classifier that can extract punishments from Dutch criminal law decisions.
One of those punishments is called &#34;TBS&#34;, which is assigned in severe cases where it is shown that the suspect was under the influence of a psychiatric condition at the time of committing the crime.&lt;/p&gt;
&lt;p&gt;There&#39;s two types of TBS in the Netherlands: with &#34;verpleging&#34; (mandatory psychiatric treatment) and with &#34;voorwaarden&#34; (several conditions).
We want to match &#34;terbeschikkingstelling&#34; (TBS), but if the type of TBS is specified, we want to capture that too.&lt;/p&gt;
&lt;p&gt;These TBS judgments occur in free natural language texts, but because lawyers and judges tend to use standard formulations with legal jargon -- although... &#34;standard&#34;... who really talks like that? -- we may try to extract information from case decisions using regular expressions.
Regular expressions are essentially a powerful way to do pattern matching on text.&lt;/p&gt;
&lt;h2&gt;Optional group after greedy quantifier&lt;/h2&gt;
&lt;p&gt;To start, we want to match the following test strings:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&#34;de maatregel van terbeschikkingstelling wordt aan de verdachte opgelegd.&#34;&lt;/li&gt;
&lt;li&gt;&#34;de maatregel van terbeschikkingstelling met voorwaarden te gelasten.&#34;&lt;/li&gt;
&lt;li&gt;&#34;de maatregel van terbeschikkingstelling met verpleging van overheidswege te gelasten.&#34;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In these test cases, the type of TBS is mentioned at the end of the match and is optional.&lt;/p&gt;
&lt;p&gt;A fully naive first attempt to tackle this problem could be as follows:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;(terbeschikkingstelling).*(voorwaarden|verpleging)?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But this will match &#34;terbeschikkingstelling&#34; but &lt;em&gt;not&lt;/em&gt; &#34;verpleging&#34; because of the &#34;dot star soup&#34; (expression I found and liked on rexegg.com).
Because the ending group is optional, &lt;code&gt;.*&lt;/code&gt; will consume until the end of the string and be happy.&lt;/p&gt;
&lt;p&gt;I&#39;ve actually never used regular expressions outside of trivial situations, so I had to go back and study them a bit to find a better solution to my problem
(shout out to &lt;a href=&#34;https://www.rexegg.com/&#34;&gt;rexegg.com&lt;/a&gt;!).&lt;/p&gt;
&lt;p&gt;Essentially, we want the  &#34;dot star&#34; to expand until we encounter &#34;verpleging&#34; or &#34;voorwaarden&#34;, but no further, and then capture &#34;verpleging&#34; or &#34;voorwaarden&#34;.
That is, we want to match any token (&lt;code&gt;.&lt;/code&gt;) that is &lt;em&gt;not followed&lt;/em&gt; by &#34;verpleging&#34; or &#34;voorwaarden&#34;, making these words essentially function as delimiters that restrict the scope of the greedy quantifier.
This is done with a &lt;em&gt;negative lookahead&lt;/em&gt;, which looks like this &lt;code&gt;(?!)&lt;/code&gt;.
This ensures that the pattern does &lt;em&gt;not&lt;/em&gt; occur after the position the regex engine is currently matching.&lt;/p&gt;
&lt;p&gt;Let&#39;s first apply this idea to only one of the alternatives: &lt;code&gt;(?!voorwaarden).&lt;/code&gt;.
We want to repeat this zero or more times, so we wrap this in a non-capturing group and apply the greedy star quantifier:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;(?:(?!voorwaarden).)*
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now the scope of the star is limited, because it will stop matching once &#34;voorwaarden&#34; is found.
In this case we actually want to capture &#34;voorwaarden.&#34;
Because we know the star will stop matching right before &#34;voorwaarden&#34;, we can safely gobble up &#34;voorwaarden&#34; as a literal match:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;(?:(?!voorwaarden).)*(voorwaarden)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this case, &#34;voorwaarden&#34; is still a required match.
But the crux is that now we can safely make the ending group optional, because we&#39;ve scoped the greedy quantifier and prevented it from gobbling up our optional group at the end!&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;(?:(?!voorwaarden).)*(voorwaarden)?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that with an optional group at the end, we cannot make the star quantifier lazy (&lt;code&gt;*?&lt;/code&gt;) because then the regex will never try to find the optional ending group (yep, it&#39;s &lt;em&gt;really&lt;/em&gt; lazy!).&lt;/p&gt;
&lt;p&gt;Now we finish up by including the second alternative.
The whole regex becomes:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;(terbeschikkingstelling)(?:(?!voorwaarden|verpleging).)*(voorwaarden|verpleging)?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The only thing left to do is to think a bit about what happens when &#34;voorwaarden&#34; or &#34;verpleging&#34; does &lt;em&gt;not&lt;/em&gt; occur in our input string.
We need to design for failure.
If the optional group is absent, the regex will always match until the end of the input string.
In my particular problem that&#39;s quite bad, because I&#39;m feeding the regex whole paragraphs of text at once.
We can use a bit of domain knowledge here though, because the further specification of the type of TBS will always occur in a short window after the main punishment is mentioned.
So an easy solution would be to explicitly specify the window in which we will look for the type specification, let&#39;s say within 100 characters:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;(terbeschikkingstelling)(?:(?!voorwaarden|verpleging).){0,100}(voorwaarden|verpleging)?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The test cases will now return the following groups:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;&amp;quot;de maatregel van terbeschikkingstelling wordt aan de verdachte opgelegd.&amp;quot;

-&amp;gt; group 1: terbeschikkingstelling

&amp;quot;de maatregel van terbeschikkingstelling met voorwaarden te gelasten.&amp;quot;

-&amp;gt; group 1: terbeschikkingstelling; group 2: voorwaarden

&amp;quot;de maatregel van terbeschikkingstelling met verpleging van overheidswege te gelasten.&amp;quot;

-&amp;gt; group 1: terbeschikkingstelling, group 2: verpleging
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Diving deeper into the use case&lt;/h3&gt;
&lt;p&gt;Let&#39;s take some actual test cases where TBS is imposed in Dutch law:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&#34;gelast de terbeschikkingstelling van verdachte, met verpleging van overheidswege&#34; (ECLI:NL:RBZWB:2020:6268).&lt;/li&gt;
&lt;li&gt;&#34;gelast dat de verdachte, voor de feiten 2, 3 en 4, ter beschikking wordt gesteld en stelt daarbij de volgende, het gedrag van de ter beschikking gestelde betreffende, voorwaarden&#34; (ECLI:NL:RBLIM:2020:9778).&lt;/li&gt;
&lt;li&gt;&#34;De rechtbank verlengt de termijn van de terbeschikkingstelling van veroordeelde met één jaar&#34; (ECLI:NL:RBNNE:2020:4558).&lt;/li&gt;
&lt;li&gt;&#34;verlengt de termijn gedurende welke [verdachte] ter beschikking is gesteld met verpleging van overheidswege met één jaar&#34; (ECLI:NL:RBLIM:2020:10468).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We first recognizes that there are alternative formulations like &#34;ter beschikking is gesteld&#34; and &#34;ter beschikking wordt gesteld,&#34; so we adjust the regex for that.
We also allow &#34;terbeschikkingstelling&#34; to be written as &#34;ter beschikking stelling&#34; and include &#34;TBS&#34; as the relevant abbreviation.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;(TBS|terbeschikkingstelling|ter beschikking (?:wordt |is )?(?:stelling|gesteld))(?:(?!voorwaarden|verpleging).){0,100}(voorwaarden|verpleging)?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, there is a subtlety: legal jargon related to &#34;ter beschikking stellen&#34; does not necessarily indicate TBS but can also relate e.g. to goods.
If we really want to make sure these phrases relates to TBS (i.e. avoid false positives) we should probably make the ending group non-optional after all.
However, this means we do not match cases where TBS is assigned in the past, but is now prolongated such as in &#34;verlengt de termijn van de terbeschikkingstelling.&#34;
The type of TBS is not specified here because it has already been determined in a previous judgement.
So our new problem statement could be: we think a TBS-punishment is assigned either when it is preceded by an indication of prolongation such as &#34;verlenging&#34; or when the type of TBS is explicitly specified (with &#34;voorwaarden&#34; or &#34;verpleging&#34;).&lt;/p&gt;
&lt;p&gt;Let&#39;s again decompose the problem and solve the case where &#34;verlenging&#34; occurs &lt;em&gt;before&lt;/em&gt; the indication of TBS.
We again want to design a delimiter, but now one that determines where to &lt;em&gt;start&lt;/em&gt; matching instead of where to end.
We can express that we only want to start matching after having seen either &#34;verlenging&#34; or &#34;verlengt&#34; with a &lt;em&gt;positive lookbehind&lt;/em&gt; on &#34;verleng&#34;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;(?&amp;lt;=verleng).*?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But since we know where to begin matching and we&#39;d like to also capture &#34;verlenging&#34;, we can just anchor the start with a literal match:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;(?P&amp;lt;verlenging&amp;gt;verlengt|verlenging).{0,50}(?P&amp;lt;TBS1&amp;gt;TBS|terbeschikkingstelling|ter beschikking (?:wordt |is )?(?:stelling|gesteld))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Combining everything we get a quite lengthy regex with two alternatives.
Either we require something like &#34;verlenging&#34; in front of the regex, or something like &#34;veroordeling&#34; or &#34;voorwaarden&#34; after.
The ending group is now no longer optional:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;(?P&amp;lt;verlenging&amp;gt;verlengt|verlenging).{0,50}(TBS|terbeschikkingstelling|ter beschikking (?:wordt |is )?(?:stelling|gesteld))|(TBS|terbeschikkingstelling|ter beschikking (?:wordt |is )?(?:stelling|gesteld))(?:(?!voorwaarden|verpleging).){0,100}(voorwaarden|verpleging)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By using this alternation, we have to repeat the regex for the TBS part.
I also find this a bit annoying, because if I want to do something with the &#34;TBS&#34; part downstream it can either be in the second or third capture group.
On average, this also increases the number of steps the regex engine has to traverse.&lt;/p&gt;
&lt;p&gt;We can also change our mindset: instead of only matching what we want to keep, we can capture all relevant components and throw away matches we don&#39;t want downstream.
For example, we can get rid of the alternation and just have optional groups both at the beginning and end.
The only thing we then have to do is filter out matches that have neither of the optional groups.&lt;/p&gt;
&lt;p&gt;The regex with two optional groups, both at the beginning and the end, could look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;(?:(verlengt|verlenging).{0,50})?(TBS|terbeschikkingstelling|ter beschikking (?:wordt |is )?(?:stelling|gesteld))(?:(?!voorwaarden|verpleging).){0,100}(voorwaarden|verpleging)?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Test case 1: &#34;gelast de terbeschikkingstelling van verdachte, met verpleging van overheidswege&#34; (ECLI:NL:RBZWB:2020:6268).&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;match: terbeschikkingstelling van verdachte, met verpleging
group 2: terbeschikkingstelling
group 3: verpleging
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Test case 2: &#34;gelast dat de verdachte, voor de feiten 2, 3 en 4, ter beschikking wordt gesteld en stelt daarbij de volgende, het gedrag van de ter beschikking gestelde betreffende, voorwaarden&#34; (ECLI:NL:RBLIM:2020:9778).&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;match: ter beschikking wordt gesteld en stelt daarbij de volgende, het gedrag van de ter beschikking gestelde betreffende, vooraarden
group 2: ter beschikking wordt gesteld
group 3: voorwaarden
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Test case 3: &#34;De rechtbank verlengt de termijn van de terbeschikkingstelling van veroordeelde met één jaar&#34; (ECLI:NL:RBNNE:2020:4558).&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;match: verlengt de termijn van de terbeschikkingstelling van veroordeelde met één jaar
group 1: verlengt
group 2: terbeschikkingstelling
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Test case 4: &#34;verlengt de termijn gedurende welke [verdachte] ter beschikking is gesteld met verpleging van overheidswege met één jaar&#34; (ECLI:NL:RBLIM:2020:10468).&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-text&#34;&gt;match: verlengt de termijn gedurende welke [verdachte] ter beschikking is gesteld met verpleging
group 1: verlengt
group 2: ter beschikking is gesteld
group 3: verpleging
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Some final notes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In this setup, not making &lt;code&gt;(voorwaarden|verpleging)?&lt;/code&gt; optional leads to large inefficiency if the group is not in the string. It will cause the lookahead to be repeated a lot in an attempt to still find the group.&lt;/li&gt;
&lt;li&gt;Downstream we may opt to reject the match if neither of the optional groups is matched, because this may be a false positive. The upside is that this gives flexibility in your application without having to redesign the regex. As we see in the last test case, it may also be that &lt;em&gt;both&lt;/em&gt; groups are present as we see in test case 4.&lt;/li&gt;
&lt;li&gt;There are other edge cases to catch for detecting TBS. I only consider a few test cases to keep things simple.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Please let me know if you see points where I can improve (e.g. in terms of optimization)!&lt;/p&gt;
&lt;p&gt;Related note: &lt;a href=&#34;https://www.edwinwenink.xyz/index_regex.html&#34;&gt;index regex&lt;/a&gt;.&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>Stemming and lemmatizing with sklearn vectorizers</title>
            <link>https://www.edwinwenink.xyz/posts/65-stemming_and_lemmatizing_with_sklearn_vectorizers/</link>
            <guid>https://www.edwinwenink.xyz/posts/65-stemming_and_lemmatizing_with_sklearn_vectorizers/</guid>
            <pubDate>Fri, 21 Jan 2022 19:21:21 +0100</pubDate>
            <description>&lt;p&gt;One of the most basic techniques in Natural Language Processing &lt;a href=&#34;zettelkasten/index_NLP_Natural_Language_Processing.html&#34;&gt;(NLP)&lt;/a&gt; is the creation of feature vectors based on word counts.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;scikit-learn&lt;/code&gt; provides efficient classes for this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If we want to build feature vectors over a vocabulary of &lt;em&gt;stemmed&lt;/em&gt; or &lt;em&gt;lemmatized&lt;/em&gt; words, how can we do this and still benefit from the ease and efficiency of using these &lt;code&gt;sklearn&lt;/code&gt; classes?&lt;/p&gt;
&lt;h2&gt;Vectorizers: the basic use case&lt;/h2&gt;
&lt;p&gt;Conceptually, these vectorizers first build up the vocabulary of your whole text corpus.
The size of the vocabulary determines the length of the feature vectors, unless you specify a maximum amount of features (which you probably should, cf. &lt;a href=&#34;zettelkasten/202009151217-Zipfs_law.html&#34;&gt;Zipfs law&lt;/a&gt;).
The vectorizers check for each document how often a certain word (or n-gram, technically) occurs in that document.
The &lt;code&gt;CountVectorizer&lt;/code&gt; only takes the term frequency (TF) into account.
However, words that occur in almost all the documents (like stop words) are not very useful for characterizing individual documents and distinguishing them from others.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;We should treat matches on non-frequent terms as more valuable than ones on frequent terms, without disregarding the latter altogether. The natural solution is to correlate a term&#39;s matching value with its collection frequency. (Karen Spärk Jones, 1972)&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The &lt;code&gt;TfidfVectorizer&lt;/code&gt; therefore additionally weighs the word frequency with how common the word is in the whole corpus.
If a word occurs a lot in document $t$ but is quite rare throughout the whole corpus, then this is a useful word to characterize the current document.
Conversely, if a term is frequent in document $t$ but it occurs a lot in literally every other document as well, then it is a poor descriptor.
In its most basic form (without smoothing etc.) &lt;a href=&#34;zettelkasten/202201211817-TF_IDF.html&#34;&gt;TF*IDF scoring&lt;/a&gt; looks like this:&lt;/p&gt;
&lt;p&gt;$$TF(t,d) * log (\frac{N}{DF(t)})$$&lt;/p&gt;
&lt;p&gt;Where $TF(t,d)$ is the frequency of term $t$ in document $d$, $N$ is the total amount of documents in the corpus, and $DF(t)$ is the amount of documents in which term $t$ occurs.
The logarithm is called the Inverse Document Frequency (IDF), hence we get TF*IDF.
The logarithm prevents that very rare words completely dominate the score.
Additionally, it punishes the most frequent words relatively heavy.&lt;/p&gt;
&lt;h2&gt;Composing a new tokenizer&lt;/h2&gt;
&lt;p&gt;It is very convenient and efficient to use the &lt;code&gt;sklearn&lt;/code&gt; vectorizers, but how can we use them when we want to do additional natural language processing during the building of the corpus vocabulary?&lt;/p&gt;
&lt;p&gt;Vectorizers can be customised with three arguments: 1) preprocessor, 2) tokenizer, and 3) analyzer:&lt;/p&gt;
&lt;p&gt;1) The preprocessor is a callable that operates on a whole string and returns a whole string.
2) The tokenizer takes the preprocessor output and returns a list of tokens.
3) The analyzer is a callable that replaces the whole pipeline, including preprocessing and tokenization, and I think also including N-gram extraction and stop word filtering.&lt;/p&gt;
&lt;p&gt;So in order to add stemming or lemmatization to the sklearn vectorizers, a good approach is to include this in a custom tokenize function.
This does assume our stemming and lemmatization functions only need access to tokens, instead of the whole input strings (may be documents, sections, paragraphs, sentences etc.).&lt;/p&gt;
&lt;p&gt;This is a very nice snippet to compose functions using &lt;code&gt;functools&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;import functools

def compose(*functions):
    &#39;&#39;&#39;
    Compose an arbitary amount of functions into a single function
    Source: https://mathieularose.com/function-composition-in-python
    &#39;&#39;&#39;
    def comp(f, g):
        return lambda x: f(g(x))
    return functools.reduce(comp, functions, lambda x: x)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Assuming we have some class where we can assign a stemmer, a lemmatizer, or neither, we can override the tokenizer as follows:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;# If a stemmer or lemmatizer is provided in the configuration
# compose a new tokenization function that includes stemming/lemmatization after tokenization.
# This allows stemming or lemmatization to be integrated e.g. with CountVectorizer
if stemmer:
    self._tokenize = compose(self._stemmer.stem, self._tokenizer.tokenize)
elif lemmatizer:
    self._tokenize = compose(self._lemmatizer.lemmatize, self._tokenizer.tokenize)
else:
    self._tokenize = self._tokenizer.tokenize
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the order of the composition matters, because the function signatures differ.
A tokenization function takes a string as an input and outputs a list of tokens, and our stemming or lemmatization function then operates on this list of tokens.
We can now define a &lt;code&gt;TfidfVectorizer&lt;/code&gt; with our custom callable!&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;ngram_range = (1,1)
max_features = 1000
use_idf = True

tfidf = TfidfVectorizer(tokenizer=self._tokenize,
                        max_features=max_features,
                        ngram_range=ngram_range,
                        min_df=1,
                        max_df=1.0,
                        use_idf=use_idf)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The vocabulary will now consist of stems and lemmas.&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>Applying operations on grouped dataframes in Pandas</title>
            <link>https://www.edwinwenink.xyz/posts/64-apply_operations_on_grouped_objects_pandas/</link>
            <guid>https://www.edwinwenink.xyz/posts/64-apply_operations_on_grouped_objects_pandas/</guid>
            <pubDate>Tue, 04 Jan 2022 13:41:17 +0100</pubDate>
            <description>&lt;p&gt;I have the following use case:
I have legal text data that is stored on section level, so a single document with multiple sections will provide multiple rows to the data set.
These sections have a particular type.
For example, a case is typically concluded with a section where the judges offer their final ruling.&lt;/p&gt;
&lt;p&gt;I want to investigate the hypothesis that each case has indeed a single section of the type &#39;decision&#39;.&lt;/p&gt;
&lt;p&gt;A dummy dataframe for this situation looks may like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;import pandas as pd

data = {&#39;doc_id&#39;: [1, 1, 2, 2, 3, 3],
        &#39;section_id&#39;: [1, 2, 1, 2, 1, 2],
        &#39;type&#39;: [&#39;other&#39;, &#39;decision&#39;, &#39;other&#39;, &#39;other&#39;, &#39;decision&#39;, &#39;decision&#39;]}
df = pd.DataFrame(data)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This gives:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; df
   doc_id  section_id      type
0       1           1     other
1       1           2  decision
2       2           1     other
3       2           2     other
4       3           1  decision
5       3           2  decision
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This dummy example distinguishes three cases:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;the first document contains a single section with a decision, as expected&lt;/li&gt;
&lt;li&gt;the second document contains no section with a decision&lt;/li&gt;
&lt;li&gt;the third document contains two sections with a decision&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Notice that in this case we cannot simply test our hypothesis by counting the amount of documents and checking equality with the number of sections with type &#39;decision&#39;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; len(df[&#39;doc_id&#39;].unique())
3
&amp;gt;&amp;gt;&amp;gt; len(df.loc[df[&#39;type&#39;] == &#39;decision&#39;])
3
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The totals add up, but our hypothesis is clearly false!&lt;/p&gt;
&lt;p&gt;Instead, we want to test our hypothesis on the level of documents, not sections, so we &lt;em&gt;group&lt;/em&gt; our data by the document identifier:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; df.groupby(&#39;doc_id&#39;)
&amp;lt;pandas.core.groupby.generic.DataFrameGroupBy object at 0x000001C55EF8F9E8&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we want to count the number of &#39;decision&#39; sections on the data that is grouped &lt;em&gt;per document&lt;/em&gt;, so we want to &lt;em&gt;apply&lt;/em&gt; the counting operation on the grouped data.
For this I apply a lambda expression in order to only regard data from the &#39;type&#39; column of each group.
With this functional style, we can do all operations in a single line:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; decision_counts = df.groupby(&#39;doc_id&#39;).apply(lambda x: len(x.loc[x[&#39;type&#39;] == &#39;decision&#39;]))
&amp;gt;&amp;gt;&amp;gt; decision_counts
doc_id
1    1
2    0
3    2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We end up with a dataframe that lists the number of &#39;decision&#39; sections per document.
Counting how many documents violate our hypothesis is now trivial.
We can count the number of documents that have no &#39;decision&#39; sections and those that have more than one, as follows:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; decision_counts[decision_counts == 0]
doc_id
2    0
&amp;gt;&amp;gt;&amp;gt; decision_counts[decision_counts &amp;gt; 1]
doc_id
3    2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We indeed see that document 2 has zero &#39;decision&#39; sections, whereas document 3 has two.&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>Zip is its own inverse</title>
            <link>https://www.edwinwenink.xyz/posts/63-zip_is_its_own_inverse/</link>
            <guid>https://www.edwinwenink.xyz/posts/63-zip_is_its_own_inverse/</guid>
            <pubDate>Thu, 23 Dec 2021 16:03:24 +0100</pubDate>
            <description>&lt;p&gt;You can undo the zipping operation using &lt;code&gt;zip&lt;/code&gt; itself.
Let&#39;s explore that in Python.
By using the unpacking operator &lt;code&gt;*&lt;/code&gt; you don&#39;t have to manually specify the number of arguments (although I do assume the return of two components in the example below).
In Python 3, the zip operator returns a generator instead of a list, so you need to explicitly cast to a list if you want one.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; a = [1, 3]
&amp;gt;&amp;gt;&amp;gt; b = [2, 4]
&amp;gt;&amp;gt;&amp;gt; c = list(zip(a,b))
&amp;gt;&amp;gt;&amp;gt; c
[(1, 2), (3, 4)]
&amp;gt;&amp;gt;&amp;gt; a, b = list(zip(*c))
&amp;gt;&amp;gt;&amp;gt; a
(1, 3)
&amp;gt;&amp;gt;&amp;gt; b
(2, 4)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The inverse operation will always return tuples in Python, so if your original input was a list, you also need to convert back the results to a list.&lt;/p&gt;
&lt;p&gt;This operation is super handy.
For example, I wrote a class to recommend relevant texts for a query document based on their distance in a vector space.
The &lt;code&gt;recommend()&lt;/code&gt; function of this class returns a list of recommended texts and a list of tuples containing relevant metadata about those texts.
So the metadata will be a list of &lt;code&gt;(distance, document_id, type)&lt;/code&gt; tuples.
We may be interested in easily retrieving all distances, document_ids etc. as a list of their own.
We can do that by using the unpack+zip trick:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;distances, document_ids, types = zip(*meta)
&lt;/code&gt;&lt;/pre&gt;</description>
        </item>
        
        <item>
            <title>Flatten nested lists with a list comprehension</title>
            <link>https://www.edwinwenink.xyz/posts/62-flatten_with_list_comprehension/</link>
            <guid>https://www.edwinwenink.xyz/posts/62-flatten_with_list_comprehension/</guid>
            <pubDate>Thu, 23 Dec 2021 16:03:12 +0100</pubDate>
            <description>&lt;p&gt;Here&#39;s my programming tip of the day.
You can flatten a nested list of lists into a single flat list with a nested list comprehension.
Wow, phrasing.&lt;/p&gt;
&lt;p&gt;It&#39;s easy to get confused.
If you forget how to do it, you can first write out the whole loop:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;# Flatten list
&amp;gt;&amp;gt;&amp;gt; flat = []
&amp;gt;&amp;gt;&amp;gt; nested = [ [1, 2, 3], [4, 5, 6] ]
&amp;gt;&amp;gt;&amp;gt; for sub in nested:
&amp;gt;&amp;gt;&amp;gt;    for element in sub:
&amp;gt;&amp;gt;&amp;gt;        flat.append(element)
&amp;gt;&amp;gt;&amp;gt; flat
[1, 2, 3, 4, 5, 6]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To collapse this into a one-liner, work from the &lt;em&gt;outer scope inwards&lt;/em&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;flat = [ el for sub in nested for el in sub ]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Voila. Lean and mean.&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>Wrong feature preprocessing is a source of train-test leakage</title>
            <link>https://www.edwinwenink.xyz/posts/61-feature_preprocessing_and_train_test_leakage/</link>
            <guid>https://www.edwinwenink.xyz/posts/61-feature_preprocessing_and_train_test_leakage/</guid>
            <pubDate>Fri, 10 Dec 2021 12:39:02 +0100</pubDate>
            <description>&lt;p&gt;Feature selection should be done &lt;em&gt;after&lt;/em&gt; train-test splitting to avoid leaking information from the test set into the training pipeline.
This also means that feature selection should be done &lt;em&gt;within&lt;/em&gt; each fold of cross-validation, not before.
This sounds obvious, but this is something that goes wrong easily and often.
Especially when the feature extraction and selection pipeline is relatively expensive, having to repeat it in each fold may be a perverse incentive to want to only do it once before cross-validation.
It may also be that feature selection is done on the data set prior to even starting other machine learning work, so it&#39;s easy to overlook.
In this post we discuss the do&#39;s and don&#39;ts when it comes to leaking information from a test set during preprocessing.&lt;/p&gt;
&lt;h2&gt;Code example&lt;/h2&gt;
&lt;p&gt;This is an example of how it should &lt;em&gt;not&lt;/em&gt; be done (&lt;a href=&#34;https://stackoverflow.com/questions/56308116/should-feature-selection-be-done-before-train-test-split-or-after&#34;&gt;source&lt;/a&gt;):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;import numpy as np
from sklearn.feature_selection import SelectKBest
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# random data:
X = np.random.randn(500, 10000)
y = np.random.choice(2, size=500)

selector = SelectKBest(k=25)
# first select features
X_selected = selector.fit_transform(X,y)
# then split
X_selected_train, X_selected_test, y_train, y_test = train_test_split(X_selected, y, test_size=0.25, random_state=42)

# fit a simple logistic regression
lr = LogisticRegression()
lr.fit(X_selected_train,y_train)

# predict on the test set and get the test accuracy:
y_pred = lr.predict(X_selected_test)
accuracy_score(y_test, y_pred)
# 0.76000000000000001
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example, we expect a performance around 0.5 because our data and target labels are randomly sampled.
Nevertheless, we find that we have a significantly better performance &lt;em&gt;even though there is no interesting signal in the data&lt;/em&gt;, because our feature selection is biased towards information of (what will be) the test set.
You can see that the feature selector is fitted using target signal &lt;code&gt;y&lt;/code&gt;, which includes samples that will later be in the test set.&lt;/p&gt;
&lt;p&gt;Instead, you should only fit the data preprocessing steps on the training data &lt;em&gt;after&lt;/em&gt; splitting, and then at inference time &lt;em&gt;apply&lt;/em&gt; (but not refit!) the preprocessing steps:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;# split first
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
# then select features using the training set only
selector = SelectKBest(k=25)
X_train_selected = selector.fit_transform(X_train,y_train)

# fit again a simple logistic regression
lr.fit(X_train_selected,y_train)

# select the same features on the test set, predict, and get the test accuracy:
X_test_selected = selector.transform(X_test)
y_pred = lr.predict(X_test_selected)
accuracy_score(y_test, y_pred)
# 0.52800000000000002
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This now gives the expected performance!
Because there is no useful signal in the training labels, this machine learning classifier is effectively making random guesses for this binary classification problem.&lt;/p&gt;
&lt;h2&gt;Unsupervised feature selection as exception&lt;/h2&gt;
&lt;p&gt;There is a single exception to above procedure.
Unsupervised feature selection procedures do not use the target signal and thus also do not have the same biasing effect towards the test set.
So you may for example remove features that always have the same value, i.e. selection based on (zero) variance.&lt;/p&gt;
&lt;p&gt;Okay, well, let&#39;s test that!&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;from sklearn.feature_selection import VarianceThreshold

selector = VarianceThreshold(threshold=1)  # Normally you&#39;d do some form of scaling
# first select features
X_selected = selector.fit_transform(X)  # y is not used here
# then split
X_selected_train, X_selected_test, y_train, y_test = train_test_split(X_selected, y, test_size=0.25, random_state=42)
print(X.shape, X_selected.shape)

# fit a simple logistic regression
lr = LogisticRegression()
lr.fit(X_selected_train,y_train)

# predict on the test set and get the test accuracy:
y_pred = lr.predict(X_selected_test)
accuracy_score(y_test, y_pred)
# 0.512
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Which is again close to the baseline, as expected!&lt;/p&gt;
&lt;h2&gt;Let the exception be just that: an exception&lt;/h2&gt;
&lt;p&gt;In this dummy example we know that the values of each feature follow the same distribution, since we generated them by sampling from it.
In practice, it may be that some features have a very different scale, which makes selection using a single variance threshold insensible because the variance is dependent on the chosen scale.
If I change a measurement in meters into centimeters, the same data will suddenly have a larger variance!
This is why you would scale your data e.g. using a &lt;code&gt;MinMaxScaler&lt;/code&gt; using a variance threshold (&#34;standard scaling&#34; to zero mean and unit variance is in this case useless because, well... the variance will always be 1).&lt;/p&gt;
&lt;p&gt;If you apply this form of feature scaling before splitting the data, you&#39;ll use &lt;em&gt;global&lt;/em&gt; data statistics, in this case the global minimum and maximum per feature.
However subtle, this is also a form of leakage from the test set into the training pipeline which may lead you to either over- or underestimate your model performance.
A preprocessing step would not leak information if it only requires information from a single sample, i.e. a &#34;row&#34; in the data array.
Scaling instead uses the whole &#34;column&#34; corresponding to feature values.
By scaling features using statistics from the test set as well, you basically do not account for the fact that the data distribution of your test data may be different.
You therefore effectively do not as adequately evaluate the ability of the model to &lt;em&gt;generalize&lt;/em&gt; to unseen data.&lt;/p&gt;
&lt;p&gt;In short, even though unsupervised feature selection does not leak data strictly by itself, this insight is not super useful in practical applications because 1) you&#39;ll likely also need other prior steps that &lt;em&gt;do&lt;/em&gt; leak information and 2) you&#39;ll have to constantly be careful and overthink each each step, which costs effort while unnecessarily being at risk.&lt;/p&gt;
&lt;p&gt;It&#39;s better to just follow the rule of thumb:
avoid leakage by always fitting your data preprocessing and feature selection &lt;em&gt;only&lt;/em&gt; on the &lt;em&gt;training&lt;/em&gt; data.
During testing, only &lt;em&gt;apply&lt;/em&gt; the data preprocessing steps used during the training phase.&lt;/p&gt;
&lt;p&gt;Useful sources:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&#34;https://www.nodalpoint.com/not-perform-feature-selection/&#34;&gt;https://www.nodalpoint.com/not-perform-feature-selection/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://stackoverflow.com/questions/56308116/should-feature-selection-be-done-before-train-test-split-or-after&#34;&gt;https://stackoverflow.com/questions/56308116/should-feature-selection-be-done-before-train-test-split-or-after&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&#34;https://machinelearningmastery.com/data-preparation-without-data-leakage/&#34;&gt;https://machinelearningmastery.com/data-preparation-without-data-leakage/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</description>
        </item>
        
        <item>
            <title>Masking with Boolean arrays in Numpy</title>
            <link>https://www.edwinwenink.xyz/posts/60-masking_with_boolean_arrays_numpy/</link>
            <guid>https://www.edwinwenink.xyz/posts/60-masking_with_boolean_arrays_numpy/</guid>
            <pubDate>Mon, 15 Nov 2021 12:01:10 +0200</pubDate>
            <description>&lt;h2&gt;Use case&lt;/h2&gt;
&lt;p&gt;I regularly encounter situations where I have an array that specifies which elements to keep in another array.
If you for example want to provide batched inputs to a BERT language model as a tensor, you have to pad the input text sequences because the tensor needs to be a square matrix.
BERT uses &lt;em&gt;attention masks&lt;/em&gt; (Boolean arrays) to indicate which elements correspond to actual input tokens and which ones are special tokens such as meaningless padding tokens &lt;code&gt;[PAD]&lt;/code&gt;.
If I use BERT to classify input tokens, I don&#39;t care about classifications on the &lt;code&gt;[PAD]&lt;/code&gt; token, so I want to filter them out using the attention mask.&lt;/p&gt;
&lt;p&gt;Numpy is very convenient for this use case, because it supports using boolean arrays directly as masks.
But before we dive into masking with boolean arrays, let&#39;s briefly discuss Numpy masked arrays.&lt;/p&gt;
&lt;h2&gt;Masked arrays&lt;/h2&gt;
&lt;p&gt;Something that throws me off sometimes is that Numpy has a &lt;a href=&#34;https://numpy.org/doc/stable/reference/maskedarray.generic.html&#34;&gt;masked array&lt;/a&gt; class, but this has a slightly different and specific use case, namely to work with &#34;arrays that may have missing or invalid entries&#34;.
The purpose of this is to be able to use the input array &lt;em&gt;as is&lt;/em&gt;, but exclude the invalid elements from common computations.
A simple example from the &lt;a href=&#34;https://numpy.org/doc/stable/reference/maskedarray.generic.html&#34;&gt;documentation&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; import numpy as np
&amp;gt;&amp;gt;&amp;gt; import numpy.ma as ma
&amp;gt;&amp;gt;&amp;gt; x = np.array([1, 2, 3, -1, 5])
&amp;gt;&amp;gt;&amp;gt; mx = ma.masked_array(x, mask=[0, 0, 0, 1, 0])
&amp;gt;&amp;gt;&amp;gt; mx.mean()
2.75
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this case the &lt;code&gt;1&lt;/code&gt; in the mask indicates that the fourth data point is &lt;em&gt;invalid&lt;/em&gt; (which to me is slightly counter-intuitive because in the example use case above I want to &lt;em&gt;keep&lt;/em&gt; the entries with a &lt;code&gt;1&lt;/code&gt;).
The benefit of the masked array module is that you don&#39;t have to modify the shape of the input array, but in my use case I actually just want to throw away the data I don&#39;t care about.
This is not desirable in cases where you do tensor computations and where the shape of the input must be preserved.&lt;/p&gt;
&lt;h2&gt;Four methods&lt;/h2&gt;
&lt;p&gt;So in our use case we have two arrays, where the second serves as a mask that indicates which elements to keep in the first array.
We can use:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;use &lt;code&gt;numpy.nonzero()&lt;/code&gt; for creating a boolean array&lt;/li&gt;
&lt;li&gt;explicitly cast the masking array as a boolean array&lt;/li&gt;
&lt;li&gt;create a boolean array based on a logical condition&lt;/li&gt;
&lt;li&gt;&lt;code&gt;numpy.where()&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;arr = np.array([1,2,3])
mask = np.array([0,1,0])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Method 1. We essentially want to keep all elements from &lt;code&gt;arr&lt;/code&gt; in the corresponding places where &lt;code&gt;mask&lt;/code&gt; is non-zero:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr[np.nonzero(mask)]
array([2])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Python interprets &lt;code&gt;False&lt;/code&gt; as &lt;code&gt;0&lt;/code&gt; and &lt;code&gt;True&lt;/code&gt; as &lt;code&gt;1&lt;/code&gt;.
E.g. you can do arithmetic on booleans like:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr &amp;gt; 1
array([False,  True,  True])
&amp;gt;&amp;gt;&amp;gt; np.sum(arr &amp;gt; 1)
2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This means &lt;code&gt;nonzero()&lt;/code&gt; can be used to mask an array using arbitrary conditions:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr[ np.nonzero(arr&amp;gt;1)]
array([2, 3])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This could be handy if you instead want to select elements of &lt;code&gt;arr&lt;/code&gt; based on some threshold.
Although of course, you don&#39;t really need to bother with this because you can apply the mask directly:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt; arr[arr&amp;gt;1]
array([2, 3])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Method 2. The same can be achieved with by explicitly casting the mask to a Boolean array:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr[mask.astype(bool)]
array([2])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Method 3. But the most straightforward usage to me is creating the Boolean array based on a logical operator.
Numpy also nicely handles these operations by applying them to each array element:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr[mask != 0]
array([2])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Method 4. If you use &lt;code&gt;numpy.where&lt;/code&gt; with a boolean condition, it is equivalent to using &lt;code&gt;numpy.nonzero()&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr[np.where(mask &amp;gt; 0)]
array([2])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The behavior of &lt;code&gt;numpy.where()&lt;/code&gt; is more general because it allows you to pick an element for array-like &lt;code&gt;x&lt;/code&gt; or &lt;code&gt;y&lt;/code&gt; depending on a Boolean array, where an element from &lt;code&gt;x&lt;/code&gt; is picked when the condition is &lt;code&gt;True&lt;/code&gt;, and &lt;code&gt;y&lt;/code&gt; otherwise.
This could simulate a bit of the behavior of the &lt;code&gt;numpy.maskedarray&lt;/code&gt; class.
E.g. you use the masking array to keep only certain values and set others to &lt;code&gt;NaN&lt;/code&gt; and then use &lt;code&gt;numpy&lt;/code&gt; functions that ignore &lt;code&gt;NaN&lt;/code&gt; values:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; np.where(mask &amp;gt; 0, arr, np.nan)
array([nan,  2., nan])
&amp;gt;&amp;gt;&amp;gt; np.mean(arr_nan)  # This will not give correct results
nan
&amp;gt;&amp;gt;&amp;gt; np.nanmean(arr_nan)  # But this a succesfull operation on the masked array
2.0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that the &lt;code&gt;numpy.where&lt;/code&gt; function expects array-like arguments, but will automatically broadcast the value &lt;code&gt;np.nan&lt;/code&gt; to an array of the correct shape.&lt;/p&gt;
&lt;h2&gt;Multi-dimensional case&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr = np.array([ [1,2,3], [4,5,6] ])
&amp;gt;&amp;gt;&amp;gt; arr
array([[1, 2, 3],
       [4, 5, 6]])
&amp;gt;&amp;gt;&amp;gt; mask = np.array( [[0, 1, 0], [1, 1, 0]])
&amp;gt;&amp;gt;&amp;gt; mask
array([[0, 1, 0],
       [1, 1, 0]])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you apply the masking strategies 1-3 from above, it is good to know that the shape of the input array is not preserved, like with &lt;code&gt;numpy.ma&lt;/code&gt;.
Instead you end up with a list of the preserved elements.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; arr[np.nonzero(mask)]
array([2, 4, 5])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you want to preserve the shape of the input array, you can use &lt;code&gt;numpy.where&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; np.where(mask &amp;gt; 0, arr, np.nan)
array([[nan,  2., nan],
       [ 4.,  5., nan]])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can also provide a unidimensional mask to a multidimensional input array.
For example, in the token classification task mentioned above, BERT will output activations or probabilities over classes for each input token.
Each input sequence thus gives an output with shape &lt;code&gt;(n_tokens, n_classes)&lt;/code&gt;.
If you do batch processing, many of these tokens will be &lt;code&gt;[PAD]&lt;/code&gt;, i.e. we want to mask on the first &#34;token&#34; dimension.
The attention mask in this case will have shape &lt;code&gt;(n_tokens,)&lt;/code&gt;.
Let&#39;s say we have a short sentence with only two tokens, for which we predict fictitious activations over three output classes.
The first token is actual text, the second token is padding.
We can remove the padding tokens as follows:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; a = np.array( [ [2,3,4], [5,6,7] ] )
&amp;gt;&amp;gt;&amp;gt; a.shape
(2, 3)
&amp;gt;&amp;gt;&amp;gt; m = np.array( [1,0] )
&amp;gt;&amp;gt;&amp;gt; m.shape
(2,)
&amp;gt;&amp;gt;&amp;gt; a[np.nonzero(m)]
array([2, 3, 4](2,_3,_4.md))
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Understanding the output of nonzero&lt;/h2&gt;
&lt;p&gt;The output of &lt;code&gt;np.nonzero&lt;/code&gt; can be a bit hard to read because it&#39;s not organized by row indexes, but by dimension:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; np.nonzero(mask)
(array([0, 1, 1], dtype=int64), array([1, 0, 1], dtype=int64))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These two arrays have length three because we have three non-zero elements.
The row index of these three points are [0,1,1] and the column indexes are [1,0,1], which selects the following coordinates:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; np.transpose(np.nonzero(mask))
array([[0, 1],
       [1, 0],
       [1, 1]], dtype=int64)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Which is (by definition) the output of &lt;code&gt;np.argwhere&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-python&#34;&gt;&amp;gt;&amp;gt;&amp;gt; np.argwhere(mask)
array([[0, 1],
       [1, 0],
       [1, 1]], dtype=int64)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However, you can&#39;t use this as index (which goes dimension-wise) so shouldn&#39;t be used for masking purposes.&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>Digest October 2021</title>
            <link>https://www.edwinwenink.xyz/posts/digest-2021-10/</link>
            <guid>https://www.edwinwenink.xyz/posts/digest-2021-10/</guid>
            <pubDate>Sun, 31 Oct 2021 19:58:30 +0100</pubDate>
            <description>&lt;p&gt;Update: Edo made a &lt;a href=&#34;https://open.spotify.com/playlist/6rwqkIKVp4zfw1a4wRTygv?si=0aa56643713c472e&amp;amp;nd=1&#34;&gt;Spotify playlist&lt;/a&gt; of this digest.&lt;/p&gt;
&lt;iframe src=&#34;https://open.spotify.com/embed/playlist/6rwqkIKVp4zfw1a4wRTygv?utm_source=generator&amp;theme=0&#34; width=&#34;100%&#34; height=&#34;380&#34; frameBorder=&#34;0&#34; allowfullscreen=&#34;&#34; allow=&#34;autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture&#34;&gt;&lt;/iframe&gt;

&lt;p&gt;I&#39;ve gotten to know &lt;em&gt;Men I Trust&lt;/em&gt; a while back and what a luck, they just dropped a new album in August (yes, I skipped two months worth of digest, so buckle up).
For this next song called &lt;em&gt;Organon&lt;/em&gt;, it&#39;s as if you start playing a record, but then the room gets hot and the records start melting. But not in a bad way. You kind of dig it and pour yourself a red wine.&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube -m90XiNil7M &amp;gt;}}&lt;/p&gt;
&lt;p&gt;The new album of &lt;em&gt;Men I Trust&lt;/em&gt; is great, but I&#39;ve become somewhat addicted to their old album &lt;em&gt;Headroom&lt;/em&gt;.
Take for example this song with ephemeral vocals, but a slowly emerging thick arpeggio that gives it a nice drive:&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube 5h6wu28dIB4 &amp;gt;}}&lt;/p&gt;
&lt;p&gt;Okay, staying a bit in the same vibe, give this beautifully sad song a listen.
Put this on your &#34;music for break ups&#34; playlist.
Actually, you can just go ahead and put the whole album on that list.&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube gYUB0O0No0A &amp;gt;}}&lt;/p&gt;
&lt;p&gt;In the &lt;a href=&#34;https://www.edwinwenink.xyz/posts/digest-2021-07&#34;&gt;previous digest&lt;/a&gt;, I included a latest BADBADNOTGOOD single.
This month the full album dropped and it&#39;s worth the listen.
Here is another gem (the video is again a piece of art in its own right):&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube LRDmyRJsPwM &amp;gt;}}&lt;/p&gt;
&lt;p&gt;When this song was released all the way back in April I deliberately chose not to include it in my digest.
Well, I was an absolute idiot!
This song gets better with every listen.
There&#39;s actually no sound in this song that&#39;s not quite unique.
It&#39;s as if the instruments go off the rails sometimes, yet it&#39;s never off key and quite perfect.
The drums are minimalistic, yet if you listen you&#39;ll notice all these little shifts and breaks.
The vocals go from low, warm and fuzzy to this absolutely crazy moment (e.g. from 2:30 on) where it sounds as if two people are singing at the same time.&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube p46Tm9-7i7E &amp;gt;}}&lt;/p&gt;
&lt;p&gt;The next one is not new, but scratches all the right itches for me.
I have a huge soft spot for ghostly female vocals over darker sounding music, like techno or metal.
The apotheosis reminds me of Gesaffelstein or Jon Hopkins, and the visuals of the clip are brilliant:&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube 29qMlvTXhZI &amp;gt;}}&lt;/p&gt;
&lt;p&gt;Okay, we&#39;re approaching the moment where the faint of heart may call it quits.
The next two are loud.
Spiritbox recently dropped a new album.
Holy Roller and Constance are both great songs released earlier as singles.
I haven&#39;t decided yet, but I think the opening song may actually be my favorite (unfortunately no clip):&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube iXY93aMLG7s &amp;gt;}}&lt;/p&gt;
&lt;p&gt;Amenra dropped a new album with Dutch lyrics a few months back.
Listening to Amenra has a spiritual quality to it, it&#39;s condensed catharsis.
Colin screams like he&#39;s leaving his body.
Don&#39;t afraid to put up the volume :-)&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube rBTqCIgpJ6s &amp;gt;}}&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>Writing, not collecting</title>
            <link>https://www.edwinwenink.xyz/posts/59-writing_not_collecting/</link>
            <guid>https://www.edwinwenink.xyz/posts/59-writing_not_collecting/</guid>
            <pubDate>Tue, 12 Oct 2021 12:01:10 +0200</pubDate>
            <description>&lt;p&gt;I&#39;ve written a bit about my &lt;a href=&#34;https://www.edwinwenink.xyz/series/workflow/&#34;&gt;note-taking&lt;/a&gt; on this domain because I think systems of organizing knowledge are quintessential for anyone that is a &lt;em&gt;learner&lt;/em&gt; or &lt;em&gt;knowledge&lt;/em&gt; worker.
To be frank, I find it quite ridiculous that my university education did not teach me how to manage my knowledge base, not even basic academic skills like managing references efficiently.
I&#39;ve too often repeated the pattern of following a course, learning for an exam, and not being able to reproduce everything even six months later.
(I&#39;m painfully aware of the &#34;forgetting&#34; part, as I took a decade of university &lt;a href=&#34;https://www.edwinwenink.xyz/etc/courses/&#34;&gt;courses&lt;/a&gt;...)&lt;/p&gt;
&lt;p&gt;Nobody has a perfect memory, so I don&#39;t blame myself for not recollecting everything I&#39;ve been taught throughout the years.
But the thing is that for each course and for each paper, I &lt;em&gt;did&lt;/em&gt; make extensive notes to compensate for my human limitations.
All these notes are scribbled down in barely organized old notebooks or in docx files (!), organized in folders scattered across various back-up drives.
They &lt;em&gt;are&lt;/em&gt; recorded, yet I do not &lt;em&gt;remember&lt;/em&gt;.
How come?&lt;/p&gt;
&lt;p&gt;This little example shows a core paradox of note-taking.
I took notes to &lt;em&gt;record&lt;/em&gt; insights and knowledge in order to &lt;em&gt;remember&lt;/em&gt;.
But I had no productive way of &lt;em&gt;applying&lt;/em&gt; the recorded knowledge and hence, I &lt;em&gt;forgot&lt;/em&gt;.
My old notes are locked in a dead past, instead of being a living memory.&lt;/p&gt;
&lt;p&gt;This points to perhaps the most dangerous pitfall of note-taking.
It&#39;s very tempting to convince yourself you are &lt;em&gt;learning&lt;/em&gt; just because you are writing down - in the sense of passively recording - what someone else says or writes.
What we ultimately should care about is being able to use our knowledge to produce something new, whatever that may be.
To not merely reproduce you must understand the material.
And understanding requires application, a hermeneutic principle that particularly Gadamer worked out extensively.
If you really want to measure your level of understanding, you should try to apply or explain something to yourself or someone else.&lt;/p&gt;
&lt;p&gt;I distill this insight into a very simple principle for note-taking:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;notes are things where I explain something to myself&lt;/em&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This also means, somewhat counterintuitively, that note-taking is not about &lt;em&gt;collecting&lt;/em&gt; notes!
The note is a tool for thinking.
It is about tickling the primordial soup of the archive to stimulate yourself towards producing something, anything really.
It is &lt;em&gt;to write&lt;/em&gt; in the active sense of the word.&lt;/p&gt;
&lt;p&gt;The Zettelkästen system embodies this change in mindset.
Instead of focusing on folder hierarchies, organizing, and categorizing, it focuses on &lt;em&gt;interlinking&lt;/em&gt; ideas and &lt;em&gt;traversing&lt;/em&gt; the network of notes.
This allows you to enter the archive at any place and follow traces, of which some may open very surprising lines of thought!&lt;/p&gt;
&lt;p&gt;I committed to a flat file directory for &lt;em&gt;all&lt;/em&gt; my notes.
I&#39;ve also stopped using the &lt;a href=&#34;https://www.edwinwenink.xyz/posts/43-notes_tagging/&#34;&gt;tagging system&lt;/a&gt;.
Rather than helping me find and create ideas, I found myself managing and refining the tags.
That is, even though the idea was about interlinking, it &lt;em&gt;de facto&lt;/em&gt; ended up as a futile attempt at organization.
This type of organization is simply not scalable and future proof.
In a few years, you&#39;ll change your tagging conventions and will have to battle the desire to revisit all your other notes to update the archive.
The same holds with folder organization: for another project, you&#39;ll prefer another organization and you&#39;ll be dissatisfied with your old solution.
You&#39;ll probably end up with a new directory, copying old notes over and duplicating them.
If you notice this urge to organize, take a step back and &lt;em&gt;do nothing&lt;/em&gt;!&lt;/p&gt;
&lt;p&gt;This desire to archive and organize comes from the fear of &lt;em&gt;losing&lt;/em&gt; notes.
But as we&#39;ve said before, recording something does not prevent you from losing it.
You lose it when you don&#39;t actively use it.
If you mainly rely on interlinking notes for finding notes, it can indeed be that there will be many ghost notes without incoming links.
But this probably means that what was written in the note, wasn&#39;t that useful after all!
It&#39;s OK!
On the other hand, notes that are productive will solidify their position in the rhizomatic network, because increasingly many paths lead to and from them.
It&#39;s an evolutionary process.
In the end, you&#39;ll actually remember what&#39;s in these notes because their insights are used and engage with other ideas.&lt;/p&gt;
&lt;p&gt;I know it&#39;s scary.
I know it&#39;s hard.
I still succumb to &lt;em&gt;Archive Fever&lt;/em&gt; once in a while.
But when you do too, you must explain to yourself and repeat as a feverish mantra:&lt;/p&gt;
&lt;p&gt;Writing, not collecting...&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Writing, not collecting.&lt;/em&gt;&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>Site update: Breadcrumbs, taxonomies, paginators</title>
            <link>https://www.edwinwenink.xyz/posts/58-breadcrumbs_taxonomies_paginators/</link>
            <guid>https://www.edwinwenink.xyz/posts/58-breadcrumbs_taxonomies_paginators/</guid>
            <pubDate>Mon, 11 Oct 2021 23:34:31 +0200</pubDate>
            <description>&lt;p&gt;I have just added some new features to this website.&lt;/p&gt;
&lt;h2&gt;Breadcrumb navigation&lt;/h2&gt;
&lt;p&gt;This took a bit of puzzling.
To get all the breadcrumbs, you essentially want to parse all the URL components of the current URL relate to the base domain.
The Hugo &lt;code&gt;split&lt;/code&gt; function returns an empty head and tail, which I needed to filter out.&lt;/p&gt;
&lt;p&gt;I wanted to keep my regular navigation bar next to the breadcrumb navigation.
This means that if I visit let&#39;s say the &#34;about&#34; page, that &lt;em&gt;both&lt;/em&gt; the breadcrumb and regular navigation bar show the &#34;about&#34; page.
As a nice twist, I therefore remove a reference from the regular menu if it is already mentioned in the breadcrumb navigation (i.e. if it&#39;s the current page).&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-html&#34;&gt;&amp;lt;div id=&amp;quot;breadcrumbs&amp;quot;&amp;gt;
    &amp;lt;!-- Remove empty first and last element --&amp;gt;
    {{ $url  := .RelPermalink }}
    {{ $components := last 2 (split (delimit (split .RelPermalink &amp;quot;/&amp;quot;) &amp;quot;,&amp;quot; &amp;quot;&amp;quot;) &amp;quot;,&amp;quot; ) }}
    {{ $counter := 0 }}

    &amp;lt;!-- The breadcrumbs --&amp;gt;
    {{ range $components }}
        {{ $counter = add $counter 1 }}
        &amp;lt;!-- Following line is strictly not necessary anymore
            because I filter out the empty elements above --&amp;gt;
        {{ if gt (len . ) 0 }}
            {{ if eq $counter (len $components) }}
                &amp;gt; &amp;lt;a href=&amp;quot;{{ $url }}&amp;quot;&amp;gt;{{ humanize . }}&amp;lt;/a&amp;gt;
            {{ else }}
                &amp;gt; &amp;lt;a href=&amp;quot;/{{ . }}&amp;quot;&amp;gt;{{ humanize . }}&amp;lt;/a&amp;gt;
            {{ end }}
        {{ end }}
    {{ end }}
    | 
 &amp;lt;!-- Navigation Pages --&amp;gt;
    {{ range .Site.Menus.main }}
        {{ if ne $url .URL }}
            &amp;lt;a href=&amp;quot;{{ .URL }}&amp;quot;&amp;gt;{{ .Name }}&amp;lt;/a&amp;gt;&amp;amp;nbsp;&amp;amp;nbsp;
        {{ end }}
    {{ end }}
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;{{ define &#34;main&#34; }} and baseof.html&lt;/h2&gt;
&lt;p&gt;I started this website without understanding much about ... anything really.
By now I have a better grip of the Hugo language.
I initially separately defined a header and footer partial in all my templates, which amounts to a lot of unnecessary repetition.
Hugo avoids this bad pattern by allowing you to define a &lt;code&gt;baseof.html&lt;/code&gt; template, as such:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-html&#34;&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang=&amp;quot;en&amp;quot;&amp;gt;
    {{ partial &amp;quot;header.html&amp;quot; . }}
    &amp;lt;body&amp;gt;
        &amp;lt;div id=&amp;quot;content&amp;quot;&amp;gt;
        {{- block &amp;quot;main&amp;quot; . }}{{- end -}}
        &amp;lt;/div&amp;gt;
        {{ partial &amp;quot;footer.html&amp;quot; . }}
    &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we no longer have to repeat the header and footer templates.
Instead, other templates are responsible for filling in the main block with &lt;code&gt;{{ define &#34;main&#34; }} ... {{ end }}&lt;/code&gt;.
The next section shows a full example.&lt;/p&gt;
&lt;h2&gt;Section index pages&lt;/h2&gt;
&lt;p&gt;Having proper index pages for sections is not hard to do at all and yet, I never had them.
This is because I did not fully understand how Hugo treats &lt;code&gt;_index.md&lt;/code&gt; pages in the content organization.
But once I did understand, I still didn&#39;t get them to work.
Turns out I had &lt;code&gt;disableKinds&lt;/code&gt; enabled for sections in my &lt;code&gt;config.toml&lt;/code&gt;.
I can&#39;t remember at all that I enabled this and it took way too long to figure out this prevented Hugo from generating index pages.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-html&#34;&gt;{{ define &amp;quot;main&amp;quot; }}

{{ partial &amp;quot;paginator.html&amp;quot; . }}

&amp;lt;div&amp;gt;
    {{ .Content }}
    &amp;lt;ul&amp;gt;
    {{ range .Paginator.Pages }}
    &amp;lt;h1&amp;gt;&amp;lt;a href=&amp;quot;{{ .Page.Permalink }}&amp;quot;&amp;gt;{{ .Page.Title }}&amp;lt;/a&amp;gt;&amp;lt;/h1&amp;gt;
        {{ .Content }}
    {{ end }}
    &amp;lt;/ul&amp;gt;
&amp;lt;/div&amp;gt;

{{ partial &amp;quot;paginator.html&amp;quot; . }}

{{ end }}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In addition to the &lt;a href=&#34;https://www.edwinwenink.xyz/archives&#34;&gt;archive&lt;/a&gt;, which has a template of its own, the &lt;a href=&#34;https://www.edwinwenink.xyz/posts/&#34;&gt;posts&lt;/a&gt; now have their own page where you can scroll through all the posts.&lt;/p&gt;
&lt;h2&gt;Paginator&lt;/h2&gt;
&lt;p&gt;As you can also see in the above snippet, I also introduced a paginator in the section index pages.
You can use the default Hugo paginator with &lt;code&gt;{{ template &#34;_internal/pagination.html&#34; . }}&lt;/code&gt;, but I built a simple custom paginator instead:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-html&#34;&gt;{{ $paginator := .Paginator }}
{{ if gt $paginator.TotalPages 1 }}
    &amp;lt;div style=&amp;quot;text-align: center; font-size: 1.5em; margin: 1em;&amp;quot;&amp;gt;
        &amp;lt;!--{{ template &amp;quot;_internal/pagination.html&amp;quot; . }}--&amp;gt;

        &amp;lt;!-- First page. --&amp;gt;
          &amp;lt;a  href=&amp;quot;{{ $paginator.First.URL }}&amp;quot;&amp;gt; 0 &amp;lt;/a&amp;gt;
        &amp;lt;/li&amp;gt;

      &amp;lt;!-- Previous page. --&amp;gt;
        {{ if $paginator.HasPrev }}
          &amp;lt;a href=&amp;quot;{{ $paginator.Prev.URL }}&amp;quot;&amp;gt;&amp;lt;--&amp;lt;/a&amp;gt;
        {{ end }}

        {{ range after 1 $paginator.Pagers }}
            {{ if eq . $paginator }}
                [ {{ .PageNumber }} ]
            {{ end  }}
        {{ end }}

       &amp;lt;!-- Next page. --&amp;gt;
        {{ if $paginator.HasNext }}
        &amp;lt;a href=&amp;quot;{{ $paginator.Next.URL }}&amp;quot;&amp;gt;--&amp;gt;&amp;lt;/a&amp;gt;
        {{ end }}

        &amp;lt;!-- Last page. --&amp;gt;
          &amp;lt;a  href=&amp;quot;{{ $paginator.Last.URL }}&amp;quot;&amp;gt; N &amp;lt;/a&amp;gt;
        &amp;lt;/li&amp;gt;
    &amp;lt;/div&amp;gt;
{{ end  }}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The paginator doesn&#39;t appear if there is only one page.
The &#34;next&#34; arrow also does not show when there&#39;s no next page.
Be aware that I used inline css styling, because I&#39;m bothered by my browsers/Hugo not picking up changes in the static style.css file in time.&lt;/p&gt;
&lt;h2&gt;Series taxonomy&lt;/h2&gt;
&lt;p&gt;In the &lt;a href=&#34;https://www.edwinwenink.xyz/posts/57-ai_ethics_tool_landscape/&#34;&gt;AI Ethics Tool Landscape&lt;/a&gt; I heavily made use of taxonomies, which made me realize I should also do this on my personal website.
I added a new &lt;a href=&#34;https://www.edwinwenink.xyz/series/&#34;&gt;series&lt;/a&gt; taxonomy.
I also wrote a &lt;code&gt;terms.html&lt;/code&gt; template that does not only lists the taxonomy terms, but also counts how often they occur:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-html&#34;&gt;{{ define &amp;quot;main&amp;quot; }}

&amp;lt;div&amp;gt;
   &amp;lt;h1&amp;gt;{{ .Title }}&amp;lt;/h1&amp;gt;
    {{ .Content }}
    {{ range sort .Data.Terms }}
        &amp;lt;li&amp;gt;&amp;lt;a href=&amp;quot;{{ .Page.Permalink }}&amp;quot;&amp;gt;{{ upper .Page.Title }}&amp;lt;/a&amp;gt; ({{ .Count }})&amp;lt;/li&amp;gt;
    {{ end }}
&amp;lt;/div&amp;gt;

{{ end }}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Date of last modification&lt;/h2&gt;
&lt;p&gt;This is a really cool Hugo feature I wasn&#39;t aware of before.
If you keep your Hugo site in a git repo (which you should anyways), the Hugo build can pick up the latest commit made on the current file in order to show the date of the last edit.
It&#39;s as simple as:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&#34;language-html&#34;&gt;&amp;lt;aside&amp;gt; 
  Last modified on {{ .Lastmod.Format &amp;quot;2 January, 2006&amp;quot;}}.
&amp;lt;/aside&amp;gt;
&lt;/code&gt;&lt;/pre&gt;</description>
        </item>
        
        <item>
            <title>Introducing the AI Ethics Tool Landscape</title>
            <link>https://www.edwinwenink.xyz/posts/57-ai_ethics_tool_landscape/</link>
            <guid>https://www.edwinwenink.xyz/posts/57-ai_ethics_tool_landscape/</guid>
            <pubDate>Tue, 24 Aug 2021 09:35:29 +0200</pubDate>
            <description>&lt;p&gt;Many companies that employ AI by now recognize the need for what the European Commission calls an &#34;ecosystem of trust&#34; &lt;sup id=&#34;fnref:7&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:7&#34;&gt;7&lt;/a&gt;&lt;/sup&gt;.
This has resulted in a large amount of (ethical) principle statements for the usage of AI.
These statements are often to a large degree inspired by pre-existing guidelines and principles, such as the European Commission&#39;s &lt;em&gt;Ethics Guidelines for Trustworthy AI&lt;/em&gt; &lt;sup id=&#34;fnref:9&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:9&#34;&gt;9&lt;/a&gt;&lt;/sup&gt; or the SAP guiding principles for AI &lt;sup id=&#34;fnref:10&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:10&#34;&gt;10&lt;/a&gt;&lt;/sup&gt;.
However, there are doubts about the effectiveness of these guidelines.
A main challenge for the coming years is to effectively &lt;em&gt;operationalise&lt;/em&gt; AI policy.
In this post I introduce an open source project that hopefully makes a step in the right direction by listing available tools to support the ethical development of AI.&lt;/p&gt;
&lt;p&gt;The tools are described and organized in the &lt;a href=&#34;https://edwinwenink.github.io/ai-ethics-tool-landscape/&#34;&gt;AI Ethics Tooling Landscape&lt;/a&gt;.
The website itself and the corresponding &lt;a href=&#34;https://github.com/EdwinWenink/ai-ethics-tool-landscape/blob/main/README.html&#34;&gt;README&lt;/a&gt; explains how the website works and how to contribute to it.&lt;/p&gt;
&lt;h2&gt;Where guidelines fall short&lt;/h2&gt;
&lt;p&gt;AlgorithmWatch initiated an &lt;em&gt;AI Ethics Guidelines Global Inventory&lt;/em&gt;
&lt;sup id=&#34;fnref:1&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:1&#34;&gt;1&lt;/a&gt;&lt;/sup&gt; in which more than 160 AI ethics guidelines have been
collected. The organizers of this initiative noted that the overwhelming
majority of guidelines contained general promises, for example to not
used biased data, but no concrete &#34;recommendations or examples of how to
operationalise the principles&#34; &lt;sup id=&#34;fnref:3&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:3&#34;&gt;3&lt;/a&gt;&lt;/sup&gt;. Evaluating the
guidelines in this repository a year later, AlgorithmWatch states that
often &#34;it is a matter of weaving together principles without a clear
view on how they are to be applied in practice. Thus, many guidelines
are not suitable as a tool against potential harmful uses of AI-based
technologies and will probably fail in their attempt to prevent damage.
The question arises whether guidelines that can neither be applied nor
enforced are not more harmful than having no ethical guidelines at all.
Ethics guidelines should be more than a PR tool for companies and
governments&#34; &lt;sup id=&#34;fnref:2&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:2&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;. Because most ethical guidelines do
not indicate &#34;an oversight or enforcement mechanism&#34;
&lt;sup id=&#34;fnref2:3&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:3&#34;&gt;3&lt;/a&gt;&lt;/sup&gt; they risk being rather toothless &#34;paper tigers.&#34;
Ethics does by nature not include any mechanisms for its own enforcement
and the active promotion of ethics guidelines is even seen by some as an
attempt to preemptively stifle the development of more rigid AI
legislation that &lt;em&gt;does&lt;/em&gt; enforce compliance &lt;sup id=&#34;fnref:8&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:8&#34;&gt;8&lt;/a&gt;&lt;/sup&gt;.
This suspicion that companies use ethics guidelines as a PR tool can
lead to accusations of &lt;em&gt;ethics washing&lt;/em&gt; &lt;sup id=&#34;fnref:5&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:5&#34;&gt;5&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;
&lt;h2&gt;A call for operationalisation&lt;/h2&gt;
&lt;p&gt;This shows that despite a proliferation of principle statements --- the
&#34;what&#34; of ethical AI --- there is not enough focus on the &#34;how&#34; of
ethical AI. Papers that review the operationalisation of AI principles point out that currently these principles do &#34;not yet bring
about actual change in the design of algorithmic systems&#34; &lt;sup id=&#34;fnref:11&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:11&#34;&gt;11&lt;/a&gt;&lt;/sup&gt;.
In a similar vein, Hagendorff points out that &#34;it is
noteworthy that almost all guidelines suggest that technical solutions
exist for many of the problems described. Nevertheless, there are only
two guidelines which contain genuinely technical explanations at all ---
albeit only very sparsely&#34; &lt;sup id=&#34;fnref2:8&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:8&#34;&gt;8&lt;/a&gt;&lt;/sup&gt;. Equally stern,
Canca concludes that &#34;the multiplication of these mostly vaguely
formulated principles has not proven to be helpful in guiding practice.
Only by operationalizing AI principles for ethical practice can we help
computer scientists, developers, and designers to spot and think through
ethical issues and recognize when a complex ethical issue requires
in-depth expert analysis&#34; &lt;sup id=&#34;fnref:6&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:6&#34;&gt;6&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;
&lt;p&gt;These citations from review papers show that there are serious doubts,
to put it mildly, about the effectiveness of guidelines. These
guidelines are great public statements, but how do we make sure they
actually impact the work being done in professional AI communities? A
main challenge for AI ethics and ethical AI in the coming years is
therefore &#34;to build tangible bridges between abstract values and
technical implementations, as long as these bridges can be reasonably
constructed&#34; &lt;sup id=&#34;fnref3:8&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:8&#34;&gt;8&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;
&lt;h2&gt;Bridging the gap&lt;/h2&gt;
&lt;p&gt;This call for concretisation and operationalisation of AI principles
does not mean, however, that AI principles can always and
straightforwardly be technically implemented in a tool or computer
program.
This tension between abstract principles and concrete tools requires thoughtful navigation.
From the perspective of principles, there is a strong call to make them as concrete as possible so that they can
be used by the professionals actually creating AI applications. In this
context, Hagendorff calls for a &#34;microethics&#34; &lt;sup id=&#34;fnref4:8&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:8&#34;&gt;8&lt;/a&gt;&lt;/sup&gt;
that engages with technical details, such as the way algorithms are
designed, or how data is used throughout a machine learning pipeline.
From the perspective of existing tools and techniques, it should instead
be emphasized that they are not &#34;plug-and-play&#34; solutions to make an AI
application ethical. Instead, appropriate use of these tools requires an
ethical sensitivity, with attention to the context in which an AI
technique is embedded and used. For example, if you use a fairness tool,
which definition of fairness is used and is this definition appropriate
given the type of application you are developing?&lt;/p&gt;
&lt;h2&gt;The AI Ethics Tool Landscape&lt;/h2&gt;
&lt;p&gt;To these ends, I did an explorative study of the available tools and techniques for ethical AI.
The target audience that would use these tools are developers, so I
wanted to tailor the format in which I presented my insights to
developers. The majority of the tools are technical, but the value
&#34;accountability&#34; includes non-technical tools, that nevertheless meet
the criterion that they provide hands-on guidance for developers to
engage with ethical AI. Instead of writing a large document on these
tools --- which no developer would ever read --- I decided to program a
website from scratch in the style of a &lt;em&gt;wiki&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The website is called the &lt;a href=&#34;https://edwinwenink.github.io/ai-ethics-tool-landscape/&#34;&gt;AI Ethics Tooling Landscape&lt;/a&gt; and is set up as an open source project.
The website and corresponding &lt;a href=&#34;https://github.com/EdwinWenink/ai-ethics-tool-landscape/blob/main/README.html&#34;&gt;README&lt;/a&gt; explains how the website works and how to contribute to it.
Specifically, because the project content is completely based on simple text files that are automatically parsed, little to no technical know-how is required to contribute content.&lt;/p&gt;
&lt;p&gt;Each tool is placed in a conceptual taxonomy, which I based on 1)
existing typologies and taxonomies for categorizing (machine learning)
tools &lt;sup id=&#34;fnref2:11&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:11&#34;&gt;11&lt;/a&gt;&lt;/sup&gt;&lt;sup id=&#34;fnref:4&#34;&gt;&lt;a class=&#34;footnote-ref&#34; href=&#34;#fn:4&#34;&gt;4&lt;/a&gt;&lt;/sup&gt;, 2) insights from my study of
e.g. explainability and fairness, 3) things that are very practical to
know for developers, such as the programming language of the tool or
which frameworks are used. For example, Morley et al. used a matrix with
ethical values on the x-axis and the development stage in which a
technique applies on the y-axis. Similarly, the wiki categorizes tools
by the &lt;em&gt;value&lt;/em&gt; they support (accountability, explainability, fairness,
privacy, security) and the &lt;em&gt;stage&lt;/em&gt; in which they are useful (design
phase, preprocessing, in-processing, post-processing). I fine-tuned the conceptual taxonomy incrementally based on feedback from developers.
Morley et al. use more stages, but this results in
an extremely sparse matrix. Based on feedback that the stages were
indeed a bit too complicated, I came to the current broader stage
categories, which are also used in the &lt;code&gt;fairlearn&lt;/code&gt; tool.&lt;/p&gt;
&lt;p&gt;However, due to the digital design of the website, I was not limited to
a 2D matrix. Tools are also categorized on the following properties:
whether they are model-agnostic or -specific; which type of data the
tool handles; which type of explanation is supported (if applicable);
which type of fairness is supported (if applicable); which programming
framework is compatible (e.g. PyTorch); which programming languages are
supported; and which machine learning tasks are relevant.&lt;/p&gt;
&lt;p&gt;An interesting observation is that the tooling landscape is not
uniformly distributed. Significantly more technical tools are available
for the values explainability and fairness than for privacy and
security, which reflects that the research field on topics like
differential privacy and adversarial AI are relatively young.&lt;/p&gt;
&lt;p&gt;At the time of writing, the website project contains 41
custom-made tool entries. Each of these entries contains metadata to
categorize the tool, as well as my description of the tool with relevant
information. All values, stages, explanation types, and fairness types
have their own guiding descriptions as well.&lt;/p&gt;
&lt;div class=&#34;footnote&#34;&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li id=&#34;fn:1&#34;&gt;
&lt;p&gt;AlgorithmWatch. AI Ethics Guidelines Global Inventory. url: &lt;a href=&#34;https://inventory.algorithmwatch.org/&#34;&gt;https://inventory.algorithmwatch.org/&lt;/a&gt; (visited on 03/16/2021).&amp;#160;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref:1&#34; title=&#34;Jump back to footnote 1 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:2&#34;&gt;
&lt;p&gt;AlgorithmWatch. In the realm of paper tigers - exploring the failings of AI ethics guidelines. Apr. 28, 2020. url: &lt;a href=&#34;https://algorithmwatch.org/en/ai-ethics-guidelines-inventory-upgrade-2020/&#34;&gt;https://algorithmwatch.org/en/ai-ethics-guidelines-inventory-upgrade-2020/&lt;/a&gt; (visited on 08/04/2021)&amp;#160;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref:2&#34; title=&#34;Jump back to footnote 2 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:3&#34;&gt;
&lt;p&gt;AlgorithmWatch. Launch of our &#39;AI Ethics Guidelines Global Inventory&#39;. Apr. 9, 2019. url: &lt;a href=&#34;https://algorithmwatch.org/en/launch-of-our-ai-ethics-guidelines-global-inventory/&#34;&gt;https://algorithmwatch.org/en/launch-of-our-ai-ethics-guidelines-global-inventory/&lt;/a&gt; (visited on 08/04/2021).&amp;#160;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref:3&#34; title=&#34;Jump back to footnote 3 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref2:3&#34; title=&#34;Jump back to footnote 3 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:4&#34;&gt;
&lt;p&gt;Alejandro Barredo Arrieta et al. &#34;Explainable Artificial Intelligence (XAI): Concepts, taxonomies, opportunities and challenges toward responsible AI&#34;. In: Information Fusion 58 (2020), pp. 82-115. doi: &lt;a href=&#34;https://doi&#34;&gt;https://doi&lt;/a&gt;.
org/10.1016/j.inffus.2019.12.012.&amp;#160;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref:4&#34; title=&#34;Jump back to footnote 4 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:5&#34;&gt;
&lt;p&gt;Elettra Bietti. &#34;From Ethics Washing to Ethics Bashing: A View on Tech Ethics from within Moral Philosophy&#34;. In: Proceedings of the 2020 Conference on Fairness, Accountability, and Transparency. FAT* &#39;20. Barcelona, Spain: Association for Computing Machinery, Jan. 2020, pp. 210-219. doi: 10.1145/3351095.3372860.&amp;#160;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref:5&#34; title=&#34;Jump back to footnote 5 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:6&#34;&gt;
&lt;p&gt;Cansu Canca. &#34;Operationalizing AI Ethics Principles&#34;. In: Commun. ACM 63.12 (Nov. 2020), pp. 18-21. doi: 10.1145/3430368.&amp;#160;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref:6&#34; title=&#34;Jump back to footnote 6 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:7&#34;&gt;
&lt;p&gt;European Commission. White Paper On Artificial Intelligence - A European approach to excellence and trust. Tech. rep. Brussels: European Commission, 2020, p. 27.&amp;#160;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref:7&#34; title=&#34;Jump back to footnote 7 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:8&#34;&gt;
&lt;p&gt;Thilo Hagendorff. &#34;The Ethics of AI Ethics: An Evaluation of Guidelines&#34;. In: Minds and Machines 30.1 (2020), pp. 99-120. doi: 10.1007/s11023-020-09517-8.&amp;#160;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref:8&#34; title=&#34;Jump back to footnote 8 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref2:8&#34; title=&#34;Jump back to footnote 8 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref3:8&#34; title=&#34;Jump back to footnote 8 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref4:8&#34; title=&#34;Jump back to footnote 8 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:9&#34;&gt;
&lt;p&gt;High-Level Expert Group on Artificial Intelligence. The European Commission&#39;s high-level expert group on Artificial Intelligence: Ethics guidelines for trustworthy AI. Tech. rep. European Commission, Apr. 8, 2019, pp. 1-39.&amp;#160;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref:9&#34; title=&#34;Jump back to footnote 9 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:10&#34;&gt;
&lt;p&gt;Corinna Machmeier. SAP&#39;s Guiding Principles for Artificial Intelligence. Sept. 18, 2018. url: &lt;a href=&#34;https://news.sap.com/2018/09/sap-guiding-principles-for-artificial-intelligence/&#34;&gt;https://news.sap.com/2018/09/sap-guiding-principles-for-artificial-intelligence/&lt;/a&gt; (visited on 08/04/2021).&amp;#160;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref:10&#34; title=&#34;Jump back to footnote 10 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&#34;fn:11&#34;&gt;
&lt;p&gt;Jessica Morley et al. &#34;From What to How: An Initial Review of Publicly Available AI Ethics Tools, Methods and Research to Translate Principles into Practices?. In: Science and Engineering Ethics 26.4 (2020), pp. 2141- 2168. doi: 10.1007/s11948-019-00165-5.&amp;#160;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref:11&#34; title=&#34;Jump back to footnote 11 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;a class=&#34;footnote-backref&#34; href=&#34;#fnref2:11&#34; title=&#34;Jump back to footnote 11 in the text&#34;&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;</description>
        </item>
        
        <item>
            <title>Digest July 2021</title>
            <link>https://www.edwinwenink.xyz/posts/digest-2021-07/</link>
            <guid>https://www.edwinwenink.xyz/posts/digest-2021-07/</guid>
            <pubDate>Sat, 31 Jul 2021 11:00:00 +0200</pubDate>
            <description>&lt;p&gt;This month BADBADNOTGOOD released a single in anticipation of their upcoming album Talk Memory (dropping beginning of October).
The track takes you on a 9 minute long gloomy journey that stays dynamic and tense from beginning to end.
It is sometimes hard to distinguish the instruments from dark electro and the solos are at no point middle-of-the-road.
The rather enigmatic video clip features DJ Steves.
Piece of art, really.&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube gMEto80a2HY &amp;gt;}}&lt;/p&gt;
&lt;p&gt;The best discovery of this month is the new collaboration between guitarist Blake Mills and bassist Pino Palladino, the full-length album &#34;Notes with Attachment&#34;.
This album is so unique and it gets better with every listen.
The Tiny Desk concert is a great teaser for the whole album and it&#39;s fascinating to get to see the artistry from up close, especially because the instruments sound quite alien at times.
There&#39;s sections where I wouldn&#39;t have believed I&#39;m listening to a saxophone.
Blake Mills is the kind of guitarist where every note is supposed to be there, condensed to perfection.
That holds generally for this whole album.&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube a-V77_moZYw &amp;gt;}}&lt;/p&gt;
&lt;p&gt;I watched Bo Burnham&#39;s new musical comedy special &lt;em&gt;Inside&lt;/em&gt; last week and it was brilliant.
We see Burnham&#39;s turn into a Jesus figure during a year inside in his own guest house, musically addressing the ins and outs of a life forced to be lived online and his declining mental health.&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube k1BneeJTDcU &amp;gt;}}&lt;/p&gt;
&lt;p&gt;Tip from my housemate Maria, thanks!
Psychedelic &lt;em&gt;and&lt;/em&gt; you can dance to it, what&#39;s not to like.
New single to the upcoming album &#34;City Slicker&#34;:&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube u-WTfP3WJc4 &amp;gt;}}&lt;/p&gt;
&lt;p&gt;This is not a new song, but I&#39;ve been listening to this cover by Jordan Rakei a lot:&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube DeZeY6C8Meo &amp;gt;}}&lt;/p&gt;
&lt;p&gt;I&#39;ve learned about Emma Ruth Rundle relatively late and for the next collaboration I&#39;m also a year late to the party.
Caution: We are ending on a &lt;em&gt;heavier&lt;/em&gt; note:&lt;/p&gt;
&lt;p&gt;{{&amp;lt; youtube ImMHsDDV_YA &amp;gt;}}&lt;/p&gt;</description>
        </item>
        
        <item>
            <title>Mnemonic for closed-form Bayesian univariate inference with Gaussians</title>
            <link>https://www.edwinwenink.xyz/posts/56-learning_gaussian_univariate_inference_by_heart/</link>
            <guid>https://www.edwinwenink.xyz/posts/56-learning_gaussian_univariate_inference_by_heart/</guid>
            <pubDate>Sun, 13 Jun 2021 21:35:29 +0200</pubDate>
            <description>&lt;p&gt;The following note helps me remember the closed-form solution for Bayesian inference using Gaussian distributions, which comes in handy very often.
See Bishop p.98 (2.141 and 2.142) for closed-form parameter updates for univariate Bayesian inference using a Gaussian likelihood with conjugate Gaussian prior.
Let&#39;s start with the rule for the posterior mean:&lt;/p&gt;
&lt;p&gt;$$\mu_{new} = \frac{\sigma^2}{N \sigma_{0}^2 + \sigma^2} \mu_0 + \frac{N \sigma_{0}^2}{N \sigma_{0}^2 + \sigma^2} \mu_{MLE}$$&lt;/p&gt;
&lt;p&gt;Where we know that the maximum likelihood estimate for the mean is the sample mean:&lt;/p&gt;
&lt;p&gt;$$\mu_{MLE} = \frac{1}{N} \sum_{n=1}^N x_{n}$$&lt;/p&gt;
&lt;p&gt;See the bottom of this post for a derivation of the maximum likelihood estimate for the mean.
Notice that the mean update has the following shape, balancing between the prior mean and the data sample mean:&lt;/p&gt;
&lt;p&gt;$$\mu_{new} = \lambda \mu_{0} + (1-\lambda) \mu_{MLE}$$&lt;/p&gt;
&lt;p&gt;With&lt;/p&gt;
&lt;p&gt;$$ \lambda = \frac{\sigma^2}{N \sigma_{0}^2 + \sigma^2}$$&lt;/p&gt;
&lt;p&gt;I find this form a bit hard to remember by heart.
We can also think of this weighting factor $\lambda$ as the &lt;em&gt;prior precision&lt;/em&gt; divided by the &lt;em&gt;posterior precision&lt;/em&gt;.
This is not immediately obvious, but we can already see in the formula for $\mu_{new}$ that, as the posterior precision increases, the posterior density becomes more concentrated around the maximum likelihood solution for the mean, $\mu_{MLE}$, since then $\lambda$ diminishes and $(1-\lambda)$ will be larger.&lt;/p&gt;
&lt;p&gt;Let&#39;s first write down the posterior variance from Bishop and see how we can use it to support above intuition:&lt;/p&gt;
&lt;p&gt;$$\sigma_{new}^2 = ( \frac{1}{\sigma_{0}^2} + \frac{N}{\sigma^2} )^{-1}$$&lt;/p&gt;
&lt;p&gt;This formula is much easier to remember in terms of precision $\tau = \frac{1}{\sigma^2}$:&lt;/p&gt;
&lt;p&gt;$$\tau_{new} = \tau_{0} + N \tau$$&lt;/p&gt;
&lt;p&gt;Which intuitively reads: the posterior precision is the prior precision plus N times the precision of the likelihood function.
The multiplication by N shows the again intuitive result that the more observations you make, the more &#34;certain&#34; the posterior distribution becomes.&lt;/p&gt;
&lt;p&gt;It&#39;s not immediately obvious that that $\lambda = \frac{\tau_{0}}{\tau_{new}}$ so let&#39;s write it out:&lt;/p&gt;
&lt;p&gt;$$\frac{\tau_{0}}{\tau_{new}} = \frac{\tau_{0}}{ \tau_{0} +&lt;em&gt;N \tau }$$
$$= \frac{  \frac{1}{\sigma&lt;/em&gt;{0}^2} }{ \frac{1}{\sigma_{0}^2} + \frac{N}{\sigma^2}}$$&lt;/p&gt;
&lt;p&gt;Multiplying both sides with $\sigma_{0}^2$ gives:&lt;/p&gt;
&lt;p&gt;$$= \frac{1}{ 1 + \frac{N\sigma_{0}}{\sigma^2} }$$&lt;/p&gt;
&lt;p&gt;Multiplying both sides with $\sigma^2$ gives:&lt;/p&gt;
&lt;p&gt;$$= \frac{\sigma^2}{ \sigma^2 + N\sigma_{0}^2 } = \lambda$$&lt;/p&gt;
&lt;p&gt;QED.&lt;/p&gt;
&lt;p&gt;This results suggest that it&#39;s efficient to first compute the new variance, and then use this variance to compute $\lambda$ in the formula for the posterior mean.&lt;/p&gt;
&lt;p&gt;So if you want to easily remember the parameter update rules, in natural language:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The posterior precision is the prior precision plus N times the likelihood precision&lt;/li&gt;
&lt;li&gt;The posterior mean is a mix between the prior mean and the mean of the observed data sample&lt;/li&gt;
&lt;li&gt;The mixing coefficient of the prior mean is the &lt;em&gt;prior precision&lt;/em&gt; divided by the &lt;em&gt;posterior precision&lt;/em&gt; which we called $\lambda$&lt;/li&gt;
&lt;li&gt;$(1-\lambda)$ is the mixing coefficient of the sample mean.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;MLE for the mean&lt;/h2&gt;
&lt;p&gt;First find the expression for the Gaussian log likelihood:&lt;/p&gt;
&lt;p&gt;$$ln p(D|\mu, \sigma^2) = ln \prod_{n=1}^N \mathbb{N}(x_n | \mu, \sigma^2)$$
$$= \sum_{n=1}^N ln \mathbb{N}(x_n | \mu, \sigma^2)$$
$$= \sum_{n=1}^N ln( \frac{1}{\sqrt{ 2\pi \sigma^2}} exp{ - \frac{(x_n - \mu)^2}{2 \sigma^2}})$$
$$= N ln( \frac{1}{\sqrt{2\pi \sigma^2}}) - \sum_{n=1}^N \frac{(x_n - \mu)^2}{2 \sigma^2}$$
$$= -\frac{1}{2 \sigma^2} \sum_{n=1}^N (x_n - \mu)^2 - \frac{N}{2} ln(\sigma^2) - \frac{N}{2}ln(2\pi)$$&lt;/p&gt;
&lt;p&gt;The next step is to find $\mu_{ML}$ by deriving with respect to $\mu$.
The derivative w.r.t. $\mu$ is:&lt;/p&gt;
&lt;p&gt;$$\frac{1}{\sigma^2} \sum_{n=1}^N (x_n - \mu)$$&lt;/p&gt;
&lt;p&gt;Setting to zero gives the MLE:&lt;/p&gt;
&lt;p&gt;$$\mu_{ML} = \frac{1}{N}\sum_{n=1}^N x_n$$&lt;/p&gt;</description>
        </item>
        
    </channel>
</rss>