Dimitri Lozeve's Blog https://www.lozeve.com Tue, 05 May 2020 00:00:00 UT ICLR 2020 Notes: Speakers and Workshops https://www.lozeve.com/posts/iclr-2020-notes.html

ICLR is one of the most important conferences in machine learning, and as such, I was very excited to have the opportunity to volunteer and attend the first fully-virtual edition of the event. The whole content of the conference has been made publicly available, only a few days after the end of the event!

I would like to thank the organizing committee for this incredible event, and the possibility to volunteer to help other participantsTo better organize the event, and help people navigate the various online tools, they brought in 500(!) volunteers, waved our registration fees, and asked us to do simple load-testing and tech support. This was a very generous offer, and felt very rewarding for us, as we could attend the conference, and give back to the organization a little bit.

.

The many volunteers, the online-only nature of the event, and the low registration fees also allowed for what felt like a very diverse, inclusive event. Many graduate students and researchers from industry (like me), who do not generally have the time or the resources to travel to conferences like this, were able to attend, and make the exchanges richer.

In this post, I will try to give my impressions on the event, the speakers, and the workshops that I could attend. I will do a quick recap of the most interesting papers I saw in a future post.

The Format of the Virtual Conference

As a result of global travel restrictions, the conference was made fully-virtual. It was supposed to take place in Addis Ababa, Ethiopia, which is great for people who are often the target of restrictive visa policies in Northern American countries.

The thing I appreciated most about the conference format was its emphasis on asynchronous communication. Given how little time they had to plan the conference, they could have made all poster presentations via video-conference and call it a day. Instead, each poster had to record a 5-minute videoThe videos are streamed using SlidesLive, which is a great solution for synchronising videos and slides. It is very comfortable to navigate through the slides and synchronising the video to the slides and vice-versa. As a result, SlidesLive also has a very nice library of talks, including major conferences. This is much better than browsing YouTube randomly.

summarising their research. Alongside each presentation, there was a dedicated Rocket.Chat channelRocket.Chat seems to be an open-source alternative to Slack. Overall, the experience was great, and I appreciate the efforts of the organizers to use open source software instead of proprietary applications. I hope other conferences will do the same, and perhaps even avoid Zoom, because of recent privacy concerns (maybe try Jitsi?).

where anyone could ask a question to the authors, or just show their appreciation for the work. This was a fantastic idea as it allowed any participant to interact with papers and authors at any time they please, which is especially important in a setting where people were spread all over the globe.

There were also Zoom session where authors were available for direct, face-to-face discussions, allowing for more traditional conversations. But asking questions on the channel had also the advantage of keeping a track of all questions that were asked by other people. As such, I quickly acquired the habit of watching the video, looking at the chat to see the previous discussions (even if they happened in the middle of the night in my timezone!), and then skimming the paper or asking questions myself.

All of these excellent ideas were implemented by an amazing website, collecting all papers in a searchable, easy-to-use interface, and even including a nice visualisation of papers as a point cloud!

Speakers

Overall, there were 8 speakers (two for each day of the main conference). They made a 40-minute presentation, and then there was a Q&A both via the chat and via Zoom. I only saw a few of them, but I expect I will be watching the others in the near future.

Prof. Leslie Kaelbling, Doing for Our Robots What Nature Did For Us

This talk was fascinating. It is about robotics, and especially how to design the “software” of our robots. We want to program a robot in a way that it could work the best it can over all possible domains it can encounter. I loved the discussion on how to describe the space of distributions over domains, from the point of view of the robot factory:

  • The domain could be very narrow (e.g. playing a specific Atari game) or very broad and complex (performing a complex task in an open world).
  • The factory could know in advance in which domain the robot will evolve, or have a lot of uncertainty around it.

There are many ways to describe a policy (i.e. the software running in the robot’s head), and many ways to obtain them. If you are familiar with recent advances in reinforcement learning, this talk is a great occasion to take a step back, and review the relevant background ideas from engineering and control theory.

Finally, the most important take-away from this talk is the importance of abstractions. Whatever the methods we use to program our robots, we still need a lot of human insights to give them good structural biases. There are many more insights, on the cost of experience, (hierarchical) planning, learning constraints, etc, so I strongly encourage you to watch the talk!

Dr. Laurent Dinh, Invertible Models and Normalizing Flows

This is a very clear presentation of an area of ML research I do not know very well. I really like the approach of teaching a set of methods from a “historical”, personal point of view. Laurent Dinh shows us how he arrived at this topic, what he finds interesting, in a very personal and relatable manner. This has the double advantage of introducing us to a topic that he is passionate about, while also giving us a glimpse of a researcher’s process, without hiding the momentary disillusions and disappointments, but emphasising the great achievements. Normalizing flows are also very interesting because it is grounded in strong theoretical results, that brings together a lot of different methods.

Profs. Yann LeCun and Yoshua Bengio, Reflections from the Turing Award Winners

This talk was very interesting, and yet felt very familiar, as if I already saw a very similar one elsewhere. Especially for Yann LeCun, who clearly reuses the same slides for many presentations at various events. They both came back to their favourite subjects: self-supervised learning for Yann LeCun, and system 1/system 2 for Yoshua Bengio. All in all, they are very good speakers, and their presentations are always insightful. Yann LeCun gives a lot of references on recent technical advances, which is great if you want to go deeper in the approaches he recommends. Yoshua Bengio is also very good at broadening the debate around deep learning, and introducing very important concepts from cognitive science.

Workshops

On Sunday, there were 15 different workshops. All of them were recorded, and are available on the website. As always, unfortunately, there are too many interesting things to watch everything, but I saw bits and pieces of different workshops.

Beyond ‘tabula rasa’ in reinforcement learning: agents that remember, adapt, and generalize

A lot of pretty advanced talks about RL. The general theme was meta-learning, aka “learning to learn”. This is a very active area of research, which goes way beyond classical RL theory, and offer many interesting avenues to adjacent fields (both inside ML and outside, especially cognitive science). The first talk, by Martha White, about inductive biases, was a very interesting and approachable introduction to the problems and challenges of the field. There was also a panel with Jürgen Schmidhuber. We hear a lot about him from the various controversies, but it’s nice to see him talking about research and future developments in RL.

Causal Learning For Decision Making

Ever since I read Judea Pearl’s The Book of Why on causality, I have been interested in how we can incorporate causality reasoning in machine learning. This is a complex topic, and I’m not sure yet that it is a complete revolution as Judea Pearl likes to portray it, but it nevertheless introduces a lot of new fascinating ideas. Yoshua Bengio gave an interesting talkYou can find it at 4:45:20 in the livestream of the workshop.

(even though very similar to his keynote talk) on causal priors for deep learning.

Bridging AI and Cognitive Science

Cognitive science is fascinating, and I believe that collaboration between ML practitioners and cognitive scientists will greatly help advance both fields. I only watched Leslie Kaelbling’s presentation, which echoes a lot of things from her talk at the main conference. It complements it nicely, with more focus on intelligence, especially embodied intelligence. I think she has the right approach to relationships between AI and natural science, explicitly listing the things from her work that would be helpful to natural scientists, and things she wish she knew about natural intelligences. It raises many fascinating questions on ourselves, what we build, and what we understand. I felt it was very motivational!

Integration of Deep Neural Models and Differential Equations

I didn’t attend this workshop, but I think I will watch the presentations if I can find the time. I have found the intersection of differential equations and ML very interesting, ever since the famous NeurIPS best paper on Neural ODEs. I think that such improvements to ML theory from other fields in mathematics would be extremely beneficial to a better understanding of the systems we build.

]]>
Tue, 05 May 2020 00:00:00 UT https://www.lozeve.com/posts/iclr-2020-notes.html Dimitri Lozeve
Reading notes: Hierarchical Optimal Transport for Document Representation https://www.lozeve.com/posts/hierarchical-optimal-transport-for-document-classification.html

Two weeks ago, I did a presentation for my colleagues of the paper from Yurochkin et al. (2019), from NeurIPS 2019. It contains an interesting approach to document classification leading to strong performance, and, most importantly, excellent interpretability.

This paper seems interesting to me because of it uses two methods with strong theoretical guarantees: optimal transport and topic modelling. Optimal transport looks very promising to me in NLP, and has seen a lot of interest in recent years due to advances in approximation algorithms, such as entropy regularisation. It is also quite refreshing to see approaches using solid results in optimisation, compared to purely experimental deep learning methods.

Introduction and motivation

The problem of the paper is to measure similarity (i.e. a distance) between pairs of documents, by incorporating semantic similarities (and not only syntactic artefacts), without encountering scalability issues.

They propose a “meta-distance” between documents, called the hierarchical optimal topic transport (HOTT), providing a scalable metric incorporating topic information between documents. As such, they try to combine two different levels of analysis:

  • word embeddings data, to embed language knowledge (via pre-trained embeddings for instance),
  • topic modelling methods (e.g. Latent Dirichlet Allocation), to represent semantically-meaningful groups of words.

Background: optimal transport

The essential backbone of the method is the Wasserstein distance, derived from optimal transport theory. Optimal transport is a fascinating and deep subject, so I won’t enter into the details here. For an introduction to the theory and its applications, check out the excellent book from Peyré and Cuturi (2019), (available on ArXiv as well). There are also very nice posts (in French) by Gabriel Peyré on the CNRS maths blog. Many more resources (including slides for presentations) are available at https://optimaltransport.github.io. For a more complete theoretical treatment of the subject, check out Santambrogio (2015), or, if you’re feeling particularly adventurous, Villani (2009).

For this paper, only a superficial understanding of how the Wasserstein distance works is necessary. Optimal transport is an optimisation technique to lift a distance between points in a given metric space, to a distance between probability distributions over this metric space. The historical example is to move piles of dirt around: you know the distance between any two points, and you have piles of dirt lying around Optimal transport originated with Monge, and then Kantorovich, both of whom had very clear military applications in mind (either in Revolutionary France, or during WWII). A lot of historical examples move cannon balls, or other military equipment, along a front line.

. Now, if you want to move these piles to another configuration (fewer piles, say, or a different repartition of dirt a few metres away), you need to find the most efficient way to move them. The total cost you obtain will define a distance between the two configurations of dirt, and is usually called the earth mover’s distance, which is just an instance of the general Wasserstein metric.

More formally, we start with two sets of points \(x = (x_1, x_2, \ldots, x_n)\), and \(y = (y_1, y_2, \ldots, y_n)\), along with probability distributions \(p \in \Delta^n\), \(q \in \Delta^m\) over \(x\) and \(y\) (\(\Delta^n\) is the probability simplex of dimension \(n\), i.e. the set of vectors of size \(n\) summing to 1). We can then define the Wasserstein distance as \[ W_1(p, q) = \min_{P \in \mathbb{R}_+^{n\times m}} \sum_{i,j} C_{i,j} P_{i,j} \] \[ \text{\small subject to } \sum_j P_{i,j} = p_i \text{ \small and } \sum_i P_{i,j} = q_j, \] where \(C_{i,j} = d(x_i, x_j)\) are the costs computed from the original distance between points, and \(P_{i,j}\) represent the amount we are moving from pile \(i\) to pile \(j\).

Now, how can this be applied to a natural language setting? Once we have word embeddings, we can consider that the vocabulary forms a metric space (we can compute a distance, for instance the euclidean or the cosine distance, between two word embeddings). The key is to define documents as distributions over words.

Given a vocabulary \(V \subset \mathbb{R}^n\) and a corpus \(D = (d^1, d^2, \ldots, d^{\lvert D \rvert})\), we represent a document as \(d^i \in \Delta^{l_i}\) where \(l_i\) is the number of unique words in \(d^i\), and \(d^i_j\) is the proportion of word \(v_j\) in the document \(d^i\). The word mover’s distance (WMD) is then defined simply as \[ \operatorname{WMD}(d^1, d^2) = W_1(d^1, d^2). \]

If you didn’t follow all of this, don’t worry! The gist is: if you have a distance between points, you can solve an optimisation problem to obtain a distance between distributions over these points! This is especially useful when you consider that each word embedding is a point, and a document is just a set of words, along with the number of times they appear.

Hierarchical optimal transport

Using optimal transport, we can use the word mover’s distance to define a metric between documents. However, this suffers from two drawbacks:

  • Documents represented as distributions over words are not easily interpretable. For long documents, the vocabulary is huge and word frequencies are not easily understandable for humans.
  • Large vocabularies mean that the space on which we have to find an optimal matching is huge. The Hungarian algorithm used to compute the optimal transport distance runs in \(O(l^3 \log l)\), where \(l\) is the maximum number of unique words in each documents. This quickly becomes intractable as the size of documents become larger, or if you have to compute all pairwise distances between a large number of documents (e.g. for clustering purposes).

To escape these issues, we will add an intermediary step using topic modelling. Once we have topics \(T = (t_1, t_2, \ldots, t_{\lvert T \rvert}) \subset \Delta^{\lvert V \rvert}\), we get two kinds of representations:

  • representations of topics as distributions over words,
  • representations of documents as distributions over topics \(\bar{d^i} \in \Delta^{\lvert T \rvert}\).

Since they are distributions over words, the word mover’s distance defines a metric over topics. As such, the topics with the WMD become a metric space.

We can now define the hierarchical optimal topic transport (HOTT), as the optimal transport distance between documents, represented as distributions over topics. For two documents \(d^1\), \(d^2\), \[ \operatorname{HOTT}(d^1, d^2) = W_1\left( \sum_{k=1}^{\lvert T \rvert} \bar{d^1_k} \delta_{t_k}, \sum_{k=1}^{\lvert T \rvert} \bar{d^2_k} \delta_{t_k} \right). \] where \(\delta_{t_k}\) is a distribution supported on topic \(t_k\).

Note that in this case, we used optimal transport twice:

  • once to find distances between topics (WMD),
  • once to find distances between documents, where the distance between topics became the costs in the new optimal transport problem.

The first one can be precomputed once for all subsequent distances, so it is invariable in the number of documents we have to process. The second one only operates on \(\lvert T \rvert\) topics instead of the full vocabulary: the resulting optimisation problem is much smaller! This is great for performance, as it should be easy now to compute all pairwise distances in a large set of documents.

Another interesting insight is that topics are represented as collections of words (we can keep the top 20 as a visual representations), and documents as collections of topics with weights. Both of these representations are highly interpretable for a human being who wants to understand what’s going on. I think this is one of the strongest aspects of these approaches: both the various representations and the algorithms are fully interpretable. Compared to a deep learning approach, we can make sense of every intermediate step, from the representations of topics to the weights in the optimisation algorithm to compute higher-level distances.

Representation of two documents in topic space, along with how the distance was computed between them. Everything is interpretable: from the documents as collections of topics, to the matchings between topics determining the overall distance between the books (Yurochkin et al. 2019).

Experiments

The paper is very complete regarding experiments, providing a full evaluation of the method on one particular application: document clustering. They use Latent Dirichlet Allocation to compute topics and GloVe for pretrained word embeddings (Pennington, Socher, and Manning 2014), and Gurobi to solve the optimisation problems. Their code is available on GitHub.

If you want the details, I encourage you to read the full paper, they tested the methods on a wide variety of datasets, with datasets containing very short documents (like Twitter), and long documents with a large vocabulary (books). With a simple \(k\)-NN classification, they establish that HOTT performs best on average, especially on large vocabularies (books, the “gutenberg” dataset). It also has a much better computational performance than alternative methods based on regularisation of the optimal transport problem directly on words. So the hierarchical nature of the approach allows to gain considerably in performance, along with improvements in interpretability.

What’s really interesting in the paper is the sensitivity analysis: they ran experiments with different word embeddings methods (word2vec, (Mikolov et al. 2013)), and with different parameters for the topic modelling (topic truncation, number of topics, etc). All of these reveal that changes in hyperparameters do not impact the performance of HOTT significantly. This is extremely important in a field like NLP where most of the times small variations in approach lead to drastically different results.

Conclusion

All in all, this paper present a very interesting approach to compute distance between natural-language documents. It is no secret that I like methods with strong theoretical background (in this case optimisation and optimal transport), guaranteeing a stability and benefiting from decades of research in a well-established domain.

Most importantly, this paper allows for future exploration in document representation with interpretability in mind. This is often added as an afterthought in academic research but is one of the most important topics for the industry, as a system must be understood by end users, often not trained in ML, before being deployed. The notion of topic, and distances as weights, can be understood easily by anyone without significant background in ML or in maths.

Finally, I feel like they did not stop at a simple theoretical argument, but carefully checked on real-world datasets, measuring sensitivity to all the arbitrary choices they had to take. Again, from an industry perspective, this allows to implement the new approach quickly and easily, being confident that it won’t break unexpectedly without extensive testing.

References

Mikolov, Tomas, Ilya Sutskever, Kai Chen, Greg S Corrado, and Jeff Dean. 2013. “Distributed Representations of Words and Phrases and Their Compositionality.” In Advances in Neural Information Processing Systems 26, 3111–9. http://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf.

Pennington, Jeffrey, Richard Socher, and Christopher Manning. 2014. “Glove: Global Vectors for Word Representation.” In Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP), 1532–43. Doha, Qatar: Association for Computational Linguistics. https://doi.org/10.3115/v1/D14-1162.

Peyré, Gabriel, and Marco Cuturi. 2019. “Computational Optimal Transport.” Foundations and Trends in Machine Learning 11 (5-6): 355–206. https://doi.org/10.1561/2200000073.

Santambrogio, Filippo. 2015. Optimal Transport for Applied Mathematicians. Vol. 87. Progress in Nonlinear Differential Equations and Their Applications. Cham: Springer International Publishing. https://doi.org/10.1007/978-3-319-20828-2.

Villani, Cédric. 2009. Optimal Transport: Old and New. Grundlehren Der Mathematischen Wissenschaften 338. Berlin: Springer.

Yurochkin, Mikhail, Sebastian Claici, Edward Chien, Farzaneh Mirzazadeh, and Justin M Solomon. 2019. “Hierarchical Optimal Transport for Document Representation.” In Advances in Neural Information Processing Systems 32, 1599–1609. http://papers.nips.cc/paper/8438-hierarchical-optimal-transport-for-document-representation.pdf.

]]>
Sun, 05 Apr 2020 00:00:00 UT https://www.lozeve.com/posts/hierarchical-optimal-transport-for-document-classification.html Dimitri Lozeve
Mindsay: Towards Self-Learning Chatbots https://www.lozeve.com/posts/self-learning-chatbots-destygo.html

Last week I made a presentation at the Paris NLP Meetup, on how we implemented self-learning chatbots in production at Mindsay.

It was fascinating to other people interested in NLP about the technologies and models we deploy at work! It’s always nice to have some feedback about our work, and preparing this talk forced me to take a step back about what we do and rethink it in new interesting ways.

Also check out the other presentations, one about diachronic (i.e. time-dependent) word embeddings and the other about the different models and the use of Knowledge Bases for Information Retrieval. (This might even give us new ideas to explore…)

If you’re interested about exciting applications at the confluence of Reinforcement Learning and NLP, the slides are available here. It includes basic RL theory, how we transposed it to the specific case of conversational agents, the technical and mathematical challenges in implementing self-learning chatbots, and of course plenty of references for further reading if we piqued your interest!

Update: The videos are now available on the NLP Meetup website.

Update 2: Destygo changed its name to Mindsay!

]]>
Sat, 06 Apr 2019 00:00:00 UT https://www.lozeve.com/posts/self-learning-chatbots-destygo.html Dimitri Lozeve
Random matrices from the Ginibre ensemble https://www.lozeve.com/posts/ginibre-ensemble.html

Ginibre ensemble and its properties

The Ginibre ensemble is a set of random matrices with the entries chosen independently. Each entry of a \(n \times n\) matrix is a complex number, with both the real and imaginary part sampled from a normal distribution of mean zero and variance \(1/2n\).

Random matrices distributions are very complex and are a very active subject of research. I stumbled on this example while reading an article in Notices of the AMS by Brian C. Hall (1).

Now what is interesting about these random matrices is the distribution of their \(n\) eigenvalues in the complex plane.

The circular law (first established by Jean Ginibre in 1965 (2)) states that when \(n\) is large, with high probability, almost all the eigenvalues lie in the unit disk. Moreover, they tend to be nearly uniformly distributed there.

I find this mildly fascinating that such a straightforward definition of a random matrix can exhibit such non-random properties in their spectrum.

Simulation

I ran a quick simulation, thanks to Julia’s great ecosystem for linear algebra and statistical distributions:

I like using UnicodePlots for this kind of quick-and-dirty plots, directly in the terminal. Here is the output:

References

  1. Hall, Brian C. 2019. “Eigenvalues of Random Matrices in the General Linear Group in the Large-\(N\) Limit.” Notices of the American Mathematical Society 66, no. 4 (Spring): 568-569. https://www.ams.org/journals/notices/201904/201904FullIssue.pdf
  2. Ginibre, Jean. “Statistical ensembles of complex, quaternion, and real matrices.” Journal of Mathematical Physics 6.3 (1965): 440-449. https://doi.org/10.1063/1.1704292
]]>
Wed, 20 Mar 2019 00:00:00 UT https://www.lozeve.com/posts/ginibre-ensemble.html Dimitri Lozeve
Peano Axioms https://www.lozeve.com/posts/peano.html

Introduction

I have recently bought the book Category Theory from Steve Awodey (Awodey 2010) is awesome, but probably the topic for another post), and a particular passage excited my curiosity:

Let us begin by distinguishing between the following things: i. categorical foundations for mathematics, ii. mathematical foundations for category theory.

As for the first point, one sometimes hears it said that category theory can be used to provide “foundations for mathematics,” as an alternative to set theory. That is in fact the case, but it is not what we are doing here. In set theory, one often begins with existential axioms such as “there is an infinite set” and derives further sets by axioms like “every set has a powerset,” thus building up a universe of mathematical objects (namely sets), which in principle suffice for “all of mathematics.”

This statement is interesting because one often considers category theory as pretty “fundamental”, in the sense that it has no issue with considering what I call “dangerous” notions, such as the category \(\mathbf{Set}\) of all sets, and even the category \(\mathbf{Cat}\) of all categories. Surely a theory this general, that can afford to study such objects, should provide suitable foundations for mathematics? Awodey addresses these issues very explicitly in the section following the quote above, and finds a good way of avoiding circular definitions.

Now, I remember some basics from my undergrad studies about foundations of mathematics. I was told that if you could define arithmetic, you basically had everything else “for free” (as Kronecker famously said, “natural numbers were created by God, everything else is the work of men”). I was also told that two sets of axioms existed, the Peano axioms and the Zermelo-Fraenkel axioms. Also, I should steer clear of the axiom of choice if I could, because one can do strange things with it, and it is equivalent to many different statements. Finally (and this I knew mainly from Logicomix, I must admit), it is impossible for a set of axioms to be both complete and consistent.

Given all this, I realised that my knowledge of foundational mathematics was pretty deficient. I do not believe that it is a very important topic that everyone should know about, even though Gödel’s incompleteness theorem is very interesting from a logical and philosophical standpoint. However, I wanted to go deeper on this subject.

In this post, I will try to share my path through Peano’s axioms (Gowers, Barrow-Green, and Leader 2010), because they are very simple, and it is easy to uncover basic algebraic structure from them.

The Axioms

The purpose of the axioms is to define a collection of objects that we will call the natural numbers. Here, we place ourselves in the context of first-order logic. Logic is not the main topic here, so I will just assume that I have access to some quantifiers, to some predicates, to some variables, and, most importantly, to a relation \(=\) which is reflexive, symmetric, transitive, and closed over the natural numbers.

Without further digressions, let us define two symbols \(0\) and \(s\) (called successor) such that:

  1. \(0\) is a natural number.
  2. For every natural number \(n\), \(s(n)\) is a natural number. (“The successor of a natural number is a natural number.”)
  3. For all natural number \(m\) and \(n\), if \(s(m) = s(n)\), then \(m=n\). (“If two numbers have the same successor, they are equal.”)
  4. For every natural number \(n\), \(s(n) = 0\) is false. (“\(0\) is nobody’s successor.”)
  5. If \(A\) is a set such that:
    • \(0\) is in \(A\)
    • for every natural number \(n\), if \(n\) is in \(A\) then \(s(n)\) is in \(A\)
    then \(A\) contains every natural number.

Let’s break this down. Axioms 1–4 define a collection of objects, written \(0\), \(s(0)\), \(s(s(0))\), and so on, and ensure their basic properties. All of these are natural numbers by the first four axioms, but how can we be sure that all natural numbers are of the form \(s( \cdots s(0))\)? This is where the induction axiom (Axiom 5) intervenes. It ensures that every natural number is “well-formed” according to the previous axioms.

But Axiom 5 is slightly disturbing, because it mentions a “set” and a relation “is in”. This seems pretty straightforward at first sight, but these notions were never defined anywhere before that! Isn’t our goal to define all these notions in order to derive a foundation of mathematics? (I still don’t know the answer to that question.) I prefer the following alternative version of the induction axiom:

  • If \(\varphi\) is a unary predicate such that:
    • \(\varphi(0)\) is true
    • for every natural number \(n\), if \(\varphi(n)\) is true, then \(\varphi(s(n))\) is also true
    then \(\varphi(n)\) is true for every natural number \(n\).

The alternative formulation is much better in my opinion, as it obviously implies the first one (juste choose \(\varphi(n)\) as “\(n\) is a natural number”), and it only references predicates. It will also be much more useful afterwards, as we will see.

Addition

What is needed afterwards? The most basic notion after the natural numbers themselves is the addition operator. We define an operator \(+\) by the following (recursive) rules:

  1. \(\forall a,\quad a+0 = a\).
  2. \(\forall a, \forall b,\quad a + s(b) = s(a+b)\).

Let us use these rules to prove the basic properties of \(+\).

Commutativity

\(\forall a, \forall b,\quad a+b = b+a\).

First, we prove that every natural number commutes with \(0\).

  • \(0+0 = 0+0\).
  • For every natural number \(a\) such that \(0+a = a+0\), we have:

By Axiom 5, every natural number commutes with \(0\).

We can now prove the main proposition:

  • \(\forall a,\quad a+0=0+a\).
  • For all \(a\) and \(b\) such that \(a+b=b+a\),

We used the opposite of the second rule for \(+\), namely \(\forall a, \forall b,\quad s(a) + b = s(a+b)\). This can easily be proved by another induction.

Associativity

\(\forall a, \forall b, \forall c,\quad a+(b+c) = (a+b)+c\).

Todo, left as an exercise to the reader 😉

Identity element

\(\forall a,\quad a+0 = 0+a = a\).

This follows directly from the definition of \(+\) and commutativity.

From all these properties, it follows that the set of natural numbers with \(+\) is a commutative monoid.

Going further

We have imbued our newly created set of natural numbers with a significant algebraic structure. From there, similar arguments will create more structure, notably by introducing another operation \(\times\), and an order \(\leq\).

It is now a matter of conventional mathematics to construct the integers \(\mathbb{Z}\) and the rationals \(\mathbb{Q}\) (using equivalence classes), and eventually the real numbers \(\mathbb{R}\).

It is remarkable how very few (and very simple, as far as you would consider the induction axiom “simple”) axioms are enough to build an entire theory of mathematics. This sort of things makes me agree with Eugene Wigner (Wigner 1990) when he says that “mathematics is the science of skillful operations with concepts and rules invented just for this purpose”. We drew some arbitrary rules out of thin air, and derived countless properties and theorems from them, basically for our own enjoyment. (As Wigner would say, it is incredible that any of these fanciful inventions coming out of nowhere turned out to be even remotely useful.) Mathematics is done mainly for the mathematician’s own pleasure!

Mathematics cannot be defined without acknowledging its most obvious feature: namely, that it is interesting — M. Polanyi (Wigner 1990)

References

Awodey, Steve. 2010. Category Theory. 2nd ed. Oxford Logic Guides 52. Oxford ; New York: Oxford University Press.

Gowers, Timothy, June Barrow-Green, and Imre Leader. 2010. The Princeton Companion to Mathematics. Princeton University Press.

Wigner, Eugene P. 1990. “The Unreasonable Effectiveness of Mathematics in the Natural Sciences.” In Mathematics and Science, by Ronald E Mickens, 291–306. WORLD SCIENTIFIC. https://doi.org/10.1142/9789814503488_0018.

]]>
Mon, 18 Mar 2019 00:00:00 UT https://www.lozeve.com/posts/peano.html Dimitri Lozeve
Quick Notes on Reinforcement Learning https://www.lozeve.com/posts/reinforcement-learning-1.html

Introduction

In this series of blog posts, I intend to write my notes as I go through Richard S. Sutton’s excellent Reinforcement Learning: An Introduction (1).

I will try to formalise the maths behind it a little bit, mainly because I would like to use it as a useful personal reference to the main concepts in RL. I will probably add a few remarks about a possible implementation as I go on.

Relationship between agent and environment

Context and assumptions

The goal of reinforcement learning is to select the best actions availables to an agent as it goes through a series of states in an environment. In this post, we will only consider discrete time steps.

The most important hypothesis we make is the Markov property:

At each time step, the next state of the agent depends only on the current state and the current action taken. It cannot depend on the history of the states visited by the agent.

This property is essential to make our problems tractable, and often holds true in practice (to a reasonable approximation).

With this assumption, we can define the relationship between agent and environment as a Markov Decision Process (MDP).

A Markov Decision Process is a tuple \((\mathcal{S}, \mathcal{A}, \mathcal{R}, p)\) where:

  • \(\mathcal{S}\) is a set of states,
  • \(\mathcal{A}\) is an application mapping each state \(s \in \mathcal{S}\) to a set \(\mathcal{A}(s)\) of possible actions for this state. In this post, we will often simplify by using \(\mathcal{A}\) as a set, assuming that all actions are possible for each state,
  • \(\mathcal{R} \subset \mathbb{R}\) is a set of rewards,
  • and \(p\) is a function representing the dynamics of the MDP:

    such that \[ \forall s \in \mathcal{S}, \forall a \in \mathcal{A},\quad \sum_{s', r} p(s', r \;|\; s, a) = 1. \]

The function \(p\) represents the probability of transitioning to the state \(s'\) and getting a reward \(r\) when the agent is at state \(s\) and chooses action \(a\).

We will also use occasionally the state-transition probabilities:

Rewarding the agent

The expected reward of a state-action pair is the function

The discounted return is the sum of all future rewards, with a multiplicative factor to give more weights to more immediate rewards: \[ G_t := \sum_{k=t+1}^T \gamma^{k-t-1} R_k, \] where \(T\) can be infinite or \(\gamma\) can be 1, but not both.

Deciding what to do: policies

Defining our policy and its value

A policy is a way for the agent to choose the next action to perform.

A policy is a function \(\pi\) defined as

In order to compare policies, we need to associate values to them.

The state-value function of a policy \(\pi\) is

We can also compute the value starting from a state \(s\) by also taking into account the action taken \(a\).

The action-value function of a policy \(\pi\) is

The quest for the optimal policy

References

  1. R. S. Sutton and A. G. Barto, Reinforcement learning: an introduction, Second edition. Cambridge, MA: The MIT Press, 2018.
]]>
Wed, 21 Nov 2018 00:00:00 UT https://www.lozeve.com/posts/reinforcement-learning-1.html Dimitri Lozeve
Ising model simulation in APL https://www.lozeve.com/posts/ising-apl.html

The APL family of languages

Why APL?

I recently got interested in APL, an array-based programming language. In APL (and derivatives), we try to reason about programs as series of transformations of multi-dimensional arrays. This is exactly the kind of style I like in Haskell and other functional languages, where I also try to use higher-order functions (map, fold, etc) on lists or arrays. A developer only needs to understand these abstractions once, instead of deconstructing each loop or each recursive function encountered in a program.

APL also tries to be a really simple and terse language. This combined with strange Unicode characters for primitive functions and operators, gives it a reputation of unreadability. However, there is only a small number of functions to learn, and you get used really quickly to read them and understand what they do. Some combinations also occur so frequently that you can recognize them instantly (APL programmers call them idioms).

Implementations

APL is actually a family of languages. The classic APL, as created by Ken Iverson, with strange symbols, has many implementations. I initially tried GNU APL, but due to the lack of documentation and proper tooling, I went to Dyalog APL (which is proprietary, but free for personal use). There are also APL derivatives, that often use ASCII symbols: J (free) and Q/kdb+ (proprietary, but free for personal use).

The advantage of Dyalog is that it comes with good tooling (which is necessary for inserting all the symbols!), a large ecosystem, and pretty good documentation. If you want to start, look at Mastering Dyalog APL by Bernard Legrand, freely available online.

The Ising model in APL

I needed a small project to try APL while I was learning. Something array-based, obviously. Since I already implemented a Metropolis-Hastings simulation of the Ising model, which is based on a regular lattice, I decided to reimplement it in Dyalog APL.

It is only a few lines long, but I will try to explain what it does step by step.

The first function simply generates a random lattice filled by elements of \(\{-1,+1\}\).

L←{(2×?⍵ ⍵⍴2)-3}

Let’s deconstruct what is done here:

  • ⍵ is the argument of our function.
  • We generate a ⍵×⍵ matrix filled with 2, using the function: ⍵ ⍵⍴2
  • ? draws a random number between 1 and its argument. We give it our matrix to generate a random matrix of 1 and 2.
  • We multiply everything by 2 and subtract 3, so that the result is in \(\{-1,+1\}\).
  • Finally, we assign the result to the name L.

Sample output:

      ising.L 5
 1 ¯1  1 ¯1  1
 1  1  1 ¯1 ¯1
 1 ¯1 ¯1 ¯1 ¯1
 1  1  1 ¯1 ¯1
¯1 ¯1  1  1  1

Next, we compute the energy variation (for details on the Ising model, see my previous post).

∆E←{
    ⎕IO←0
    (x y)←⍺
    N←⊃⍴⍵
    xn←N|((x-1)y)((x+1)y)
    yn←N|(x(y-1))(x(y+1))
    ⍵[x;y]×+/⍵[xn,yn]
}
  • ⍺ is the left argument (coordinates of the site), ⍵ is the right argument (lattice).
  • We extract the x and y coordinates of the site.
  • N is the size of the lattice.
  • xn and yn are respectively the vertical and lateral neighbours of the site. N| takes the coordinates modulo N (so the lattice is actually a torus). (Note: we used ⎕IO←0 to use 0-based array indexing.)
  • +/ sums over all neighbours of the site, and then we multiply by the value of the site itself to get \(\Delta E\).

Sample output, for site \((3, 3)\) in a random \(5\times 5\) lattice:

      3 3ising.∆E ising.L 5
¯4

Then comes the actual Metropolis-Hastings part:

U←{
    ⎕IO←0
    N←⊃⍴⍵
    (x y)←?N N
    new←⍵
    new[x;y]×←(2×(?0)>*-⍺×x y ∆E ⍵)-1
    new
}
  • ⍺ is the \(\beta\) parameter of the Ising model, ⍵ is the lattice.
  • We draw a random site \((x,y)\) with the ? function.
  • new is the lattice but with the \((x,y)\) site flipped.
  • We compute the probability \(\alpha = \exp(-\beta\Delta E)\) using the * function (exponential) and our previous ∆E function.
  • ?0 returns a uniform random number in \([0,1)\). Based on this value, we decide whether to update the lattice, and we return it.

We can now bring everything together for display:

Ising←{' ⌹'[1+1=({10 U ⍵}⍣⍵)L ⍺]}
  • We draw a random lattice of size ⍺ with L ⍺.
  • We apply to it our update function, with $β$=10, ⍵ times (using the function, which applies a function \(n\) times.
  • Finally, we display -1 as a space and 1 as a domino ⌹.

Final output, with a \(80\times 80\) random lattice, after 50000 update steps:

      80ising.Ising 50000
   ⌹⌹⌹⌹ ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹      ⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹          
   ⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹ ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹           
⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹
⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹             ⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹     ⌹⌹⌹⌹⌹⌹             ⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹ ⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹       ⌹⌹⌹⌹⌹      ⌹       
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹        ⌹⌹⌹⌹      ⌹⌹⌹      
 ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹       ⌹⌹⌹      
 ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹    ⌹⌹⌹⌹⌹⌹      
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹          ⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹
⌹⌹⌹⌹ ⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹           ⌹⌹⌹⌹                ⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹
  ⌹ ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹ ⌹⌹⌹⌹           ⌹⌹⌹⌹                ⌹⌹⌹      ⌹⌹⌹⌹⌹         
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹                ⌹⌹        ⌹           
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹                                     
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹                                    
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹           ⌹                         
 ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹          ⌹                          
⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹          ⌹⌹⌹⌹⌹⌹                          ⌹⌹     ⌹⌹⌹
⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹                  ⌹⌹⌹⌹⌹⌹         ⌹               ⌹⌹⌹     ⌹⌹⌹
⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹                   ⌹⌹⌹⌹⌹⌹                     ⌹⌹⌹⌹⌹⌹     ⌹⌹⌹
⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹             ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹                ⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹                 ⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹ ⌹⌹⌹⌹⌹⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹                            ⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹                               ⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹                                ⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹                   ⌹⌹⌹⌹             ⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹                   ⌹⌹⌹⌹                           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹                  ⌹⌹⌹⌹⌹⌹⌹                ⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹ 
  ⌹⌹⌹⌹                  ⌹⌹⌹⌹⌹⌹⌹              ⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
  ⌹⌹⌹⌹                 ⌹⌹⌹⌹⌹⌹⌹⌹⌹             ⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
  ⌹⌹⌹⌹   ⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
 ⌹⌹⌹⌹⌹   ⌹ ⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
 ⌹⌹⌹⌹⌹   ⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
 ⌹⌹⌹⌹⌹             ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
⌹⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹
⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹
⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹ ⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹             ⌹          ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹                       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹            ⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
                    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
                       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹  
            ⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹  
           ⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹  
   ⌹⌹⌹ ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹           ⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹             ⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹   ⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹        ⌹⌹⌹                       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹         ⌹⌹⌹                          ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹         ⌹⌹⌹    ⌹⌹                      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹                      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹          ⌹⌹⌹⌹⌹⌹⌹⌹                      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹                         ⌹⌹⌹⌹⌹⌹⌹⌹       
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹                          ⌹⌹⌹⌹⌹⌹⌹       
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹                          ⌹⌹⌹          
 ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹                        ⌹⌹⌹          
 ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹                        ⌹⌹⌹          
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹                      ⌹⌹⌹⌹          
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹       ⌹             ⌹⌹⌹⌹⌹       ⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹ ⌹             ⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹            ⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹             ⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹
   ⌹⌹⌹⌹⌹⌹⌹⌹             ⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹ 
   ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹           
   ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         
   ⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         

Complete code, with the namespace:

:Namespace ising

        L←{(2×?⍵ ⍵⍴2)-3}

        ∆E←{
                ⎕IO←0
                (x y)←⍺
                N←⊃⍴⍵
                xn←N|((x-1)y)((x+1)y)
                yn←N|(x(y-1))(x(y+1))
                ⍵[x;y]×+/⍵[xn,yn]
        }

        U←{
                ⎕IO←0
                N←⊃⍴⍵
                (x y)←?N N
                new←⍵
                new[x;y]×←(2×(?0)>*-⍺×x y ∆E ⍵)-1
                new
        }

        Ising←{' ⌹'[1+1=({10 U ⍵}⍣⍵)L ⍺]}

:EndNamespace

Conclusion

The algorithm is very fast (I think it can be optimized by the interpreter because there is no branching), and is easy to reason about. The whole program fits in a few lines, and you clearly see what each function and each line does. It could probably be optimized further (I don’t know every APL function yet…), and also could probably be golfed to a few lines (at the cost of readability?).

It took me some time to write this, but Dyalog’s tools make it really easy to insert symbols and to look up what they do. Next time, I will look into some ASCII-based APL descendants. J seems to have a good documentation and a tradition of tacit definitions, similar to the point-free style in Haskell. Overall, J seems well-suited to modern functional programming, while APL is still under the influence of its early days when it was more procedural. Another interesting area is K, Q, and their database engine kdb+, which seems to be extremely performant and actually used in production.

Still, Unicode symbols make the code much more readable, mainly because there is a one-to-one link between symbols and functions, which cannot be maintained with only a few ASCII characters.

]]>
Mon, 05 Mar 2018 00:00:00 UT https://www.lozeve.com/posts/ising-apl.html Dimitri Lozeve
Ising model simulation https://www.lozeve.com/posts/ising-model.html
by Dimitri Lozeve

The Ising model is a model used to represent magnetic dipole moments in statistical physics. Physical details are on the Wikipedia page, but what is interesting is that it follows a complex probability distribution on a lattice, where each site can take the value +1 or -1.

Mathematical definition

We have a lattice \(\Lambda\) consisting of sites \(k\). For each site, there is a moment \(\sigma_k \in \{ -1, +1 \}\). \(\sigma = (\sigma_k)_{k\in\Lambda}\) is called the configuration of the lattice.

The total energy of the configuration is given by the Hamiltonian \[ H(\sigma) = -\sum_{i\sim j} J_{ij}\, \sigma_i\, \sigma_j, \] where \(i\sim j\) denotes neighbours, and \(J\) is the interaction matrix.

The configuration probability is given by: \[ \pi_\beta(\sigma) = \frac{e^{-\beta H(\sigma)}}{Z_\beta} \] where \(\beta = (k_B T)^{-1}\) is the inverse temperature, and \(Z_\beta\) the normalisation constant.

For our simulation, we will use a constant interaction term \(J > 0\). If \(\sigma_i = \sigma_j\), the probability will be proportional to \(\exp(\beta J)\), otherwise it would be \(\exp(\beta J)\). Thus, adjacent spins will try to align themselves.

Simulation

The Ising model is generally simulated using Markov Chain Monte Carlo (MCMC), with the Metropolis-Hastings algorithm.

The algorithm starts from a random configuration and runs as follows:

  1. Select a site \(i\) at random and reverse its spin: \(\sigma'_i = -\sigma_i\)
  2. Compute the variation in energy (hamiltonian) \(\Delta E = H(\sigma') - H(\sigma)\)
  3. If the energy is lower, accept the new configuration
  4. Otherwise, draw a uniform random number \(u \in ]0,1[\) and accept the new configuration if \(u < \min(1, e^{-\beta \Delta E})\).

Implementation

The simulation is in Clojure, using the Quil library (a Processing library for Clojure) to display the state of the system.

This post is “literate Clojure”, and contains core.clj. The complete project can be found on GitHub.

The application works with Quil’s functional mode, with each function taking a state and returning an updated state at each time step.

The setup function generates the initial state, with random initial spins. It also sets the frame rate. The matrix is a single vector in row-major mode. The state also holds relevant parameters for the simulation: \(\beta\), \(J\), and the iteration step.

Given a site \(i\), we reverse its spin to generate a new configuration state.

In order to decide whether to accept this new state, we compute the difference in energy introduced by reversing site \(i\): \[ \Delta E = J\sigma_i \sum_{j\sim i} \sigma_j. \]

The filter some? is required to eliminate sites outside of the boundaries of the lattice.

We also add a function to compute directly the hamiltonian for the entire configuration state. We can use it later to log its values across iterations.

Finally, we put everything together in the update-state function, which will decide whether to accept or reject the new configuration.

The last thing to do is to draw the new configuration:

And to reset the simulation when the user clicks anywhere on the screen:

Conclusion

The Ising model is a really easy (and common) example use of MCMC and Metropolis-Hastings. It allows to easily and intuitively understand how the algorithm works, and to make nice visualizations!

]]>
Mon, 05 Feb 2018 00:00:00 UT https://www.lozeve.com/posts/ising-model.html Dimitri Lozeve
Generating and representing L-systems https://www.lozeve.com/posts/lsystems.html
by Dimitri Lozeve

L-systems are a formal way to make interesting visualisations. You can use them to model a wide variety of objects: space-filling curves, fractals, biological systems, tilings, etc.

See the Github repo: https://github.com/dlozeve/lsystems

What is an L-system?

A few examples to get started

Definition

An L-system is a set of rewriting rules generating sequences of symbols. Formally, an L-system is a triplet of:

  • an alphabet \(V\) (an arbitrary set of symbols)
  • an axiom \(\omega\), which is a non-empty word of the alphabet (\(\omega \in V^+\))
  • a set of rewriting rules (or productions) \(P\), each mapping a symbol to a word: \(P \subset V \times V^*\). Symbols not present in \(P\) are assumed to be mapped to themselves.

During an iteration, the algorithm takes each symbol in the current word and replaces it by the value in its rewriting rule. Not that the output of the rewriting rule can be absolutely anything in \(V^*\), including the empty word! (So yes, you can generate symbols just to delete them afterwards.)

At this point, an L-system is nothing more than a way to generate very long strings of characters. In order to get something useful out of this, we have to give them meaning.

Drawing instructions and representation

Our objective is to draw the output of the L-system in order to visually inspect the output. The most common way is to interpret the output as a sequence of instruction for a LOGO-like drawing turtle. For instance, a simple alphabet consisting only in the symbols \(F\), \(+\), and \(-\) could represent the instructions “move forward”, “turn right by 90°”, and “turn left by 90°” respectively.

Thus, we add new components to our definition of L-systems:

  • a set of instructions, \(I\). These are limited by the capabilities of our imagined turtle, so we can assume that they are the same for every L-system we will consider:
    • Forward makes the turtle draw a straight segment.
    • TurnLeft and TurnRight makes the turtle turn on itself by a given angle.
    • Push and Pop allow the turtle to store and retrieve its position on a stack. This will allow for branching in the turtle’s path.
    • Stay, which orders the turtle to do nothing.
  • a distance \(d \in \mathbb{R_+}\), i.e. how long should each forward segment should be.
  • an angle \(\theta\) used for rotation.
  • a set of representation rules \(R \subset V \times I\). As before, they will match a symbol to an instruction. Symbols not matched by any rule will be associated to Stay.

Finally, our complete L-system, representable by a turtle with capabilities \(I\), can be defined as \[ L = (V, \omega, P, d, \theta, R). \]

One could argue that the representation is not part of the L-system, and that the same L-system could be represented differently by changing the representation rules. However, in our setting, we won’t observe the L-system other than by displaying it, so we might as well consider that two systems differing only by their representation rules are different systems altogether.

Implementation details

The LSystem data type

The mathematical definition above translate almost immediately in a Haskell data type:

Here, a is the type of the literal in the alphabet. For all practical purposes, it will almost always be Char.

Instruction is just a sum type over all possible instructions listed above.

Iterating and representing

From here, generating L-systems and iterating is straightforward. We iterate recursively by looking up each symbol in rules and replacing it by its expansion. We then transform the result to a list of Instruction.

Drawing

The only remaining thing is to implement the virtual turtle which will actually execute the instructions. It goes through the list of instructions, building a sequence of points and maintaining an internal state (position, angle, stack). The stack is used when Push and Pop operations are met. In this case, the turtle builds a separate line starting from its current position.

The final output is a set of lines, each being a simple sequence of points. All relevant data types are provided by the Gloss library, along with the function that can display the resulting Picture.

Common file format for L-systems

In order to define new L-systems quickly and easily, it is necessary to encode them in some form. We chose to represent them as JSON values.

Here is an example for the Gosper curve:

Using this format, it is easy to define new L-systems (along with how they should be represented). This is translated nearly automatically to the LSystem data type using Aeson.

Variations on L-systems

We can widen the possibilities of L-systems in various ways. L-systems are in effect deterministic context-free grammars.

By allowing multiple rewriting rules for each symbol with probabilities, we can extend the model to probabilistic context-free grammars.

We can also have replacement rules not for a single symbol, but for a subsequence of them, thus effectively taking into account their neighbours (context-sensitive grammars). This seems very close to 1D cellular automata.

Finally, L-systems could also have a 3D representation (for instance space-filling curves in 3 dimensions).

Usage notes

  1. Clone the repository: git clone [[https://github.com/dlozeve/lsystems]]
  2. Build: stack build
  3. Execute stack exec lsystems-exe -- examples/penroseP3.json to see the list of options
  4. (Optional) Run tests and build documentation: stack test --haddock

Usage: stack exec lsystems-exe -- --help

lsystems -- Generate L-systems

Usage: lsystems-exe FILENAME [-n|--iterations N] [-c|--color R,G,B]
                    [-w|--white-background]
  Generate and draw an L-system

Available options:
  FILENAME                 JSON file specifying an L-system
  -n,--iterations N        Number of iterations (default: 5)
  -c,--color R,G,B         Foreground color RGBA
                           (0-255) (default: RGBA 1.0 1.0 1.0 1.0)
  -w,--white-background    Use a white background
  -h,--help                Show this help text

Apart from the selection of the input JSON file, you can adjust the number of iterations and the colors.

stack exec lsystems-exe -- examples/levyC.json -n 12 -c 0,255,255

References

  1. Prusinkiewicz, Przemyslaw; Lindenmayer, Aristid (1990). The Algorithmic Beauty of Plants. Springer-Verlag. ISBN 978-0-387-97297-8. http://algorithmicbotany.org/papers/#abop
  2. Weisstein, Eric W. “Lindenmayer System.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/LindenmayerSystem.html
  3. Corte, Leo. “L-systems and Penrose P3 in Inkscape.” The Brick in the Sky. https://thebrickinthesky.wordpress.com/2013/03/17/l-systems-and-penrose-p3-in-inkscape/
]]>
Thu, 18 Jan 2018 00:00:00 UT https://www.lozeve.com/posts/lsystems.html Dimitri Lozeve