The Mrs. White probability puzzle

tl;dr -I don’t remember how many games of Clue I’ve played but I do remember being surprised by Mrs White being the murderer in only 2 of those games. Can you give an estimate and an upper bound for the number of games I have played?
We solve this problem by using Bayes theorem and discussing the data generation mechanism, and illustrate the solution with R.

The characters in the original game of Clue. Mrs White is third from the left on the first row (and is now retired!)

Making use of external information with Bayes theorem

Having been raised a frequentist, I first tried to solve this using a max likelihood method, but quickly gave up when I realized how intractable it actually was, especially for the upper bound.
This is a problem where conditioning on external knowledge is key, so the most natural way to tackle it is to use Bayes theorem. This will directly yield an interpretable probability for what we’re looking for (most probable number of and uncertainty interval)
Denote an integer n>3 and:
Our notations for the problem
What we want writes as a simple product of quantities that we can compute, thanks to Bayes:
Bayes theorem gives us directly the probability we are looking for
Notice that there is an “proportional to” sign instead of an equal. This is because the denominator is just a normalization constant, which we can take care of easily after computing the likelihood and the prior.
The likelihood indicates the odds of us observing the data (in this case, that k_Mrs_White = 2) given the value of the unknown parameter (here the number of games played). Since at the beginning of each game the murderer is chosen at uniform random between 6 characters, the number of times Mrs White ends up being the culprit can be modeled as a binomial distribution with parameters n and 1/6.
This will be easily obtained using the dbinom function, which gives directly the exact value of P(x = k), for any x and a binomial distribution of parameters n and p. Let’s first import a few useful functions that I put in our GitHub repo to save some space on this post, and set a few useful parameters:

## Parameters
k_mrs_white <- 2 # Number of times Mrs. White was the murderer
prob <- 1/6 # Probability of Mrs. White being the murderer for one game
Note that we can’t exactly obtain the distribution for any game from 1 to infinity, so we actually compute the distribution for 1 to 200 games (this doesn’t matter much in practice):
x <- 1:200 # Reduction of the problem to a finite number of games

## Likelihood
dlikelihood <- dbinom(k_mrs_white, x, prob)
easy enough 🙂
Side note: when I was a student, I kept forgetting that the distribution functions existed in R and whenever I needed them I used to re-generate them using the random generation function (rbinom in this case) 🤦‍♂️
There are a lot of possible choices for the prior but here I’m going to consider that I don’t have any real reason to believe and assume a uniform probability for any number of games between 3 and 200:
dprior1 <- dunifdisc(x,3,100)
plot_clue_prior(x, dprior1)
Uniform prior for all number of games between 3 and 100
First posterior
Using the likelihood and the prior, we can easily compute the posterior, normalize it and plot it:
dposterior1 <- dlikelihood * dprior1
dposterior1 <- dposterior1 / sum(dposterior1)
plot_clue_posterior(x, dposterior1)
Plot of the first posterior computed
We can also compute directly the estimates we’re looking for. The most probable number of games played is 11:
> which.max(dposterior1)
[1] 11
And there is a 95% chance that the number of games is less than 40:
> threshold_val <- 0.975
> which(cumsum(dposterior1) > (threshold_val))[1]
[1] 40

A more realistic data generation mechanism

I find this result very unsatisfying. It doesn’t “feel” right to me that someone would be surprised by only 2 occurrences of Mrs White being guilty in such a small number of games! For example, I simulated 40 games, a number that was supposedly suspiciously high according to the model:
N_sim_games <- 40
sim_murderer <- runifdisc(N_sim_games, 6)

plot_murderer <- ggplot(tibble(x=1:N_sim_games, y=sim_murderer), aes(y, stat(count))) +
  geom_histogram(aes(y =..count..),
                 bins=6, fill="white",colour="black") +
  ylab("Frequency - murderer") +
  xlab("Character #") +
  scale_x_continuous(breaks = 1:6)
Simulating 40 games of Clue. Character #4 and #5 were the murderer in respectively only 2 and 3 games
We observe that characters #4 and #5 are the murderers in respectively only 2 and 3 games!
In the end I think what really counts is not the likelihood that *Mrs White* was the murderer 2 times, but that the *minimum* number of times one of the characters was the culprit was 2 times!
I think it’s a cool example of a problem where just looking at the data available is not enough to make good inference – you also have to think about *how* the data was generated (in a way, it’s sort of a twist of the Monty Hall paradox, which is one of the most famous examples of problems where the data generation mechanism is critical to understand the result).
I wrote a quick and dirty function based on simulations to generate this likelihood, given a certain number of games. I saved the distribution directly in the GitHub (and called it Gumbel since it kinda looks like an extreme value problem) so that we can call it and do the same thing as above:
gumbelclue_2 <- readRDS("clue/dcluegumbel_2.rds")
gumbelclue_2 <- gumbelclue_2[x]

dposterior_gen <- gumbelclue_2 * dprior1
dposterior_gen <- dposterior_gen / sum(dposterior_gen)

plot_clue_posterior(x, dposterior_gen)
Posterior with the new data generation mechanism
The new posterior has the same shape but appears shifted to the right. For example N_games = 50 seems much more likely now! The estimates are now 23 for the number of games:
> which.max(dposterior_gen)
[1] 23
And 51 for the max bound of the uncertainty interval
> threshold_val <- 0.975
> which(cumsum(dposterior_gen) > (threshold_val))[1]
[1] 51

Credits for title image: Yeonsang

[Sampling] Big data and sampling in Ottawa

Tomorrow (November 7th), I’ll give a talk at the Statistics Canada Symposium on survey sampling and big data.

I’ll show how techniques that were developed at official statistics institutes can now be used in the context of big data and machine learning, and add a lot of value. I’ll show some examples with:

  • A/B testing
  • Tracking design
  • Calibration in Machine Learning
  • Network analysis
  • User feedback


And really glad to be returning to Ottawa, even though the trip will be short!



Featured image: Parliament Hill, by Taxiarchos228

Bad recommendations, good algorithm

If you’ve ever shopped online (*cough* Amazon *cough*), you’ve probably experienced the “vacuum cleaner effect”. You carefully buy one expensive item (e.g. a vacuum cleaner) and then you receive dozens of recommendations for other vacuum cleaners to buy: by email, everywhere on the retailer’s website, or sometimes in the ads you see on other websites.

In other terms, Amazon is a 1 trillion dollar company that employs hundreds of data scientists and is incapable of understanding that if you bought an expensive appliance, buying another one of the same category in the next weeks is what you’re *least* likely to do!

But let’s think about the problem for a second. Suggesting item that are similar to what you just bought is actually the core feature of recommendation algorithms! Detecting that it might be inappropriate for some precise categories of items is not an easy task! It would require some careful analysis of the performance by categories, which would be prone to many potential errors: sampling variance, categorization error (maybe some manual tagging would be required), temporal fluctuations, etc.
So fixing this little annoyance for the consumer might take a few weeks of research, a couple months of integration, and still fail in some cases. It could end up costing several hundred thousands of dollars to fix this, not even counting that it could also affect the performance of the global recommendation algorithm.

So the recommendations might be bad, but in the end the algorithm is valuable nonetheless. Remember, machine learning and artificial intelligence are pretty stupid, but they are very valuable!


Recommender systems are awesome! Very excited to say I’ll be at RecSys 2018 in Vancouver next month to learn more about them 🙂


— Featured image: View of downtown Vancouver from the Lookout Tower at Harbour Centre, by Magnus Larsson.

Weighting tricks for machine learning with Icarus – Part 1

Calibration in survey sampling is a wonderful tool, and today I want to show you how we can use it in some Machine Learning applications, using the R package Icarus. And because ’tis the season, what better than a soccer dataset to illustrate this? The data and code are located on this gitlab repo:

weighting ML gitlab

First, let’s start by installing and loading icarus and nnet, the two packages needed in this tutorial, from CRAN (if necessary):


Then load the data:


The RData file contains two dataframes, one for the training set and one for the test set. They contain results of some international soccer games, from 01/2008 to 12/2016 for the training set, and from 01/2017 to 11/2017 for the test. Along with the team names and goals scored for each side, a few descriptive variables that we’re going to use as features of our ML models:

> head(train_soccer)
        Date                   team opponent_team home_field elo_team
1 2010-10-12                Belarus       Albania          1      554
2 2010-10-08 Bosnia and Herzegovina       Albania          0      544
3 2011-06-07 Bosnia and Herzegovina       Albania          0      594
4 2011-06-20              Argentina       Albania          1     1267
5 2011-08-10             Montenegro       Albania          0      915
6 2011-09-02                 France       Albania          0      918
  opponent_elo importance goals_for goals_against outcome year
1          502          1         2             0     WIN 2010
2          502          1         1             1    DRAW 2010
3          564          1         2             0     WIN 2011
4          564          1         4             0     WIN 2011
5          524          1         2             3    LOSS 2011
6          546          1         2             1     WIN 2011

elo_team and opponent_elo are quantitative variables indicative of the level of the team at the date of the game ; importance is a measure of high-profile the game played was (a friendly match rates 1 while a World Cup game rates 4). The other variables are imo self-descriptive.

Then we can train a multinomial logistic regression, with outcome being the predicted variable, and compute the predictions from the model:

outcome_model_unw <- multinom(outcome ~ elo_team + opponent_elo + home_field + importance,
data = train_soccer)

test_soccer$pred_outcome_unw <- predict(outcome_model_unw, newdata = test_soccer)

The sheer accuracy of this predictor is kinda good:

> ## Accuracy
> sum(test_soccer$pred_outcome_unw == test_soccer$outcome) / nrow(test_soccer)
[1] 0.5526316

but it has a problem: it never predicts draws!

> summary(test_soccer$pred_outcome_unw)
   0  208  210

And indeed, draws being less common than other results, it seems more profitable for the algorithm that optimizes accuracy never to predict them. As a consequence, the probabilities of the game being a draw is always lesser than the probability of one team winning it. We could show that the probabilities are not well calibrated.

A common solution to this problem is to use reweighting to correct the imbalances in the sample, which we’ll now tackle. It is important to note that the weighting trick has to happen in the training set to avoid “data leaks”. A very good piece on this subject has been written by Max Kuhn in the documentation of caret.

R package caret

Commonly, you would do:

train_soccer$weight <- 1
train_soccer[train_soccer$outcome == "DRAW",]$weight <- (nrow(train_soccer)/table(train_soccer$outcome)[1]) * 1/3
train_soccer[train_soccer$outcome == "LOSS",]$weight <- (nrow(train_soccer)/table(train_soccer$outcome)[2]) * 1/3
train_soccer[train_soccer$outcome == "WIN",]$weight <- (nrow(train_soccer)/table(train_soccer$outcome)[3]) * 1/3

> table(train_soccer$weight)

0.916067146282974  1.22435897435897 
             3336              1248

The draws are reweighted with a factor greater than 1 and the other games with a factor lesser than 1. This balances the predicted outcomes and thus improves the quality of the probabilities …

outcome_model <- multinom(outcome ~ elo_team + opponent_elo + home_field + importance,
data = train_soccer,
weights = train_soccer$weight)

test_soccer$pred_outcome <- predict(outcome_model, newdata = test_soccer)
> summary(test_soccer$pred_outcome)
  96  167  155

… though at a loss in accuracy:

> ## Accuracy
> sum(test_soccer$pred_outcome == test_soccer$outcome) / nrow(test_soccer)
[1] 0.5263158

Now let’s look at the balance of our training sample on other variables:

> round(table(test_soccer$importance) / nrow(test_soccer),2)

   1    2    3    4 
0.26 0.08 0.54 0.12 
> round(table(train_soccer$importance) / nrow(train_soccer),2)

   1    2    3    4 
0.56 0.08 0.23 0.12

It seems that the test set features a lot more important matches than the training set. Let’s look further, in particular at the dates the matches of the training set were played:

> round(table(train_soccer$year) / nrow(train_soccer),2)

2008 2009 2010 2011 2012 2013 2014 2015 2016 
0.10 0.11 0.11 0.10 0.11 0.13 0.11 0.11 0.12

Thus the matches of each year between 2008 and 2016 have the same influence on the final predictor. A better idea would be to give the most recent games a slightly higher influence, for example by increasing their weight and thus reducing the weights of the older games:

nyears <- length(unique(train_soccer$year))
year_tweak <- rep(1/nyears,nyears) * 1:nyears
year_tweak <- year_tweak * 1/sum(year_tweak) ## Normalization

> year_tweak
[1] 0.02222222 0.04444444 0.06666667 0.08888889 0.11111111 0.13333333
[7] 0.15555556 0.17777778 0.20000000

We determine it is thus a good idea to balance on these two additional variables (year and importance). Now how should we do this? A solution could be to create an indicator variable containing all the values of the cross product between the variables outcome, year and importance, and use the same reweighting technique as before. But this would not be very practical and more importantly, some of the sub-categories would be nearly empty, making the procedure not very robust. A better solution is to use survey sampling calibration and Icarus 🙂

train_soccer$weight_cal <- 1
importance_pct_test <- unname(
table(test_soccer$importance) / nrow(test_soccer),

marginMatrix <- matrix(, nrow = 0, ncol = 1) %>% ## Will be replaced by newMarginMatrix() in icarus 0.3.2
addMargin("outcome", c(0.333,0.333,0.333)) %>%
addMargin("importance", importance_pct_test) %>%
addMargin("year", year_tweak)

train_soccer$weight_cal <- calibration(data=train_soccer, marginMatrix=marginMatrix,
colWeights="weight_cal", pct=TRUE, description=TRUE,
popTotal = nrow(train_soccer), method="raking")

outcome_model_cal <- multinom(outcome ~ elo_team + opponent_elo + home_field + importance,
data = train_soccer,
weights = train_soccer$weight_cal)

test_soccer$pred_outcome_cal <- predict(outcome_model_cal, newdata = test_soccer)

icarus gives a summary of the calibration procedure in the log (too long to reproduce here). We then observe a slight improvement in accuracy compared to the previous reweighting technique:

> sum(test_soccer$pred_outcome_cal == test_soccer$outcome) / nrow(test_soccer)
[1] 0.5478469

But more importantly we have reason to believe that the we improved the quality of the probabilities assigned to each event (we could check this using metrics such as the Brier score or calibration plots) 🙂

It is also worth noting that some algorithms (especially those who rely on bagging, boosting, or more generally on ensemble methods) naturally do a good job at balancing samples. You could for example rerun the whole code and replace the logit regressions by boosted algorithms. You would then observe fewer differences between the unweighted algorithm and its weighted counterparts.

Stay tuned for the part 2, where we’ll show a trick to craft better probabilities (particularly for simulations) using external knowledge on probabilities.

A shiny app to convert sports scores

I’m a huge sports fan, but I certainly don’t have extended knowledge about all team sports. Sometimes when I hear about scores in a sports I’m not quite “fluent” in, I wonder how they would translate in a sports I know better. I guess many people ask the same question from time to time. For instance, three years ago, many americans started wondering how the 7-1 blowout that happened during the World Cup semifinals would translate in basketball, football or hockey. ESPN first came up with an absurd answer, and then Neil Paine of FiveThirtyEight wrote a much more sensible paper on the question.

I created a shiny app that finds a statistical equivalent of a game score in one sports in other sports:

The program is very simple, let me show you on an example how it works. Suppose you want to know how a 103 – 97 home win in basketball translates in other sports.

The program starts by computing the score difference between the two teams (103-97 = +6), and looks how many basketball games have ended with a home team win by 6 points or less. In this case, the number is 30.7% of games.

Histogram and density of score differences in basketball games

Then the program looks among the home wins in other sports what score difference corresponds to the same 30.7% (the 30.7% quantile). This corresponds to +1 in soccer and hockey and +6 in football.

Finally, it does the same operation by comparing the offensive score of the winning team. In 50.4% of basketball games, the home team scores 103 points or less when it wins, which corresponds to 2 scored goals in soccer, 4 in hockey and 28 points scored in football. The final result is thus:

The full code of the shiny app is available on the GitHub page of the project. The dataset is made of all NBA, NHL, NFL and Champions League games since the year 2000. If you want to see other sports, make a pull request or ping us on Twitter or Mastodon!

Marges d’erreurs, approche modèle et sondages

Si cette élection présidentielle aura permis quelque chose, c’est bien d’avoir des discussions intéressantes sur les sondages ! Cette course à quatre est inédite dans l’histoire de la Vème République, et avec les grosses surprises de l’actualité récente (Trump et Brexit), il est normal de s’interroger sur l’incertitude réelle contenue dans ces données de sondages. Je propose donc de parler aujourd’hui des “marges d’erreurs” (dits aussi “intervalles de confiance à 95%”) qui ont pour but de quantifier cette incertitude. Je proposerai aussi une idée pour estimer une marge d’erreur prenant en compte à la fois les sondages (“le plan”) et l’évolution du paysage politique (“le modèle”).

Les “marges d’erreur” légales

Commençons par le début : aujourd’hui, on utilise une formule simple pour estimer les marges d’erreur d’un sondage : on prend le chiffre estimé et on effectue +/- deux fois l’erreur-type du sondage aléatoire simple de même taille. Malheureusement, ce mode de calcul ne repose sur aucun socle mathématique. La méthode utilisée par les instituts français, le sondage par quotas est en réalité très éloigné d’un sondage à probabilités égales, et les marges d’erreurs calculées ainsi ne correspondent pas à grand chose. C’est embêtant pour deux raisons qui peuvent sembler contradictoire :
– l’erreur aléatoire du sondage par quotas est probablement plus faible que celle utilisée pour calculer les marges (ce qui a amené des débats sur le “herding”)
– l’erreur totale est sans nul doute plus forte, car elle contient d’autres termes en plus de l’aléatoire (“vote caché”, profils difficiles à joindre, formulation des questions non neutres, etc.)

Le plan et le modèle

En plus de ces erreurs de mesure, on comprend bien que l’intention de vote sous-jacente des électeurs peut être elle-même variable ! Pour comprendre mieux ce dont on est en train de parler, on peut utiliser la formalisation suivante, empruntée à Binder et Roberts et illustrer avec le sondage politique :

Chaque observation à un instant t des intentions de vote consiste en un sondage en deux phases :

  • 1ère phase (modèle) : les intentions de vote des français varient en fonction des événements et du temps. Ce phénomène (supposé aléatoire) produit une population (ou “super-population”) de taille N = 47 millions, le nombre d’inscrits sur les listes électorales.
  • 2ème phase (plan) : les sondeurs sélectionnent n personnes de la population (typiquement n = 1000) et mesurent les intentions de vote à l’instant t, avec une certaine erreur de mesure.
    Comme le notait récemment Freakonometrics, il est difficile de vraiment séparer les deux phénomènes, et ne prendre en compte que l’erreur d’échantillonnage comme c’est fait aujourd’hui est très peu satisfaisant.

Approche en deux phases modèle / plan selon Binder – Roberts

Notez que l’avantage de la formalisation en deux phases choisie ici est que l’on a :

Erreur totale = Erreur modèle + Erreur de sondage

Une idée simple pour estimer ces marges

Pour le deuxième terme, faute de mieux, on va conserver l’erreur de sondage telle qu’elle est calculée aujourd’hui (avec la formule du sondage aléatoire simple) : elle sur-estime l’erreur aléatoire mais ça n’est pas plus mal car cela permet de prendre en compte au moins en partie l’erreur de mesure (voir ce post qui en parle de façon plus détaillée)

Le premier terme est le plus intéressant ! Une idée très simple pour prendre en compte le modèle et l’erreur de sondage : mettre à profit les deuxièmes choix des électeurs, information que l’on retrouve dans un certain nombre d’enquêtes cette année (par exemple chez Ipsos, en page 11 de ce document). L’idée est que si des événements se produisent qui peuvent faire évoluer les intentions de vote, les électeurs auront tendance à se reporter sur leur deuxième choix plutôt que de changer totalement d’avis. Petite remarque : il faut bien intégrer dans ces choix potentiels la possibilité de l’abstention ou du vote blanc, qui ont bien entendu une influence sur la précision des estimations.

Cette idée permettrait d’intégrer la composante modèle à peu de frais ! Reste bien sûr la question de la quantification, mais je me dis que des règles naïves peuvent suffire à obtenir des estimations d’erreur de bonne qualité. Je serais très curieux de savoir si une définition pareille permet de construire des intervalles de confiance avec de bonnes propriétés de couverture. Je crains cependant que les données de deuxième choix des candidats soient peu disponibles pour les présidentielles précédentes.

Le modèle de “Too close to call” prend justement en compte ces information, et obtient des marges d’erreur très intéressantes :

Distribution de probabilité des scores – modèle Too close to call

Ces marges reflètent en particulier la relative “sûreté” du score de Marine Le Pen, qui semble posséder une base fidèle ; le score d’Emmanuel Macron semble lui beaucoup plus incertain.

Les sondeurs se copient, vraiment ? (le herding)

Un tweet de Nate Silver posté ce lundi semble avoir déchaîné les passions de nombreux observateurs :

Dans ce gazouillis, Nate Silver (célèbre analyste statistique américain, rédacteur en chef du site remarque que les estimations des intentions de vote par les instituts de sondage français sont assez proches les unes des autres, et suggère que cela est dû au fait que les sondeurs se “copient” les uns les autres (afin de limiter le risque d’être le seul institut proposant un résultat très éloigné du score final).  Il nomme ceci le herding.

Un article publié dans The Economist hier lui emboîte le pas en s’intéressant notamment au cas de l’estimation du score de Marine Le Pen. Les autres tentent de montrer que la corrélation qu’on observe entre les différents résultats est improbable au sens statistique du terme, et en concluent qu’il y a nécessairement une intervention.

J’ai quelques doutes sur la validité de cette analyse.

Erreur en sondages

L’erreur totale des sondages est composée de deux termes :

Erreur totale de mesure = Erreur d’échantillonnage + Erreur d’observation

  • L’erreur d’échantillonnage vient du fait qu’on ne demande pas leur intention de vote à tous les français mais à seulement un petit nombre d’entre eux, typiquement entre 1000 et 2000 (cela a un coût, que l’on paye en précision). C’est l’erreur aléatoire. On suppose généralement que les tirages sont indépendants et, faute de mieux, on estime cette erreur en utilisant la variance du sondage aléatoire simple de même taille d’échantillon. Rappelons que procéder ainsi ne repose sur aucune règle mathématique rigoureuse !
  • L’erreur d’observation regroupe beaucoup de choses diverses qui ne sont pas vraiment quantifiables, mais qui ont une importance. Par exemple, l’influence de la formulation des questions, la sous-déclaration de votes “honteux”, etc. Notons qu’il y a de fortes chances pour que cette erreur d’observation soit très corrélée entre les instituts de sondage : si vous ne souhaitez pas dévoiler votre vote à un sondeur, je doute que cela change suivant que ledit sondeur travaille pour l’Ifop ou la Sofres.

Ainsi, l’étonnement des auteurs concerne l’erreur aléatoire d’échantillonnage – et c’est bien celle qui est considérée dans leur “test statistique”.

La spécificité française : quotas et redressement

Pour un sondage américain typique, la réflexion fonctionne très bien car l’erreur d’échantillonnage estimée en utilisant la formule du sondage aléatoire simple est en général une sous-estimation de l’erreur d’échantillonnage réelle. L’article original de Nate Silver sur le herding est convainquant à cet égard.

Pour un sondage politique français, c’est beaucoup plus compliqué car les méthodes utilisées (notamment les quotas et l’utilisation intensive de redressements) sont très différentes des méthodes américaines ! La méthode des quotas et le redressement permettent, lorsque les variables mises en jeu (âge, géographie, catégorie socio-professionnelle et vote passé principalement) expliquent correctement le phénomène mesuré (les intentions de vote pour dimanche), de réduire sensiblement l’erreur d’échantillonnage.

De plus, j’ai “l’intuition” que le mode de sélection par quotas et le redressement (qui ne sont en fait pas aléatoire) peuvent eux-mêmes conduire à une corrélation des erreurs d’échantillonnage entre les instituts. J’espère vraiment avoir l’occasion dans des travaux futurs de proposer un modèle pour pouvoir tester cette idée ! La littérature sur les sondages par quotas est très peu développée et on ne peut que le regretter.

Ces deux arguments montrent que la variabilité des sondages “attendue” par les auteurs de l’article de The Economist est peut-être bien plus importante que leur variabilité réelle. Leur “probabilité” estimée que les sondages n’aient pas subi d’intervention est donc à mon avis très largement surestimée, et leur conclusion me semble hâtive.

Autrement dit à propos de leur méthodologie : le fait que peu de sondages sortent des marges d’erreur ne montre pas nécessairement que les sondeurs “trichent”, mais tout simplement… que leurs marges d’erreur sont mal calculées !

Reste… le risque !

Agrégé des estimations d’intentions de vote – Will Jennings and Chris Wlezien, The Economist

Il reste que cette corrélation entre les résultats est à double tranchant. Rien ne garantit que l’erreur totale des sondages français est inférieure à l’erreur totale des sondages américains. En résumé, la méthode française est sans doute plus risquée : il y a des chances que les résultats soient plus précis qu’avec la méthode “américaine”, mais en contrepartie, s’il y a une erreur, tous les sondages seront éloignés de la réalité à la fois ! Etant donné que la course à quatre de cette année est inédite dans l’histoire de la Vème République, rien ne garantit que l’on n’ait pas une grosse surprise dimanche à 20h !

A bientôt pour un post sur les marges d’erreur en sondages politique !

Illustrations : graphiques de l’article de The Economist, par Will Jennings et Chris Wlezien. Je ne possède pas les droits de ces images.

Sampling graphs – MAD-Stat Seminar at Toulouse School of Economics

Tomorrow (march 23rd), I’ll be presenting my work on sampling designs for graph (and particularly extension sampling designs, with an application to Twitter data) at the MAD Stat seminar of the Toulouse School of Economics. Here are my slides:


Announcing Icarus v0.3

This weekend I released version 0.3.0 of the Icarus package to CRAN.

Icarus provides tools to help perform calibration on margins, which is a very important method in sampling. One of these days I’ll write a blog post explaining calibration on margins! In the meantime if you want to learn more, you can read our course on calibration (in French) or the original paper of Deville and Sarndal (1992). Shortly said, calibration computes new sampling weights so that the sampling estimates match totals we already know thanks to another source (census, typically).

In the industry, one of the most widely used software for performing calibration on margins is the SAS macro Calmar developed at INSEE. Icarus is designed with the typical Calmar user in mind if s/he whishes to find a direct equivalent in R. The format expected by Icarus for the margins and the variables is directly inspired by Calmar’s (wiki and example here). Icarus also provides the same kind of graphs and stats aimed at helping statisticians understand the quality of their data and estimates (especially on domains), and in general be able to understand and explain the reweighting process.

Example of Icarus in RStudio
Example of Icarus in RStudio

I hope I find soon the time to finish a full well documented article to submit to a journal and set it as a vignette on CRAN. For now, here are the slides (in French, again) I presented at the “colloque francophone sondages” in Gatineau last october:

Kudos to the CRAN team for their amazing work!

A winning strategy at the lottery

tl;dr – It is possible to construct a winning strategy at the lottery by choosing the numbers that other people rarely select. We discuss this and prove it on a small example.


There are many things I don’t like with so-called math reasoning and lotteries, and I wanted to write about it for a very long time. So, on the one hand we have the classic scammers who try to sell you the “most probable numbers” (or alternatively the “numbers that are due”). Of course, neither strategy is mathematically valid (because the draws are independent). On the other hand, many “educated” and “rational” people argue that, given that the expected value of a lottery ticket is negative (because the probability of wining a prize at the lottery is very low), smart people should never buy lottery tickets.

Comic by Zach Wiener,
Comic by Zach Wiener,

Now what if we could find a (mathematically correct!) strategy to make the expected value of our ticket positive? The idea is to choose the numbers that other players choose the least often, so that when we win a prize, it will be divided among fewer other players. But will it be enough to make a significant difference?

The example

Let’s consider a lottery where players have to choose 6 numbers out of 19. The total number of players is 10000. The favorite numbers of the players are 1, 2, 3, 4, 5 and the least favorite are 15, 16, 17, 18, 19. They are respectively selected 2 times more often and 2 times less often than the other numbers 6 –  14. The company who runs the lottery decides to give the players back 90 percent of the amount of the tickets (thus ensuring a 10% profit) depending on the number of numbers they have chosen that also are in the right combination:

  • 0 or 1 correct number: 0%
  • 2 correct numbers: 42%, shared with other winners
  • 3 correct numbers: 10%, shared with other winners
  • 4 correct numbers: 3%, shared with other winners
  • 5 correct numbers: 4%, shared with other winners
  • 6 correct numbers (the jackpot): 40%, shared with (the eventual) other winners

Then we compute the expected value for each ticket that was bought. You can find the R code I used on my GitHub page. I plotted the expected gains against an indicator of the rarity of the combination chosen by each player (the harmonic mean of the inclusion probabilities):


Expected gains wrt a measure of the frequency of the combination chosen

As we predicted, the expected gains are higher if you chose an “unpopular” combination. But what impresses me most is the order of magnitude of the effect. It is indeed possible to find a combination that yields a positive expected value (points on the left that are above the red line)!

Further work

I have no idea how all this works when we change the parameters of the problem: numbers to choose from (49 in France for example), number of players, choices of the players (inclusion probabilities of the numbers), payoffs, etc. I bet that the shape of the curve remains the same, but I wonder how high the expected value can get for the rarest combinations, and if it is always possible to find a winning strategy. I might try to work on an analytical solution when I find some time because I believe it involves some sampling theory.

Finally, a question to all people who never play the lottery because the expected value is negative, would you start buying tickets now that you know there exists a strategy with positive expected value?

Comic by Zach Wiener,
Comic by Zach Wiener,

PS: Henri pointed out chapter 11 of Jordan Ellenberg’s “How not to be wrong” which deals with interesting mathematical facts about the lottery, including a similar discussion as this post. Be sure to check it out, it’s really great!