Category Archives: Non classé

Au-delà de la procédure, quand “bien calibrer” ne suffit pas à être juste

Quand on parle d’IA “responsable”, souvent, on englobe deux choses. La fiabilité (on comprend ce qu’on fait) et l’équité (on traite tout le monde pareil). Dit comme ça, ça semble simple et clair. Mais forcément, dans la vraie vie, c’est un peu plus subtil. En particulier on peut avoir une procédure statistiquement irréprochable, juste… et produire quand même des décisions inéquitables, une fois mise en place. C’est ce qu’on essayait de comprendre (et de mesurer) dans “Beyond Procedure: Substantive Fairness in Conformal Prediction“, coécrit avec Pengqi Liu, Zijun Yu, Mouloud Belbahri, Masoud Asgharian, et Jesse Cresswell: la conformité d’une procédure ne garantit pas la justice de ses effets.

Passer de la “fairness” de la méthode à la “fairness” des conséquences

Cette distinction rappelle des discussions en cours d’éthique : faut-il dire qu’un système est juste parce que sa règle est la même pour tous (vision procédurale, proche d’une éthique des principes), ou parce qu’il produit des effets équitables (vision conséquentialiste) ? Ici, l’enjeu n’est pas tant de “maximiser” un score global que de vérifier que l’aide fournie ne profite pas surtout à certains groupes. En terme méthodologique, notre article s’inscrit dans la littérature sur la prédiction conforme (conformal prediction, CP). L’intuition est assez simple pour des classifieurs (c’est le cadre qu’on regarde ici). Au lieu de prédire une seule étiquette (“il va pleuvoir”, “c’est un médecin”, “c’est la classe 7”, “ce revenu est dans telle tranche”), on prédit un ensemble de réponses plausibles. Avec un degré de confiance. Par exemple “je suis sûr à 90% que la bonne réponse est dans cette liste.” Cette promesse, on appelle ça la couverture. À un niveau 90%, CP garantit que, en moyenne, la vérité est bien dans l’ensemble retourné. Autrement dit, peu importe le modèle, peu importe la distribution, on a une garantie statistique robuste. Mais dans la vraie vie, personne ne décide à partir d’une garantie abstraite de couverture. On décide à partir de l’ensemble de prédictions fournies. Et cet ensemble peut varier fortement d’une personne à l’autre, ou d’un groupe à l’autre.

  • Si l’ensemble contient 1 réponse, c’est presque une décision automatique.
  • S’il en contient 7, c’est une aide beaucoup plus vague : on hésite, on délègue, on choisit “au feeling”, ou on s’en remet à un autre processus.

Autrement dit, une même “garantie à 90%” peut se traduire par des niveaux d’aide très différents. Pour revenir à ce que je disais au début, on fait une distinction centrale dans le papier entre :

  • la Fairness procédurale : la méthode respecte des critères “internes” (ex. même couverture par groupe).
  • la Fairness substantive : au final, l’outil améliore (ou dégrade) l’équité des résultats et des bénéfices entre groupes.

Mais “égaliser la couverture” peut aggraver l’iniquité

Dans la littérature, une idée a longtemps semblé naturelle. Si on veut être juste entre groupes (genre, âge, origine…), alors il faut que la garantie statistique soit la même pour tous. En CP, cela conduit à ce qu’on appelle l’Equalized Coverage : calibrer séparément par groupe, pour que chacun obtienne, disons, 90% de couverture. Sur le plan procédural, c’est pas mal, mais sur le plan des conséquences, le papier montre que cela peut être un mauvais objectif. Pourquoi ? Tout simplement parce que calibrer par groupe revient à découper les données de calibration. Dans ce cas, certains groupes ont moins d’exemples, ce qui rend les seuils plus instables. Et pour tenir la couverture, on compense souvent en produisant des ensembles plus grands pour certains groupes. Et si un groupe reçoit systématiquement des ensembles plus larges, il reçoit une aide moins facile à utiliser en pratique.

Le papier propose alors en avant un autre indicateur procédural, plus proche des effets : l’Equalized Set Size (parité de taille des ensembles). Et ce qu’on montre, c’est que dans les expériences, la parité de taille est fortement associée à une meilleure équité des résultats, tandis que la parité de couverture est souvent corrélée à une équité plus mauvaise. Dit autrement, optimiser le bon niveau de couverture peut pousser dans la mauvaise direction du point de vue social.

Mesurer l’équité “substantive” sans mobiliser des centaines de participants

En pratique, évaluer l’équité des conséquences est coûteux, puisqu’il faudrait idéalement des expériences avec des humains, parce que ce sont eux (ou leurs règles décisionnelles) qui transforment l’ensemble de prédiction en décision. On a essayé d’être pragmatique, en remplaçant l’évaluateur humain par un LLM dans un protocole contrôlé (LLM-in-the-loop), de façon à simuler l’usage des ensembles de prédiction comme “aide à la décision”, à grande échelle, sur plusieurs modalités (image, texte, audio, tabulaire). L’idée n’est pas de dire que “les LLM pensent comme nous” en général, mais de construire un protocole où l’on peut donner au modèle une tâche (ex. prédire une profession, une émotion, une tranche de revenu), lui donner (ou non) l’ensemble conforme + une phrase de garantie (“la vraie réponse est dedans avec 90% de confiance”) et mesurer combien l’aide améliore l’exactitude, et surtout si cette amélioration est partagée équitablement entre groupes. Pour quantifier cette équité, on utilise une mesure inspirée des essais contrôlés, la disparité maximale de bénéfice entre groupes, résumée par un indicateur de type maxROR (une façon de comparer l’ampleur du “gain” entre groupes). Plus maxROR est faible, plus l’amélioration procurée par l’outil est équitable.

La taille des ensembles explique mieux l’équité réelle que la couverture

Sur quatre tâches (vision, texte, audio, données tabulaires) et plusieurs méthodes, on a un constat assez robuste. Tout d’abord, les méthodes qui cherchent à égaliser la couverture (Mondrian, group-clustered) ne sont pas celles qui donnent les meilleurs résultats en équité “substantive”. Mais en plus,  les méthodes qui réduisent les écarts de taille d’ensemble (en particulier Label-Clustered CP, et parfois Backward CP) tendent à produire une amélioration plus équitable. Autrement dit, la prédiction conforme donne une garantie statistique particulièrement intéressante, mais la justice réelle se joue dans l’usage, et on montre que, pour des décisions assistées, l’égalité de taille des ensembles est souvent un meilleur levier d’équité que l’égalité de couverture.

Catastrophes naturelles, catastrophes évitables ou imprévisibles ?

On a tous vu les images. Et elles sont incroyables. Comme de nombreuses catastrophes naturelles.

Le 25 janvier, Niscemi, petite ville sicilienne, s’est ouvert en deux, suite aux pluies torrentielles associées au cyclone Harry, avec une cicatrice de plusieurs kilomètres. On a vu les routes qui s’effondrent, les voitures qui disparaissent, les maisons qui restent suspendues au bord d’un vide. Plus de 1 600 personnes ont été évacuées. Dans l’article du Guardian, on nous rappelle que ce n’est pas la première fois. On nous explique que le même secteur avait déjà glissé au XVIIIe siècle, puis à nouveau en 1997, et pourtant les constructions ont continué, notamment à partir des années 1950 et 1960.

Est-ce qu’on aurait pu savoir ? Est-ce qu’on savait déjà ? Et si on savait, pourquoi ça arrive quand même ? Mine de rien, à chaque catastrophe naturelle, j’ai souvent que ces questions reviennent elles aussi, invariablement… Je me disais que je pourrais écrire un court billet, rappelant que d’un côté, il existe des régularités étonnantes dans la façon dont certaines catastrophes se déclenchent. Mais pour autant, de l’autre, “prévisible” ne veut pas dire “évitable”, parce que la catastrophe est aussi un fait social, une histoire de vulnérabilité, d’exposition et de décisions publiques (au risque de me répéter, je sais).
Continue reading Catastrophes naturelles, catastrophes évitables ou imprévisibles ?

Insurance, biases, discrimination and fairness

Almost two years ago, “Insurance, Biases, Discrimination and Fairness” was published.  A quick note: the book was initially based on a (long) report published by the Institut Louis Bachelier, in both French and English (with links on my blog)
☐ French : https://freakonometrics.hypotheses.org/63834
☐ English : https://freakonometrics.hypotheses.org/63866
Since these links (on the ILB website) are now dead (and I can’t find the reports on the website anymore – 404 error), I re-uploaded both versions — people often ask me for them.
☑︎ Report (EN): https://freakonometrics.hypotheses../..Gb.pdf
☑︎ Report (FR): https://freakonometrics.hypotheses../..Fr.pdf
(Much more material can be found on the blog…)

Il y a bientôt deux ans paraissait l’ouvrage “Insurance, Biases, Discrimination and Fairness”. Je précise qu’il s’appuyait initialement sur un (long) rapport publié par l’Institut Louis Bachelier, en français et en anglais (j’en avais alors parlé sur mon blog) :
☐ Français : https://freakonometrics.hypotheses.org/63834
☐ Anglais : https://freakonometrics.hypotheses.org/63866
Les liens sur le site de l’ILB étant désormais inaccessibles (et ne retrouvant plus le rapport sur le site), j’ai remis en ligne les deux versions — on me les demande souvent.
☑︎ Rapport (EN) : https://freakonometrics.hypotheses../..Gb.pdf
☑︎ Rapport (FR) : https://freakonometrics.hypotheses../..Fr.pdf
(Et au passage, beaucoup d’autres ressources sont disponibles sur mon blog…)

Insuring AI: New risks? New models?

Recently, Lukasz Szpruch, Agni Orfanoudaki, Carsten Maple, Matthew Wicker, Yoshua Bengio, Kwok-Yan Lam and Marcin Detyniecki posted a paper entitled Insuring AI: Incentivising Safe and Secure Deployment of AI Workflows. I came across it recently, and it strikes me as a good opportunity to complement the post I published last month, Insurers and Insurers and AI, a systemic risk The paper starts from a diagnosis that many people share: AI is spreading everywhere, and with it come risks that are hard to measure (sometimes already present but “silent” in existing insurance policies). The authors argue for dedicated insurance (AI insurance) and governance. They also emphasize (i) the lack of historical data, (ii) the dynamic nature of models, (iii) accumulation/correlation risks, and they conclude that a “paradigm shift” in pricing is needed: moving away from past experience toward a priori performance and evaluation data.

My point here is simple (and not polemical): this diagnosis is useful, but it leaves an important blind spot. A large part of these difficulties is not really new for insurance. They have structured, for decades, the scientific literature on insurability, accumulation, catastrophe modeling, uncertainty (epistemic vs aleatory), information asymmetry—and even the question of bias and discrimination. In other words: there are genuine novelties (speed, scale, technological dependencies, updates), but the methodological toolbox developed over more than a century is not outdated. If I dared, I would say it is precisely designed to deal with poorly observed, unstable, socially sensitive risks—provided it is extended with well-written contracts.
Continue reading Insuring AI: New risks? New models?

Pareto models for top incomes and wealth

Our article, Pareto models for top incomes and wealth, writen with Emmanuel Flachaire, just got published in the Special Issue of the The Journal of Economic Inequality, on “Finding the Upper Tail”.

Top incomes are often related to Pareto distribution. To date, economists have mostly used Pareto Type I distribution to model the upper tail of income and wealth distribution. It is a parametric distribution, with interesting properties, that can be easily linked to economic theory. In this paper, we first show that modeling top incomes with Pareto Type I distribution can lead to biased estimation of inequality, even with millions of observations. Then, we show that the Generalized Pareto distribution and, even more, the Extended Pareto distribution, are much less sensitive to the choice of the threshold. Thus, they can provide more reliable results. We discuss different types of bias that could be encountered in empirical studies and, we provide some guidance for practice. To illustrate, two applications are investigated, on the distribution of income in South Africa in 2012 and on the distribution of wealth in the United States in 2013.

« Plus un pays est égalitaire et prospère, moins on trouve de femmes en sciences »

Je suis tombé sur cette phrase au détour d’un article cet après midi, dans La Presse,

« Plus un pays est égalitaire et prospère, moins on trouve de femmes en sciences. C’est difficile à comprendre »

et j’avoue que je suis surpris. Surpris que cette relation soit forte, et significative, au point de l’énoncer comme une loi. Je ne sais pas comment se mesurent l’égalité et la prospérité, mais j’ai tenté l’espérance de vie à la naissance, sur http://data.uis.unesco.org/. Et “researchers FTE” (nombre de chercheurs en équivalents temps plein), femme divisé par le total, pour avoir un ratio de femmes en “Science, technology and innovation“. J’ai du mal à observer la relation décroissante…

A moins d’enlever une dizaines de pays à faible espérance de vie à la naissance (dont le Burundi, l’Éthiopie, la Gambie, l’Inde, Madagascar, le Pakistan, le Togo).

Si quelqu’un sait comment voire cette étonnante relation décroissante, je suis preneur !

R0 and the exponential growth of a pandemic, an update

A few days ago, I wrote a blog post – R0 and the exponential growth of a pandemic – where I was trying to generate some visualization of some exponential growth, in the context of a pandemic. After giving some thoughts, the previous graph might not be the best one to see an exponential based contagion.

Having graphs evolving, from the left to the right, gives us the (false) idea of some temporal evolution. Which is no necessarily correct. It simply means that contaminated people will contaminate other people, and we look at the number of iterations here. So maybe some concentric dots would look better.

And from a technical perspective, what I did was fun, but probably too complicated. In my previous post, I wanted to pack optimally k identical disks intro a unit circle. On http://hydra.nat.uni-magdeburg.de/packing, it was possible to get the “best known packings of equal circles in a circle”, with the coordinates. But as we will see, we can use something much more simple here.

My idea is now to create some picture like one below, with concentric colored dot. In the center, we have the first people that were contaminated, and then, we can see the transmission, somehow

From a technical perspective, here, I use a different strategy. I decided to draw random points, uniformly. The problem with randomness is the natural high discrepancy, with monte carlo methods: it is very likely that some disks will overlap. It is not a major issue, but it might distort the message. So I decided to use some low-discrepancy sequences, such as Halton‘s sequence.

library(randtoolbox)
S = halton(n=5000, dim = 2)*2-1

Here, I have disk coordinates in [-1,+1]^2. Then, to get disks in a circle, I simply compute the distance to the origin (0,0),

D0 = S[,1]^2+S[,2]^2

and take the ranks. If I want to visualize k=200 people, I consider the 200 smaller ranks. To get concentric circles, each part having k_i individuals, I use as thresholds R_0^{\bar k_{i-1}},R_0^{\bar k_{i}},R_0^{\bar k_{i+1}}, etc, where \bar k_i=\bar k_{i-1}+k_i,

R0 = rank(D0,ties.method = "random")
C0 = as.numeric(cut(R0,c(0,cumsum(k)+.5)),100000)

where

R0=1.8
k=round(R0^(seq(1,9,by=2)))

Then we can plot the dots, with appropriate colors,

points(S,pch=19,col=colrpal[C0],cex=.75)

And of course, we can try that with different values, for R_0

R0=2.2
k=round(R0^(seq(1,9,by=2)))
kmax=max(k)  
S = halton(n=5000, dim = 2)*2-1
plot(S,col="light yellow",axes=FALSE,xlab="",ylab="",xlim=c(-1.3,1),ylim=c(-1,1),cex=.75,pch=19)
D0 = S[,1]^2+S[,2]^2
R0 = rank(D0,ties.method = "random")
C0 = as.numeric(cut(R0,c(0,cumsum(k)+.5)),100000)
points(S,pch=19,col=colrpal[C0],cex=.75)

Modeling Joint Lives within Families

With Olivier Cabrignac and Ewen Gallic, we recently uploaded a research paper, entitled “Modeling Joint Lives within Families

Family history is usually seen as a significant factor insurance companies look at when applying for a life insurance policy. Where it is used, family history of cardiovascular diseases, death by cancer, or family history of high blood pressure and diabetes could result in higher premiums or no coverage at all. In this article, we use massive (historical) data to study dependencies between life length within families. If joint life contracts (between a husband and a wife) have been long studied in actuarial literature, little is known about child and parents dependencies. We illustrate those dependencies using 19th century family trees in France, and quantify implications in annuities computations. For parents and children, we observe a modest but significant positive association between life lengths. It yields different estimates for remaining life expectancy, present values of annuities, or whole life insurance guarantee, given information about the parents (such as the number of parents alive). A similar but weaker pattern is observed when using information on grandparents.

The paper is online on https://arxiv.org/abs/2006.08446.

Lasso Regression (home made)

Again, this post is related to my MAT7381 course, where we will see that it is actually possible to write our own code to compute Lasso regression, \min\left\lbrace\frac{1}{2}\|\mathbf{y}-\mathbf{X}\mathbf{\beta}\|_{\ell_2}^2+\lambda\|\mathbf{\beta}\|_{\ell_1}\right\rbraceWe have to define the soft-thresholding functionS(z,\gamma)=\text{sign}(z)\cdot(|z|-\gamma)_+=\begin{cases}z-\gamma&\text{ if }\gamma>|z|\text{ and }z<0\\z+\gamma&\text{ if }\gamma<|z|\text{ and }z<0 \\0&\text{ if }\gamma\geq|z|\end{cases}The R function would be

soft_thresholding = function(x,a){
sign(x) * pmax(abs(x)-a,0)
}

To solve our optimization problem, set\mathbf{r}_j=\mathbf{y} - \left(\beta_0\mathbf{1}+\sum_{k\neq j}\beta_k\mathbf{x}_k\right)=\mathbf{y}-\widehat{\mathbf{y}}^{(j)}
so that the optimization problem can be written, equivalently
\min\left\lbrace\frac{1}{2n}\sum_{j=1}^p [\mathbf{r}_j-\beta_j\mathbf{x}_j]^2+\lambda |\beta_j|\right\rbrace
hence\min\left\lbrace\frac{1}{2n}\sum_{j=1}^p \beta_j^2\|\mathbf{x}_j\|-2\beta_j\mathbf{r}_j^T\mathbf{x}_j+\lambda |\beta_j|\right\rbrace
and one gets
\beta_{j,\lambda} = \frac{1}{\|\mathbf{x}_j\|^2}S(\mathbf{r}_j^T\mathbf{x}_j,n\lambda)
or, if we develop
\beta_{j,\lambda} = \frac{1}{\sum_i x_{ij}^2}S\left(\sum_ix_{i,j}[y_i-\widehat{y}_i^{(j)}],n\lambda\right)
Again, if there are weights \mathbf{\omega}=(\omega_i), the coordinate-wise update becomes
\beta_{j,\lambda,{\color{red}{\omega}}} = \frac{1}{\sum_i {\color{red}{\omega_i}}x_{ij}^2}S\left(\sum_i{\color{red}{\omega_i}}x_{i,j}[y_i-\widehat{y}_i^{(j)}],n\lambda\right)
The code to compute this componentwise descent is

lasso_coord_desc = function(X,y,beta,lambda,tol=1e-6,maxiter=1000){
  beta = as.matrix(beta)
  X = as.matrix(X)
  omega = rep(1/length(y),length(y))
  obj = numeric(length=(maxiter+1))
  betalist = list(length(maxiter+1))
  betalist[[1]] = beta
  beta0list = numeric(length(maxiter+1))
  beta0 = sum(y-X%*%beta)/(length(y))
  beta0list[1] = beta0
  for (j in 1:maxiter){
    for (k in 1:length(beta)){
      r = y - X[,-k]%*%beta[-k] - beta0*rep(1,length(y))
      beta[k] = (1/sum(omega*X[,k]^2))*
        soft_thresholding(t(omega*r)%*%X[,k],length(y)*lambda)
    }
    beta0 = sum(y-X%*%beta)/(length(y))
    beta0list[j+1] = beta0
    betalist[[j+1]] = beta
    obj[j] = (1/2)*(1/length(y))*norm(omega*(y - X%*%beta - 
           beta0*rep(1,length(y))),'F')^2 + lambda*sum(abs(beta))
    if (norm(rbind(beta0list[j],betalist[[j]]) - 
             rbind(beta0,beta),'F') &lt; tol) { break } 
  } 
  return(list(obj=obj[1:j],beta=beta,intercept=beta0)) }

For instance, consider the following (simple) dataset, with three covariates

chicago = read.table("http://freakonometrics.free.fr/chicago.txt",header=TRUE,sep=";")

that we can “normalize” (or “standardize“)

X = model.matrix(lm(Fire~.,data=chicago))[,2:4]
for(j in 1:3) X[,j] = (X[,j]-mean(X[,j]))/sd(X[,j])
y = chicago$Fire
y = (y-mean(y))/sd(y)

To initialize the algorithm, use the OLS estimate

beta_init = lm(Fire~0+.,data=chicago)$coef

For instance

lasso_coord_desc(X,y,beta_init,lambda=.001)
$obj
[1] 0.001014426 0.001008009 0.001009558 0.001011094 0.001011119 0.001011119
 
$beta
          [,1]
X_1  0.0000000
X_2  0.3836087
X_3 -0.5026137
 
$intercept
[1] 2.060999e-16

and we can get the standard Lasso plot by looping,

October, grant proposal season

In 2012, Danielle Herbert, Adrian Barnett, Philip Clarke and Nicholas Graves published an article entitled “on the time spent preparing grant proposals: an observational study of Australian researchers“, whose conclusions had been included in Nature under a more explicit title, “Australia’s grant system wastes time” ! In this study, they included 3700 grant applications sent to the National Health and Medical Research Council, and showed that each application represented 37 working days: “Extrapolating this to all 3,727 submitted proposals gives an estimated 550 working years of researchers’ time (95% confidence interval, 513-589)“. But in these times when I have to write my funding application, I find that losing 37 days of work is huge. Because it’s become the norm! And somehow, it’s sad.

Forget about the crazy idea that I would rather, in fact, spend more time doing my research. In fact, the thought I had this morning was that it is rather sad that in the Faculty of Science, mathematicians are asked to spend a considerable amount of time, comparable to that required of physicists or chemists, for often smaller amounts of funding… And I thought it could be easily verified. We start by retrieving the discipline codes

url="http://www.nserc-crsng.gc.ca/NSERC-CRSNG/FundingDecisions-DecisionsFinancement/ResearchGrants-SubventionsDeRecherche/ResultsGSC-ResultatsCSS_eng.asp"
download.file(url,destfile = "GSC.html")
library(XML)
tables=readHTMLTable("GSC.html")
GSC=tables[[1]]$V1
GSC=as.character(GSC[-(1:2)])
namesGSC=tables[[1]]$V2
namesGSC=as.character(namesGSC[-(1:2)])

We’re going to need a small function, to remove the $ and other symbols that pollute the data (and prevent them from being treated as numbers)

library(stringr)
Correction = function(x) as.numeric(gsub('[$,]', '', x))

We will now read the 12 pages, and harvest (we will just take the 2017 data, but we could go back a few years before)

grants= function(gsc){
     url=paste("http://www.nserc-crsng.gc.ca/NSERC-CRSNG/FundingDecisions-DecisionsFinancement/ResearchGrants-SubventionsDeRecherche/ResultsGSCDetail-ResultatsCSSDetails_eng.asp?Year=2017&amp;GSC=",gsc,sep="")
    download.file(url,destfile = "GSC.html")
    library(XML)
    tables=readHTMLTable("GSC.html")
    X=as.character(tables[[1]]$"Awarded Amount")
    A=as.numeric(Vectorize(Correction)(X))
return(c(median(A),mean(A),as.numeric(quantile(A,(1:99)/100))))
}
M=Vectorize(grants)(GSC[1:12])

The average amounts of individual grants can be compared,

barplot(M[2,])

In mathematics, the average grant amount is $24400. If we normalize by this quantity, we obtain

barplot(M[2,]/M[2,8])

In other words, the average amount of a (individual) grant in chemistry (to pay for students, conferences, etc.) is twice that in mathematics, 60% higher in physics than in maths…

We can also look at the median values (rather than the averages)

barplot(M[1,])

Here again, it is in mathematics that it is the weakest….

barplot(M[1,]/M[1,8])

in comparable proportions. If we think that the time spent writing should be proportional to the amount allocated, we should spend half as much time in math as in chemistry.

Cumulative functions can also be ploted,

plot(M[3:101,8],(1:99)/100,type="s",xlim=range(M))
lines(M[3:101,5],(1:99)/100,type="s",col="red")
lines(M[3:101,4],(1:99)/100,type="s",col="blue")

with math in black, physics in red, and chemistry in blue. What is surprising is the bottom part: a “bad” researcher in chemistry or physics will earn more than the median researcher in mathematics…

Now that my intuition is confirmed, I have to go back, writing my proposal… and explain to my coauthors that I have to postpone some research projects because, well, you know…

Tests non-paramétriques et simulations

Lors du dernier cours de statistique, nous avons présenter les tests d’ajustment de lois. Nous avions illustré ces tests à partir de la taille d’individus (déjà utilisé pour présenter l’ajustement de lois, et l’estimation de densité), correspondant à https://latex.codecogs.com/gif.latex?\boldsymbol{x}=\{x_1,\cdots,x_n\}.

> Davis=read.table(
+ "http://socserv.socsci.mcmaster.ca/jfox/Books/Applied-Regression-2E/datasets/Davis.txt")
> Davis[12,c(2,3)]=Davis[12,c(3,2)]
> X=Davis$height
> n=length(X)

On notera https://latex.codecogs.com/gif.latex?%20(x_{i:n}) la statistique d’ordre, au sens où

https://latex.codecogs.com/gif.latex?%20x_{1:n}\leq%20x_{2:n}\leq\cdots\leq%20x_{n-1:n}\leq%20x_{n:n}

Parmi les outils graphiques, nous avons vu le PP plot (graphique probabilité-probabilité) et le QQ plot (graphique quantile). Le code pour créer un PP plot peut être le suivant

> PP=function(Y,F=pnorm){
+   n=length(Y)
+   x=F(sort(Y))
+   y=seq(1/n/2,1-1/n/2,by=1/n)
+   return(data.frame(x=x,y=y))
+ }

qui représente (à un détail près) le nuage de points

https://latex.codecogs.com/gif.latex?\left\{F_0(x_{i:n}),\frac{i}{n}\right\}

et celui pour le QQ plot serait

> QQ=function(Y,Q=qnorm){
+   n=length(Y)
+   x=Q(seq(1/n/2,1-1/n/2,by=1/n))
+   y=sort(Y)
+   return(data.frame(x=x,y=y))
+ }

qui représente (toujours à un détail près) le nuage de points

https://latex.codecogs.com/gif.latex?%20\left\{F_0^{-1}\left(\frac{i}{n}\right),x_{i:n}\right\}

où https://latex.codecogs.com/gif.latex?%20F_0 est la loi que l’on cherche à tester, au sens où on a https://latex.codecogs.com/gif.latex?%20H_0:F=F_0 avec comme hypothèse alternative https://latex.codecogs.com/gif.latex?%20H_1:F\neq%20F_0.

Continue reading Tests non-paramétriques et simulations