# Chapter 4
`Original content created by Cam Davidson-Pilon`

`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`

______

## The greatest theorem never told

This chapter focuses on an idea that is always bouncing around our minds, but is rarely made explicit outside books devoted to statistics. In fact, we've been using this simple idea in every example thus far.

### The Law of Large Numbers

Let $Z_i$ be $N$ independent samples from some probability distribution. According to *the Law of Large numbers*,  so long as the expected value $E[Z]$ is finite, the following holds,

$$\frac{1}{N} \sum_{i=1}^N Z_i \rightarrow E[ Z ],  \;\;\; N \rightarrow \infty.$$

In words:

>   The average of a sequence of random variables from the same distribution converges to the expected value of that distribution.

This may seem like a boring result, but it will be the most useful tool you use.

### Intuition

If the above Law is somewhat surprising,  it can be made more clear by examining a simple example.

Consider a random variable $Z$ that can take only two values, $c_1$ and $c_2$. Suppose we have a large number of samples of $Z$, denoting a specific sample $Z_i$. The Law says that we can approximate the expected value of $Z$ by averaging over all samples. Consider the average:

$$ \frac{1}{N} \sum_{i=1}^N \;Z_i $$

By construction, $Z_i$ can only take on $c_1$ or $c_2$, hence we can partition the sum over these two values:

\begin{align}
\frac{1}{N} \sum_{i=1}^N \;Z_i
& =\frac{1}{N} \big(  \sum_{ Z_i = c_1}c_1 + \sum_{Z_i=c_2}c_2 \big) \\\\[5pt]
& = c_1 \sum_{ Z_i = c_1}\frac{1}{N} + c_2 \sum_{ Z_i = c_2}\frac{1}{N} \\\\[5pt]
& = c_1 \times \text{ (approximate frequency of $c_1$) } \\\\
& \;\;\;\;\;\;\;\;\; + c_2 \times \text{ (approximate frequency of $c_2$) } \\\\[5pt]
& \approx c_1 \times P(Z = c_1) + c_2 \times P(Z = c_2 ) \\\\[5pt]
& = E[Z]
\end{align}

Equality holds in the limit, but we can get closer and closer by using more and more samples in the average. This Law holds for almost *any distribution*, minus some important cases we will encounter later.

##### Example
____

Below is a diagram of the Law of Large numbers in action for three different sequences of Poisson random variables.

 We sample `sample_size = 100000` Poisson random variables with parameter $\lambda = 4.5$. (Recall the expected value of a Poisson random variable is equal to its parameter.) We calculate the average for the first $n$ samples, for $n=1$ to `sample_size`.

```python
%matplotlib inline
import numpy as np
from IPython.core.pylabtools import figsize
import matplotlib.pyplot as plt

figsize( 12.5, 5 )

sample_size = 100000
expected_value = lambda_ = 4.5
poi = np.random.poisson
N_samples = range(1,sample_size,100)

for k in range(3):

    samples = poi( lambda_, sample_size )

    partial_average = [ samples[:i].mean() for i in N_samples ]

    plt.plot( N_samples, partial_average, lw=1.5,label="average \
of  $n$ samples; seq. %d"%k)

plt.plot( N_samples, expected_value*np.ones_like( partial_average),
    ls = "--", label = "true expected value", c = "k" )

plt.ylim( 4.35, 4.65)
plt.title( "Convergence of the average of \n random variables to its \
expected value" )
plt.ylabel( "average of $n$ samples" )
plt.xlabel( "# of samples, $n$")
plt.legend();
```

Looking at the above plot, it is clear that when the sample size is small, there is greater variation in the average (compare how *jagged and jumpy* the average is initially, then *smooths* out). All three paths *approach* the value 4.5, but just flirt with it as $N$ gets large. Mathematicians and statistician have another name for *flirting*: convergence.

Another very relevant question we can ask is *how quickly am I converging to the expected value?* Let's plot something new. For a specific $N$, let's do the above trials thousands of times and compute how far away we are from the true expected value, on average. But wait — *compute on average*? This is simply the law of large numbers again! For example, we are interested in, for a specific $N$, the quantity:

$$D(N) = \sqrt{ \;E\left[\;\; \left( \frac{1}{N}\sum_{i=1}^NZ_i  - 4.5 \;\right)^2 \;\;\right] \;\;}$$

The above formulae is interpretable as a distance away from the true value (on average), for some $N$. (We take the square root so the dimensions of the above quantity and our random variables are the same). As the above is an expected value, it can be approximated using the law of large numbers: instead of averaging $Z_i$, we calculate the following multiple times and average them:

$$ Y_k = \left( \;\frac{1}{N}\sum_{i=1}^NZ_i  - 4.5 \; \right)^2 $$

By computing the above many, $N_y$, times (remember, it is random), and averaging them:

$$ \frac{1}{N_Y} \sum_{k=1}^{N_Y} Y_k \rightarrow E[ Y_k ] = E\;\left[\;\; \left( \frac{1}{N}\sum_{i=1}^NZ_i  - 4.5 \;\right)^2 \right]$$

Finally, taking the square root:

$$ \sqrt{\frac{1}{N_Y} \sum_{k=1}^{N_Y} Y_k} \approx D(N) $$

```python
figsize( 12.5, 4)

N_Y = 250 #use this many to approximate D(N)
N_array = np.arange( 1000, 50000, 2500 ) #use this many samples in the approx. to the variance.
D_N_results = np.zeros( len( N_array ) )

lambda_ = 4.5
expected_value = lambda_ #for X ~ Poi(lambda) , E[ X ] = lambda

def D_N( n ):
    """
    This function approx. D_n, the average variance of using n samples.
    """
    Z = poi( lambda_, (n, N_Y) )
    average_Z = Z.mean(axis=0)
    return np.sqrt( (  (average_Z - expected_value)**2  ).mean() )

for i,n in enumerate(N_array):
    D_N_results[i] =  D_N(n)

plt.xlabel( "$N$" )
plt.ylabel( "expected squared-distance from true value" )
plt.plot(N_array, D_N_results, lw = 3,
            label="expected distance between\n\
expected value and \naverage of $N$ random variables.")
plt.plot( N_array, np.sqrt(expected_value)/np.sqrt(N_array), lw = 2, ls = "--",
        label = r"$\frac{\sqrt{\lambda}}{\sqrt{N}}$" )
plt.legend()
plt.title( "How 'fast' is the sample average converging? " );
```

As expected, the expected distance between our sample average and the actual expected value shrinks as $N$ grows large. But also notice that the *rate* of convergence decreases, that is, we need only 10 000 additional samples to move from 0.020 to 0.015, a difference of 0.005, but *20 000* more samples to again decrease from 0.015  to 0.010, again only a 0.005 decrease.

It turns out we can measure this rate of convergence. Above I have plotted a second line, the function $\sqrt{\lambda}/\sqrt{N}$. This was not chosen arbitrarily. In most cases, given a sequence of random variable distributed like $Z$, the rate of convergence to $E[Z]$ of the Law of Large Numbers is

$$ \frac{ \sqrt{ \; Var(Z) \; } }{\sqrt{N} }$$

This is useful to know: for a given large $N$, we know (on average) how far away we are from the estimate. On the other hand, in a Bayesian setting, this can seem like a useless result: Bayesian analysis is OK with uncertainty so what's the *statistical* point of adding extra precise digits? Though drawing samples can be so computationally cheap that having a *larger* $N$ is fine too.

### How do we compute $Var(Z)$ though?

The variance is simply another expected value that can be approximated! Consider the following, once we have the expected value (by using the Law of Large Numbers to estimate it, denote it $\mu$), we can estimate the variance:

$$ \frac{1}{N}\sum_{i=1}^N \;(Z_i - \mu)^2 \rightarrow E[ \;( Z - \mu)^2 \;] = Var( Z )$$

### Expected values and probabilities
There is an even less explicit relationship between expected value and estimating probabilities. Define the *indicator function*

$$\mathbb{1}_A(x) =
\begin{cases} 1 &  x \in A \\\\
              0 &  else
\end{cases}
$$
Then, by the law of large numbers, if we have many samples $X_i$, we can estimate the probability of an event $A$, denoted $P(A)$, by:

$$ \frac{1}{N} \sum_{i=1}^N \mathbb{1}_A(X_i) \rightarrow E[\mathbb{1}_A(X)] =  P(A) $$

Again, this is fairly obvious after a moments thought: the indicator function is only 1 if the event occurs, so we are summing only the times the event occurs and dividing by the total number of trials  (consider how we usually approximate probabilities using frequencies). For example, suppose we wish to estimate the probability that a $Z \sim Exp(.5)$ is greater than 5, and we have many samples from a $Exp(.5)$ distribution.

$$ P( Z > 5 ) =  \frac{1}{N}\sum_{i=1}^N \mathbb{1}_{z > 5 }(Z_i) $$

```python
N = 10000
print( np.mean( [ np.random.exponential( 0.5 ) > 5 for i in range(N) ] ) )
```

    0.0

### What does this all have to do with Bayesian statistics?

*Point estimates*, to be introduced in the next chapter, in Bayesian inference are computed using expected values. In more analytical Bayesian inference, we would have been required to evaluate complicated expected values represented as multi-dimensional integrals. No longer. If we can sample from the posterior distribution directly, we simply need to evaluate averages. Much easier. If accuracy is a priority, plots like the ones above show how fast you are converging. And if further accuracy is  desired, just take more samples from the posterior.

When is enough enough? When can you stop drawing samples from the posterior? That is the practitioners decision, and also dependent on the variance of the samples (recall from above a high variance means the average will converge slower).

We also should understand when the Law of Large Numbers fails. As the name implies, and comparing the graphs above for small $N$, the Law is only true for large sample sizes. Without this, the asymptotic result is not reliable. Knowing in what situations the Law fails can give us *confidence in how unconfident we should be*. The next section deals with this issue.

## The Disorder of Small Numbers

The Law of Large Numbers is only valid as $N$ gets *infinitely* large: never truly attainable.  While the law is a powerful tool, it is foolhardy to apply it liberally. Our next example illustrates this.

##### Example: Aggregated geographic data

Often data comes in aggregated form. For instance, data may be grouped by state, county, or city level. Of course, the population numbers vary per geographic area. If the data is an average of some characteristic of each the geographic areas, we must be conscious of the Law of Large Numbers and how it can *fail* for areas with small populations.

We will observe this on a toy dataset. Suppose there are five thousand counties in our dataset. Furthermore,  population number in each state are uniformly distributed between 100 and 1500. The way the population numbers are generated is irrelevant to the discussion, so we do not justify this. We are interested in measuring the average height of individuals per county. Unbeknownst to us, height does **not** vary across county, and each individual, regardless of the county he or she is currently living in, has the same distribution of what their height may be:

$$ \text{height} \sim \text{Normal}(150, 15 ) $$

We aggregate the individuals at the county level, so we only have data for the *average in the county*. What might our dataset look like?

```python
figsize( 12.5, 4)
std_height = 15
mean_height = 150

n_counties = 5000
pop_generator = np.random.randint
norm = np.random.normal

#generate some artificial population numbers
population = pop_generator(100, 1500, n_counties )

average_across_county = np.zeros( n_counties )
for i in range( n_counties ):
    #generate some individuals and take the mean
    average_across_county[i] = norm(mean_height, 1./std_height,
                                        population[i] ).mean()

#located the counties with the apparently most extreme average heights.
i_min = np.argmin( average_across_county )
i_max = np.argmax( average_across_county )

#plot population size vs. recorded average
plt.scatter( population, average_across_county, alpha = 0.5, c="#7A68A6")
plt.scatter( [ population[i_min], population[i_max] ],
           [average_across_county[i_min], average_across_county[i_max] ],
           s = 60, marker = "o", facecolors = "none",
           edgecolors = "#A60628", linewidths = 1.5,
            label="extreme heights")

plt.xlim( 100, 1500 )
plt.title( "Average height vs. County Population")
plt.xlabel("County Population")
plt.ylabel("Average height in county")
plt.plot( [100, 1500], [150, 150], color = "k", label = "true expected \
height", ls="--" )
plt.legend(scatterpoints = 1);
```

What do we observe? *Without accounting for population sizes* we run the risk of making an enormous inference error: if we ignored population size, we would say that the county with the shortest and tallest individuals have been correctly circled. But this inference is wrong for the following reason. These two counties do *not* necessarily have the most extreme heights. The error results from the calculated average of smaller populations not being a good reflection of the true expected value of the population (which in truth should be $\mu =150$). The sample size/population size/$N$, whatever you wish to call it,  is simply too small to invoke the Law of Large Numbers effectively.

We provide more damning evidence against this inference. Recall the population numbers were uniformly distributed over 100 to 1500. Our intuition should tell us that the counties with the most extreme population heights should also be uniformly spread over 100 to 1500, and certainly independent of the county's population. Not so. Below are the population sizes of the counties with the most extreme heights.

```python
print("Population sizes of 10 'shortest' counties: ")
print(population[ np.argsort( average_across_county )[:10] ], '\n')
print("Population sizes of 10 'tallest' counties: ")
print(population[ np.argsort( -average_across_county )[:10] ])
```

    Population sizes of 10 'shortest' counties:
    [109 135 135 133 109 157 175 120 105 131]

    Population sizes of 10 'tallest' counties:
    [122 133 313 109 124 280 106 198 326 216]

Not at all uniform over 100 to 1500. This is an absolute failure of the Law of Large Numbers.

##### Example:  Kaggle's *U.S. Census Return Rate Challenge*

Below is data from the 2010 US census, which partitions populations beyond counties to the level of block groups (which are aggregates of city blocks or equivalents). The dataset is from a Kaggle machine learning competition some colleagues and I participated in. The objective was to predict the census letter mail-back rate of a group block, measured between 0 and 100, using census variables (median income, number of females in the block-group, number of trailer parks, average number of children etc.). Below we plot the census mail-back rate versus block group population:

```python
figsize( 12.5, 6.5 )
data = np.genfromtxt( "./data/census_data.csv", skip_header=1,
                        delimiter= ",")
plt.scatter( data[:,1], data[:,0], alpha = 0.5, c="#7A68A6")
plt.title("Census mail-back rate vs Population")
plt.ylabel("Mail-back rate")
plt.xlabel("population of block-group")
plt.xlim(-100, 15e3 )
plt.ylim( -5, 105)

i_min = np.argmin(  data[:,0] )
i_max = np.argmax(  data[:,0] )

plt.scatter( [ data[i_min,1], data[i_max, 1] ],
             [ data[i_min,0],  data[i_max,0] ],
             s = 60, marker = "o", facecolors = "none",
             edgecolors = "#A60628", linewidths = 1.5,
             label="most extreme points")

plt.legend(scatterpoints = 1);
```

The above is a classic phenomenon in statistics. I say *classic* referring to the "shape" of the scatter plot above. It follows a classic triangular form, that tightens as we increase the sample size (as the Law of Large Numbers becomes more exact).

I am perhaps overstressing the point and maybe I should have titled the book *"You don't have big data problems!"*, but here again is an example of the trouble with *small datasets*, not big ones. Simply, small datasets cannot be processed using the Law of Large Numbers. Compare with applying the Law without hassle to big datasets (ex. big data). I mentioned earlier that paradoxically big data prediction problems are solved by relatively simple algorithms. The paradox is partially resolved by understanding that the Law of Large Numbers creates solutions that are *stable*, i.e. adding or subtracting a few data points will not affect the solution much. On the other hand, adding or removing data points to a small dataset can create very different results.

For further reading on the hidden dangers of the Law of Large Numbers, I would highly recommend the excellent manuscript [The Most Dangerous Equation](http://nsm.uh.edu/~dgraur/niv/TheMostDangerousEquation.pdf).

##### Example: How to order Reddit submissions

You may have disagreed with the original statement that the Law of Large numbers is known to everyone, but only implicitly in our subconscious decision making. Consider ratings on online products: how often do you trust an average 5-star rating if there is only 1 reviewer? 2 reviewers? 3 reviewers? We implicitly understand that with such few reviewers that the average rating is **not** a good reflection of the true value of the product.

This has created flaws in how we sort items, and more generally, how we compare items. Many people have realized that sorting online search results by their rating, whether the objects be books, videos, or online comments, return poor results. Often the seemingly top videos or comments have perfect ratings only from a few enthusiastic fans, and truly more quality videos or comments are hidden in later pages with *falsely-substandard* ratings of around 4.8. How can we correct this?

Consider the popular site Reddit (I purposefully did not link to the website as you would never come back). The site hosts links to stories or images, called submissions, for people to comment on. Redditors can vote up or down on each submission (called upvotes and downvotes). Reddit, by default, will sort submissions to a given subreddit by Hot, that is, the submissions that have the most upvotes recently.

How would you determine which submissions are the best? There are a number of ways to achieve this:

1. *Popularity*: A submission is considered good if it has many upvotes. A problem with this model is that a submission with hundreds of upvotes, but thousands of downvotes. While being very *popular*, the submission is likely more controversial than best.
2. *Difference*: Using the *difference* of upvotes and downvotes. This solves the above problem, but fails when we consider the temporal nature of submission. Depending on when a submission is posted, the website may be experiencing high or low traffic. The difference method will bias the *Top* submissions to be the those made during high traffic periods, which have accumulated more upvotes than submissions that were not so graced, but are not necessarily the best.
3. *Time adjusted*:  Consider using Difference divided by the age of the submission. This creates a *rate*, something like *difference per second*, or *per minute*. An immediate counter-example is, if we use per second, a 1 second old submission with 1 upvote would be better than a 100 second old submission with 99 upvotes. One can avoid this by only considering at least t second old submission. But what is a good t value? Does this mean no submission younger than t is good? We end up comparing unstable quantities with stable quantities (young vs. old submissions).
3. *Ratio*: Rank submissions by the ratio of upvotes to total number of votes (upvotes plus downvotes). This solves the temporal issue, such that new submissions who score well can be considered Top just as likely as older submissions, provided they have many upvotes to total votes. The problem here is that a submission with a single upvote (ratio = 1.0) will beat a submission with 999 upvotes and 1 downvote (ratio = 0.999), but clearly the latter submission is *more likely* to be better.

I used the phrase *more likely* for good reason. It is possible that the former submission, with a single upvote, is in fact a better submission than the later with 999 upvotes. The hesitation to agree with this is because we have not seen the other 999 potential votes the former submission might get. Perhaps it will achieve an additional 999 upvotes and 0 downvotes and be considered better than the latter, though not likely.

What we really want is an estimate of the *true upvote ratio*. Note that the true upvote ratio is not the same as the observed upvote ratio: the true upvote ratio is hidden, and we only observe upvotes vs. downvotes (one can think of the true upvote ratio as "what is the underlying probability someone gives this submission a upvote, versus a downvote"). So the 999 upvote/1 downvote submission probably has a true upvote ratio close to 1, which we can assert with confidence thanks to the Law of Large Numbers, but on the other hand we are much less certain about the true upvote ratio of the submission with only a single upvote. Sounds like a Bayesian problem to me.

One way to determine a prior on the upvote ratio is to look at the historical distribution of upvote ratios. This can be accomplished by scraping Reddit's submissions and determining a distribution. There are a few problems with this technique though:

1. Skewed data:  The vast majority of submissions have very few votes, hence there will be many submissions with ratios near the extremes (see the "triangular plot" in the above Kaggle dataset), effectively skewing our distribution to the extremes. One could try to only use submissions with votes greater than some threshold. Again, problems are encountered. There is a tradeoff between number of submissions available to use and a higher threshold with associated ratio precision.
2. Biased data: Reddit is composed of different subpages, called subreddits. Two examples are *r/aww*, which posts pics of cute animals, and *r/politics*. It is very likely that the user behaviour towards submissions of these two subreddits are very different: visitors are likely friendly and affectionate in the former, and would therefore upvote submissions more, compared to the latter, where submissions are likely to be controversial and disagreed upon. Therefore not all submissions are the same.

In light of these, I think it is better to use a `Uniform` prior.

With our prior in place, we can find the posterior of the true upvote ratio. The Python script `top_showerthoughts_submissions.py` will scrape the best posts from the `showerthoughts` community on Reddit. This is a text-only community so the title of each post *is* the post. Below is the top post as well as some other sample posts:

```python
!pip install praw -U
```

    Collecting praw
      Downloading https://files.pythonhosted.org/packages/a4/d7/0c7fb864ab9469f2964b2787910c78ade6d98c2d1710df1deab61beb99a1/praw-6.0.0-py2.py3-none-any.whl (99kB)
    Collecting prawcore<2.0,>=1.0.0 (from praw)
      Downloading https://files.pythonhosted.org/packages/cd/6d/4bf4d65d4771b15c70284c0626d24f230a5de6edac75c446fd22008ddbf6/prawcore-1.0.0-py2.py3-none-any.whl
    Collecting update-checker>=0.16 (from praw)
      Downloading https://files.pythonhosted.org/packages/17/c9/ab11855af164d03be0ff4fddd4c46a5bd44799a9ecc1770e01a669c21168/update_checker-0.16-py2.py3-none-any.whl
    Requirement already satisfied, skipping upgrade: requests<3.0,>=2.6.0 in c:\programdata\anaconda3\lib\site-packages (from prawcore<2.0,>=1.0.0->praw) (2.18.4)
    Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0,>=2.6.0->prawcore<2.0,>=1.0.0->praw) (3.0.4)
    Requirement already satisfied, skipping upgrade: idna<2.7,>=2.5 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0,>=2.6.0->prawcore<2.0,>=1.0.0->praw) (2.6)
    Requirement already satisfied, skipping upgrade: urllib3<1.23,>=1.21.1 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0,>=2.6.0->prawcore<2.0,>=1.0.0->praw) (1.22)
    Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0,>=2.6.0->prawcore<2.0,>=1.0.0->praw) (2018.10.15)
    Installing collected packages: prawcore, update-checker, praw
    Successfully installed praw-6.0.0 prawcore-1.0.0 update-checker-0.16

```python
#adding a number to the end of the %run call will get the ith top post.
%run top_showerthoughts_submissions.py 2

print("Post contents: \n")
print(top_post)
```

```python
"""
contents: an array of the text from the last 100 top submissions to a subreddit
votes: a 2d numpy array of upvotes, downvotes for each submission.
"""
n_submissions = len(votes)
submissions = np.random.randint( n_submissions, size=4)
print("Some Submissions (out of %d total) \n-----------"%n_submissions)
for i in submissions:
    print('"' + contents[i] + '"')
    print("upvotes/downvotes: ",votes[i,:], "\n")
```

    Some Submissions (out of 98 total)
    -----------
    "Rappers from the 90's used guns when they had beef rappers today use Twitter."
    upvotes/downvotes:  [32  3]

    "All polls are biased towards people who are willing to take polls"
    upvotes/downvotes:  [1918  101]

    "Taco Bell should give customers an extra tortilla so they can make a burrito out of all the stuff that spilled out of the other burritos they ate."
    upvotes/downvotes:  [79 17]

    "There should be an /r/alanismorissette where it's just examples of people using "ironic" incorrectly"
    upvotes/downvotes:  [33  6]

 For a given true upvote ratio $p$ and $N$ votes, the number of upvotes will look like a Binomial random variable with parameters $p$ and $N$. (This is because of the equivalence between upvote ratio and probability of upvoting versus downvoting, out of $N$ possible votes/trials). We create a function that performs Bayesian inference on $p$, for a particular submission's upvote/downvote pair.

```python
import pymc3 as pm

def posterior_upvote_ratio( upvotes, downvotes, samples = 20000):
    """
    This function accepts the number of upvotes and downvotes a particular submission recieved,
    and the number of posterior samples to return to the user. Assumes a uniform prior.
    """
    N = upvotes + downvotes
    with pm.Model() as model:
        upvote_ratio = pm.Uniform("upvote_ratio", 0, 1)
        observations = pm.Binomial( "obs",  N, upvote_ratio, observed=upvotes)

        trace = pm.sample(samples, step=pm.Metropolis())

    burned_trace = trace[int(samples/4):]
    return burned_trace["upvote_ratio"]

```

Below are the resulting posterior distributions.

```python
figsize( 11., 8)
posteriors = []
colours = ["#348ABD", "#A60628", "#7A68A6", "#467821", "#CF4457"]
for i in range(len(submissions)):
    j = submissions[i]
    posteriors.append( posterior_upvote_ratio( votes[j, 0], votes[j,1] ) )
    plt.hist( posteriors[i], bins = 10, normed = True, alpha = .9,
            histtype="step",color = colours[i%5], lw = 3,
            label = '(%d up:%d down)\n%s...'%(votes[j, 0], votes[j,1], contents[j][:50]) )
    plt.hist( posteriors[i], bins = 10, normed = True, alpha = .2,
            histtype="stepfilled",color = colours[i], lw = 3, )

plt.legend(loc="upper left")
plt.xlim( 0, 1)
plt.title("Posterior distributions of upvote ratios on different submissions");
```

Some distributions are very tight, others have very long tails (relatively speaking), expressing our uncertainty with what the true upvote ratio might be.

### Sorting!

We have been ignoring the goal of this exercise: how do we sort the submissions from *best to worst*? Of course, we cannot sort distributions, we must sort scalar numbers. There are many ways to distill a distribution down to a scalar: expressing the distribution through its expected value, or mean, is one way. Choosing the mean is a bad choice though. This is because the mean does not take into account the uncertainty of distributions.

I  suggest using the *95% least plausible value*, defined as the value such that there is only a 5% chance the true parameter is lower (think of the lower bound on the 95% credible region). Below are the posterior distributions with the 95% least-plausible value plotted:

```python
N = posteriors[0].shape[0]
lower_limits = []

for i in range(len(submissions)):
    j = submissions[i]
    plt.hist( posteriors[i], bins = 20, normed = True, alpha = .9,
            histtype="step",color = colours[i], lw = 3,
            label = '(%d up:%d down)\n%s...'%(votes[j, 0], votes[j,1], contents[j][:50]) )
    plt.hist( posteriors[i], bins = 20, normed = True, alpha = .2,
            histtype="stepfilled",color = colours[i], lw = 3, )
    v = np.sort( posteriors[i] )[ int(0.05*N) ]
    #plt.vlines( v, 0, 15 , color = "k", alpha = 1, linewidths=3 )
    plt.vlines( v, 0, 10 , color = colours[i], linestyles = "--",  linewidths=3  )
    lower_limits.append(v)
    plt.legend(loc="upper left")

plt.legend(loc="upper left")
plt.title("Posterior distributions of upvote ratios on different submissions");
order = np.argsort( -np.array( lower_limits ) )
print(order, lower_limits)
```

The best submissions, according to our procedure, are the submissions that are *most-likely* to score a high percentage of upvotes. Visually those are the submissions with the 95% least plausible value close to 1.

Why is sorting based on this quantity a good idea? By ordering by the 95% least plausible value, we are being the most conservative with what we think is best.  When using the lower-bound of the 95% credible interval, we believe with high certainty that the 'true upvote ratio' is at the very least equal to this value (or greater), thereby ensuring that the best submissions are still on top. Under this ordering, we impose the following very natural properties:

1. given two submissions with the same observed upvote ratio, we will assign the submission with more votes as better (since we are more confident it has a higher ratio).
2. given two submissions with the same number of votes, we still assign the submission with more upvotes as *better*.

### But this is too slow for real-time!

I agree, computing the posterior of every submission takes a long time, and by the time you have computed it, likely the data has changed. I delay the mathematics to the appendix, but I suggest using the following formula to compute the lower bound very fast.

$$ \frac{a}{a + b} - 1.65\sqrt{ \frac{ab}{ (a+b)^2(a + b +1 ) } }$$

where
\begin{align}
& a = 1 + u \\\\
& b = 1 + d \\\\
\end{align}

$u$ is the number of upvotes, and $d$ is the number of downvotes. The formula is a shortcut in Bayesian inference, which will be further explained in Chapter 6 when we discuss priors in more detail.

```python
def intervals(u,d):
    a = 1. + u
    b = 1. + d
    mu = a/(a+b)
    std_err = 1.65*np.sqrt( (a*b)/( (a+b)**2*(a+b+1.) ) )
    return ( mu, std_err )

print("Approximate lower bounds:")
posterior_mean, std_err  = intervals(votes[:,0],votes[:,1])
lb = posterior_mean - std_err
print(lb)
print("\n")
print("Top 40 Sorted according to approximate lower bounds:")
print("\n")
order = np.argsort( -lb )
ordered_contents = []
for i in order[:40]:
    ordered_contents.append( contents[i] )
    print(votes[i,0], votes[i,1], contents[i])
    print("-------------")
```

    Approximate lower bounds:
    [ 0.93349005  0.9532194   0.94149718  0.90859764  0.88705356  0.8558795
      0.85644927  0.93752679  0.95767101  0.91131012  0.910073    0.915999
      0.9140058   0.83276025  0.87593961  0.87436674  0.92830849  0.90642832
      0.89187973  0.89950891  0.91295322  0.78607629  0.90250203  0.79950031
      0.85219422  0.83703439  0.7619808   0.81301134  0.7313114   0.79137561
      0.82701445  0.85542404  0.82309334  0.75211374  0.82934814  0.82674958
      0.80933194  0.87448152  0.85350205  0.75460106  0.82934814  0.74417233
      0.79924258  0.8189683   0.75460106  0.90744016  0.83838023  0.78802791
      0.78400654  0.64638659  0.62047936  0.76137738  0.81365241  0.83838023
      0.78457533  0.84980627  0.79249393  0.69020315  0.69593922  0.70758151
      0.70268831  0.91620627  0.73346864  0.86382644  0.80877728  0.72708753
      0.79822085  0.68333632  0.81699014  0.65100453  0.79809005  0.74702492
      0.77318569  0.83221179  0.66500492  0.68134548  0.7249286   0.59412132
      0.58191312  0.73142963  0.73142963  0.66251028  0.87152685  0.74107856
      0.60935684  0.87152685  0.77484517  0.88783675  0.81814153  0.54569789
      0.6122496   0.75613569  0.53511973  0.74556767  0.81814153  0.85773646
      0.6122496   0.64814153]

    Top 40 Sorted according to approximate lower bounds:

    596 18 Someone should develop an AI specifically for reading Terms & Conditions and flagging dubious parts.
    -------------
    2360 98 Porn is the only industry where it is not only acceptable but standard to separate people based on race, sex and sexual preference.
    -------------
    1918 101 All polls are biased towards people who are willing to take polls
    -------------
    948 50 They should charge less for drinks in the drive-thru because you can't refill them.
    -------------
    3740 239 When I was in elementary school and going through the DARE program, I was positive a gang of older kids was going to corner me and force me to smoke pot. Then I became an adult and realized nobody is giving free drugs to somebody that doesn't want them.
    -------------
    166 7 "Noted" is the professional way of saying "K".
    -------------
    29 0 Rewatching Mr. Bean, I've realised that the character is an eccentric genius and not a blithering idiot.
    -------------
    289 18 You've been doing weird cameos in your friends' dreams since kindergarten.
    -------------
    269 17 At some point every parent has stopped wiping their child's butt and hoped for the best.
    -------------
    121 6 Is it really fair to say a person over 85 has heart failure? Technically, that heart has done exceptionally well.
    -------------
    535 40 It's surreal to think that the sun and moon and stars we gaze up at are the same objects that have been observed for millenia, by everyone in the history of humanity from cavemen to Aristotle to Jesus to George Washington.
    -------------
    527 40 I wonder if America's internet is censored in a similar way that North Korea's is, but we have no idea of it happening.
    -------------
    1510 131 Kenny's family is poor because they're always paying for his funeral.
    -------------
    43 1 If I was as careful with my whole paycheck as I am with my last $20 I'd be a whole lot better off
    -------------
    162 10 Black hair ties are probably the most popular bracelets in the world.
    -------------
    107 6 The best answer to the interview question "What is your greatest weakness?" is "interviews".
    -------------
    127 8 Surfing the internet without ads feels like a summer evening without mosquitoes
    -------------
    159 12 I wonder if Superman ever put a pair of glasses on Lois Lane's dog, and she was like "what's this Clark? Did you get me a new dog?"
    -------------
    21 0 Sitting on a cold toilet seat or a warm toilet seat both suck for different reasons.
    -------------
    1414 157 My life is really like Rihanna's song, "just work work work work work" and the rest of it I can't really understand.
    -------------
    222 22 I'm honestly slightly concerned how often Reddit commenters make me laugh compared to my real life friends.
    -------------
    52 3 The world must have been a spookier place altogether when candles and gas lamps were the only sources of light at night besides the moon and the stars.
    -------------
    194 19 I have not been thankful enough in the last few years that the Black Eyed Peas are no longer ever on the radio
    -------------
    18 0 Living on the coast is having the window seat of the land you live on.
    -------------
    18 0 Binoculars are like walkie talkies for the deaf.
    -------------
    28 1 Now that I am a parent of multiple children I have realized that my parents were lying through their teeth when they said they didn't have a favorite.
    -------------
    16 0 I sneer at people who read tabloids, but every time I look someone up on Wikipedia the first thing I look for is what controversies they've been involved in.
    -------------
    1559 233 Kid's menus at restaurants should be smaller portions of the same adult dishes at lower prices and not the junk food that they usually offer.
    -------------
    1426 213 Eventually once all phones are waterproof we'll be able to push people into pools again
    -------------
    61 5 Myspace is so outdated that jokes about it being outdated has become outdated
    -------------
    52 4 As a kid, seeing someone step on a banana peel and not slip was a disappointment.
    -------------
    90 9 Yahoo!® is the RadioShack® of the Internet.
    -------------
    34 2 People who "tell it like it is" rarely do so to say something nice
    -------------
    39 3 Closing your eyes after turning off your alarm is a very dangerous game.
    -------------
    39 3 Your known 'first word' is the first word your parents heard you speak. In reality, it may have been a completely different word you said when you were alone.
    -------------
    87 10 "Smells Like Teen Spirit" is as old to listeners of today as "Yellow Submarine" was to listeners of 1991.
    -------------
    239 36 if an ocean didnt stop immigrants from coming to America what makes us think a wall will?
    -------------
    22 1 The phonebook was the biggest invasion of privacy that everyone was oddly ok with.
    -------------
    57 6 I'm actually the most productive when I procrastinate because I'm doing everything I possibly can to avoid the main task at hand.
    -------------
    57 6 You will never feel how long time is until you have allergies and snot slowly dripping out of your nostrils, while sitting in a classroom with no tissues.
    -------------

We can view the ordering visually by plotting the posterior mean and bounds, and sorting by the lower bound. In the plot below, notice that the left error-bar is sorted (as we suggested this is the best way to determine an ordering), so the means, indicated by dots, do not follow any strong pattern.

```python
r_order = order[::-1][-40:]
plt.errorbar( posterior_mean[r_order], np.arange( len(r_order) ),
               xerr=std_err[r_order], capsize=0, fmt="o",
                color = "#7A68A6")
plt.xlim( 0.3, 1)
plt.yticks( np.arange( len(r_order)-1,-1,-1 ), map( lambda x: x[:30].replace("\n",""), ordered_contents) );
```

In the graphic above, you can see why sorting by mean would be sub-optimal.

### Extension to Starred rating systems

The above procedure works well for upvote-downvotes schemes, but what about systems that use star ratings, e.g. 5 star rating systems. Similar problems apply with simply taking the average: an item with two perfect ratings would beat an item with thousands of perfect ratings, but a single sub-perfect rating.

We can consider the upvote-downvote problem above as binary: 0 is a downvote, 1 if an upvote. A $N$-star rating system can be seen as a more continuous version of above, and we can set $n$ stars rewarded is equivalent to rewarding $\frac{n}{N}$. For example, in a 5-star system, a 2 star rating corresponds to 0.4. A perfect rating is a 1. We can use the same formula as before, but with $a,b$ defined differently:

$$ \frac{a}{a + b} - 1.65\sqrt{ \frac{ab}{ (a+b)^2(a + b +1 ) } }$$

where

\begin{align}
& a = 1 + S \\\\
& b = 1 + N - S \\\\
\end{align}

where $N$ is the number of users who rated, and $S$ is the sum of all the ratings, under the equivalence scheme mentioned above.

##### Example: Counting Github stars

What is the average number of stars a Github repository has? How would you calculate this? There are over 6 million respositories, so there is more than enough data to invoke the Law of Large numbers. Let's start pulling some data. TODO

### Conclusion

While the Law of Large Numbers is cool, it is only true so much as its name implies: with large sample sizes only. We have seen how our inference can be affected by not considering *how the data is shaped*.

1. By (cheaply) drawing many samples from the posterior distributions, we can ensure that the Law of Large Number applies as we approximate expected values (which we will do in the next chapter).

2. Bayesian inference understands that with small sample sizes, we can observe wild randomness. Our posterior distribution will reflect this by being more spread rather than tightly concentrated. Thus, our inference should be correctable.

3. There are major implications of not considering the sample size, and trying to sort objects that are unstable leads to pathological orderings. The method provided above solves this problem.

### Appendix

##### Derivation of sorting submissions formula

Basically what we are doing is using a Beta prior (with parameters $a=1, b=1$, which is a uniform distribution), and using a Binomial likelihood with observations $u, N = u+d$. This means our posterior is a Beta distribution with parameters $a' = 1 + u, b' = 1 + (N - u) = 1+d$. We then need to find the value, $x$, such that 0.05 probability is less than $x$. This is usually done by inverting the CDF ([Cumulative Distribution Function](http://en.wikipedia.org/wiki/Cumulative_Distribution_Function)), but the CDF of the beta, for integer parameters, is known but is a large sum [3].

We instead use a Normal approximation. The mean of the Beta is $\mu = a'/(a'+b')$ and the variance is

$$\sigma^2 = \frac{a'b'}{ (a' + b')^2(a'+b'+1) }$$

Hence we solve the following equation for $x$ and have an approximate lower bound.

$$ 0.05 = \Phi\left( \frac{(x - \mu)}{\sigma}\right) $$

$\Phi$ being the [cumulative distribution for the normal distribution](http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution)

##### Exercises

1\. How would you estimate the quantity $E\left[ \cos{X} \right]$, where $X \sim \text{Exp}(4)$? What about $E\left[ \cos{X} | X \lt 1\right]$, i.e. the expected value *given* we know $X$ is less than 1? Would you need more samples than the original samples size to be equally accurate?

```python
## Enter code here
import scipy.stats as stats
exp = stats.expon( scale=4 )
N = 1e5
N_trials = 100

cos_X_means = np.zeros(N_trials)
for n in range(N_trials):

    X = exp.rvs( int(N) )
    cos_X = np.cos(X)
    cos_X_means[n] = cos_X.mean()
print('E[mu_cos_x]:', cos_X_means.mean())
print('Var[mu_cos_x]:', cos_X_means.var())
print()

cos_X_for_x_lt_1_means = np.zeros(N_trials)
for n in range(N_trials):
    X = exp.rvs( int(N) )
    cos_X = np.cos(X)
    cos_X_for_x_lt_1 = cos_X[X<1.0]

cos_X_for_x_lt_1_means[n] = cos_X_for_x_lt_1.mean()
print('E[mu_cos_x | X < 1]:', cos_X_for_x_lt_1_means.mean())
print('Var[mu_cos_x | X < 1]:', cos_X_for_x_lt_1_means.var())
```

    E[mu_cos_x]: 0.05890420088246862
    Var[mu_cos_x]: 4.486920158200483e-06

    E[mu_cos_x | X < 1]: 0.008522997631349742
    Var[mu_cos_x | X < 1]: 0.0071915073737753386

2\. The following table was located in the paper "Going for Three: Predicting the Likelihood of Field Goal Success with Logistic Regression" [2]. The table ranks football field-goal kickers by their percent of non-misses. What mistake have the researchers made?

-----

####  Kicker Careers Ranked by Make Percentage
<table><tbody><tr><th>Rank </th><th>Kicker </th><th>Make % </th><th>Number  of Kicks</th></tr><tr><td>1 </td><td>Garrett Hartley </td><td>87.7 </td><td>57</td></tr><tr><td>2</td><td> Matt Stover </td><td>86.8 </td><td>335</td></tr><tr><td>3 </td><td>Robbie Gould </td><td>86.2 </td><td>224</td></tr><tr><td>4 </td><td>Rob Bironas </td><td>86.1 </td><td>223</td></tr><tr><td>5</td><td> Shayne Graham </td><td>85.4 </td><td>254</td></tr><tr><td>… </td><td>… </td><td>…</td><td> </td></tr><tr><td>51</td><td> Dave Rayner </td><td>72.2 </td><td>90</td></tr><tr><td>52</td><td> Nick Novak </td><td>71.9 </td><td>64</td></tr><tr><td>53 </td><td>Tim Seder </td><td>71.0 </td><td>62</td></tr><tr><td>54 </td><td>Jose Cortez </td><td>70.7</td><td> 75</td></tr><tr><td>55 </td><td>Wade Richey </td><td>66.1</td><td> 56</td></tr></tbody></table>

In August 2013, [a popular post](http://bpodgursky.wordpress.com/2013/08/21/average-income-per-programming-language/) on the average income per programmer of different languages was trending. Here's the summary chart: (reproduced without permission, cause when you lie with stats, you gunna get the hammer). What do you notice about the extremes?

------

#### Average household income by programming language

<table >
 <tr><td>Language</td><td>Average Household Income ($)</td><td>Data Points</td></tr>
 <tr><td>Puppet</td><td>87,589.29</td><td>112</td></tr>
 <tr><td>Haskell</td><td>89,973.82</td><td>191</td></tr>
 <tr><td>PHP</td><td>94,031.19</td><td>978</td></tr>
 <tr><td>CoffeeScript</td><td>94,890.80</td><td>435</td></tr>
 <tr><td>VimL</td><td>94,967.11</td><td>532</td></tr>
 <tr><td>Shell</td><td>96,930.54</td><td>979</td></tr>
 <tr><td>Lua</td><td>96,930.69</td><td>101</td></tr>
 <tr><td>Erlang</td><td>97,306.55</td><td>168</td></tr>
 <tr><td>Clojure</td><td>97,500.00</td><td>269</td></tr>
 <tr><td>Python</td><td>97,578.87</td><td>2314</td></tr>
 <tr><td>JavaScript</td><td>97,598.75</td><td>3443</td></tr>
 <tr><td>Emacs Lisp</td><td>97,774.65</td><td>355</td></tr>
 <tr><td>C#</td><td>97,823.31</td><td>665</td></tr>
 <tr><td>Ruby</td><td>98,238.74</td><td>3242</td></tr>
 <tr><td>C++</td><td>99,147.93</td><td>845</td></tr>
 <tr><td>CSS</td><td>99,881.40</td><td>527</td></tr>
 <tr><td>Perl</td><td>100,295.45</td><td>990</td></tr>
 <tr><td>C</td><td>100,766.51</td><td>2120</td></tr>
 <tr><td>Go</td><td>101,158.01</td><td>231</td></tr>
 <tr><td>Scala</td><td>101,460.91</td><td>243</td></tr>
 <tr><td>ColdFusion</td><td>101,536.70</td><td>109</td></tr>
 <tr><td>Objective-C</td><td>101,801.60</td><td>562</td></tr>
 <tr><td>Groovy</td><td>102,650.86</td><td>116</td></tr>
 <tr><td>Java</td><td>103,179.39</td><td>1402</td></tr>
 <tr><td>XSLT</td><td>106,199.19</td><td>123</td></tr>
 <tr><td>ActionScript</td><td>108,119.47</td><td>113</td></tr>
</table>

### References

1. Wainer, Howard. *The Most Dangerous Equation*. American Scientist, Volume 95.
2. Clarck, Torin K., Aaron W. Johnson, and Alexander J. Stimpson. "Going for Three: Predicting the Likelihood of Field Goal Success with Logistic Regression." (2013): n. page. [Web](http://www.sloansportsconference.com/wp-content/uploads/2013/Going%20for%20Three%20Predicting%20the%20Likelihood%20of%20Field%20Goal%20Success%20with%20Logistic%20Regression.pdf). 20 Feb. 2013.
3. http://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function

```python
from IPython.core.display import HTML
def css_styling():
    styles = open("../styles/custom.css", "r").read()
    return HTML(styles)
css_styling()
```

<style>
    @font-face {
        font-family: "Computer Modern";
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunss.otf');
    }
    @font-face {
        font-family: "Computer Modern";
        font-weight: bold;
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunsx.otf');
    }
    @font-face {
        font-family: "Computer Modern";
        font-style: oblique;
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunsi.otf');
    }
    @font-face {
        font-family: "Computer Modern";
        font-weight: bold;
        font-style: oblique;
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunso.otf');
    }
    div.cell{
        width:800px;
        margin-left:16% !important;
        margin-right:auto;
    }
    h1 {
        font-family: Helvetica, serif;
    }
    h4{
        margin-top:12px;
        margin-bottom: 3px;
       }
    div.text_cell_render{
        font-family: Computer Modern, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
        line-height: 145%;
        font-size: 130%;
        width:800px;
        margin-left:auto;
        margin-right:auto;
    }
    .CodeMirror{
            font-family: "Source Code Pro", source-code-pro,Consolas, monospace;
    }
    .prompt{
        display: None;
    }
    .text_cell_render h5 {
        font-weight: 300;
        font-size: 22pt;
        color: #4057A1;
        font-style: italic;
        margin-bottom: .5em;
        margin-top: 0.5em;
        display: block;
    }

    .warning{
        color: rgb( 240, 20, 20 )
        }
</style>

<style>
    img{
        max-width:800px}
</style>


# Transformation properties of the likelihood and posterior

In the notebooks [*How do distributions transform under a change of variables?*
](./change-of-variables) and *[Change of variables with autodiff](./one-over-x-flow)* we saw how a distribution $p_X$ for a random variable $X$ transforms under a change of variables $X \to Y$. In particular we found that that the transformation involves a Jacobian factor.

\begin{equation}
p_Y(Y=y) = p_X(x) \,/ \,\left| \, {dy}/{dx}\, \right |
\end{equation}

If we were working with a family of distributions $p_X(X | \theta)$, where $\theta$ is the parameter that is used to index the family of distributions we would have the same thing.

\begin{equation}
p_Y(Y=y \mid \theta) = p_X(x \mid \theta) \,/ \,\left| \, {dy}/{dx}\, \right |
\end{equation}

In [*Transformation of likelihood with change of random variable*](./likelihood-change-obs) we saw how this Jacobian factor leads to a multipliciative scaling of the likelihood function (or a constant shift of the log-likelihood function), but that likelihood-ratios are invariant to a change of variables $X \to Y$ (because the Jacobian factor cancels).

## How does the likelihood transform to reparameterization?

But how does the likelihood $L(\theta) := p(X=x | \theta)$ transform when we keep the random variable unchanged, but instead reparameterize the parameters used to index the family of distributions, eg. $\theta \to \phi$? As we will see, **the likelihood is invariant to reparameterization**, which is a very important property. It also underscores how the likelihood is not a probability density in $\theta$.

```{note}
This notebook is intended to demonstrate explicitly the transformation properties of the likelihood function, posterior, maximum likelihood estimate(MLE), and maximum a posterior (MAP) estimate.
```

We will start with a family of pdfs $p(X \mid \sigma)$, where $X$ is a continuous random variable and $\sigma$ is the parameter used to index or parametrize the family.  In practice, we will use a normal distribution with mean 0 and $\sigma$ will be the standard deviation.

We will then consider a reparametrization of the same family of pdfs, but instead of using $\sigma$ we will use $V=\sigma^2$ (eg. the variance).

We will consider a small data set $\{x_i\}_{i=1}^{15} \sim p(X \mid \sigma=\sigma_{true})$.

We will plot the distribution for two values of $\sigma$: $\sigma_{true}$ and $\sigma_{other}$.

We will then look at the likelihood for the individual data points $p(x_i | \sigma)$ and since the data are i.i.d. the total likelihood is $L(\sigma) = \prod_i p(x_i | \sigma)$.

We will then look at the reparametrized likelihood for the individual data points $p(x_i | V)$ and since the data are i.i.d. the total likelihood is $L^\prime(V) = \prod_i p^\prime(x_i | V)$.

We will then plot the original and reparametrized likelihoods in a particular way to demonstrate that the value of the likelihood is invariant to reprametrization: eg.  $L(\sigma) = L^\prime(V(\sigma))$

### Check explicitly

```python
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams.update({'font.size': 15})
#rcParams.update({'font.size': 18,'text.usetex': True})
rcParams['figure.figsize'] = 12,6
```

We start with a family of pdfs $p(X \mid \sigma)$, where $X$ is a continuous random variable and $\sigma$ is the parameter used to index or parametrize the family.  In practice, we will use a normal distribution with mean 0 and $\sigma$ will be the standard deviation.

```python
def my_family_of_pdfs(x, sigma):
    #return 1./np.sqrt(2.*np.pi)/sigma * np.exp( -(x-mu)**2/2/sigma**2 )
    return norm.pdf(x,scale=sigma)
```

We will then consider a reparametrization of the same family of pdfs, but instead of using $\sigma$ we will use $V=\sigma^2$ (eg. the variance).

```python
def sigma_to_V(sigma):
    return sigma*sigma

def V_to_sigma(V):
    return np.sqrt(V)
```

```python
def my_reparametrized_family_of_pdfs(x, variance):
    return my_family_of_pdfs(x,V_to_sigma(variance))
```

We will consider a small data set $\{x_i\}_{i=1}^{15} \sim p(X \mid \sigma=\sigma_{true})$.

```python
true_sigma=1.3
true_V = sigma_to_V(true_sigma)
```

```python
# Generate some synthetic data
data = norm.rvs(scale=true_sigma, size=15)
data
```

    array([ 0.93103086,  0.25461656,  0.01924056,  0.12333217,  0.88722697,
           -1.17641472,  0.44889527, -1.6312956 ,  0.11686814,  0.12861621,
            1.63503248, -0.2726336 ,  1.43866873, -1.53739523, -2.56144692])

We will plot the distribution for two values of $\sigma$: $\sigma_{true}$ and $\sigma_{other}$.

We will then look at the likelihood for the individual data points $p(x_i | \sigma)$ and since the data are i.i.d. the total likelihood is $L(\sigma) = \prod_i p(x_i | \sigma)$.

```python
likelihood_i = my_family_of_pdfs(data, true_sigma)
total_likelihood = np.prod(likelihood_i)
print('the total likeihood for this data set when sigma={0} is {1}'.format(true_sigma, total_likelihood))
print('-2 log L(sigma={0}) = {1}'.format(true_sigma, -2*np.log(total_likelihood)))
```

    the total likeihood for this data set when sigma=1.3 is 5.840111269517725e-11
    -2 log L(sigma=1.3) = 47.12737234655253

```python
other_sigma = 0.7
other_V = sigma_to_V(other_sigma)

other_likelihood_i = my_family_of_pdfs(data, other_sigma)
other_total_likelihood = np.prod(other_likelihood_i)
print('the total likeihood for this data set when sigma={0} is {1}'.format(other_sigma, other_total_likelihood))
print('-2 log L(sigma={0}) = {1}'.format(other_sigma, -2*np.log(other_total_likelihood)))
```

    the total likeihood for this data set when sigma=0.7 is 3.8317371491953943e-13
    -2 log L(sigma=0.7) = 57.1805758896008

```python
# This isn't data, just a scan over x-values for plotting
x_for_plot = np.linspace(-5,5, 100)
```

```python
true_density = my_family_of_pdfs(x_for_plot,true_sigma)
plt.plot(x_for_plot, true_density, label=r'$p(x \mid \sigma=\sigma_{true})$')
plt.scatter(data, likelihood_i, label=r'$L_i(\sigma) = p(x_i \mid \sigma=\sigma_{true})$')

other_density = my_family_of_pdfs(x_for_plot,other_sigma)
plt.plot(x_for_plot, other_density, label=r'$p(x \mid \sigma=\sigma_{other})$')
plt.scatter(data, other_likelihood_i, label=r'$L_i(\sigma) = p(x_i \mid \sigma=\sigma_{other})$')

plt.ylim(0)
plt.xlabel(r'$x$')
plt.ylabel(r'$p(x \mid \sigma=\sigma_{true}$)')
plt.plot(data, [0.01]*len(data), '|', color='k')
plt.legend();
```

We will then look at the reparametrized likelihood for the individual data points $p(x_i | V)$ and since the data are i.i.d. the total likelihood is $L^\prime(V) = \prod_i p^\prime(x_i | V)$.

```python
true_density = my_reparametrized_family_of_pdfs(x_for_plot,true_V)
plt.plot(x_for_plot, true_density, label=r'$p^\prime(x \mid V=V_{true})$')
plt.scatter(data, likelihood_i, label=r'$L_i(\sigma) = p^\prime(x_i \mid V=V_{true})$')

other_density = my_reparametrized_family_of_pdfs(x_for_plot,other_V)
plt.plot(x_for_plot, other_density, label=r'$p^\prime(x \mid V=V_{other})$')
plt.scatter(data, other_likelihood_i, label=r'$L_i^\prime(\sigma) = p^\prime(x_i \mid V=V_{other})$')

plt.ylim(0)
plt.xlabel(r'$x$')
plt.ylabel(r'$p(x \mid \sigma=\sigma_{true}$)')
plt.plot(data, [0.01]*len(data), '|', color='k')
plt.legend();
```

### Evaluate the likelihoods

Since the data are i.i.d. the total likelihood is $L(\sigma) = \prod_i p(x_i | \sigma)$ and the total likelihood for the reparametrized family is $L^\prime(V) = \prod_i p^\prime(x_i | V)$. Let's make two helper functions.

We will then plot the original and reparametrized likelihoods and see that the value of the likelihood is invariant to reprametrization: eg.  $L(\sigma) = L^\prime(V(\sigma))$

```python
def my_likelihood(data,sigma):
    L = 1.
    for x in data:
        L *= my_family_of_pdfs(x,sigma)
    return L

def my_reparametrized_likelihood(data,variance):
    L = 1.
    for x in data:
        L *= my_reparametrized_family_of_pdfs(x,variance)
    return L
```

Let's compare $L(\sigma_{true})$ and $L^\prime(V(\sigma_{true}))$

```python
-2*np.log(my_likelihood(data,true_sigma)), -2*np.log(my_reparametrized_likelihood(data,true_V))
```

    (47.12737234655253, 47.12737234655253)

Let's compare $L(\sigma_{other})$ and $L^\prime(V(\sigma_{other}))$

```python
-2*np.log(my_likelihood(data,other_sigma)), -2*np.log(my_reparametrized_likelihood(data,other_V))
```

    (57.1805758896008, 57.1805758896008)

They are equal!

### Make matched pairs for the parameters

Note, we are **not** using `np.linspace` twice, we are making pairs such that  `V_for_plot[i] = sigma_for_plot[i]**2`. This is important for understanding the last three plots.

```python
sigma_for_plot = np.linspace(.5,2.5)
V_for_plot = sigma_to_V(sigma_for_plot)
#V_for_plot = np.linspace(sigma_to_V(.5),sigma_to_V(2.5)) ## NOT THIS, it would make a line in the next plot
```

```python
plt.plot(sigma_for_plot, V_for_plot, label=r'$\sigma$ vs. $V$', lw=2)
plt.plot(sigma_for_plot, sigma_for_plot**2, label=r'$\sigma$ vs. $\sigma^2$', ls='dashed')
plt.plot(np.sqrt(V_for_plot), V_for_plot, label=r'$\sqrt{V}$ vs. $V$', ls='dashed')
plt.scatter(true_sigma, true_V, label=r'$(\sigma_{true}, V_{true})$')
plt.scatter(other_sigma, other_V, label=r'$(\sigma_{other}, V_{other})$')
plt.gca().set_aspect(0.3)
plt.xlabel(r'$\sigma$')
plt.ylabel(r'$V = \sigma^2$')
plt.legend();
```

Note that above these three curves  are identical.

| x-axis  | y-axis |
|:-----: | :-----: |
| `sigma_for_plot` | `V_for_plot` |
| `sigma_for_plot` | `sigma_for_plot**2` |
| `np.sqrt(V_for_plot)` | `V_for_plot` |

### Plot the likelihoods

First, evaluate the original and reparametrized likelihoods.

```python
original_likelihood = my_likelihood(data, sigma_for_plot)
```

```python
reparametrized_likelihood = my_reparametrized_likelihood(data, V_for_plot)
```

This is somewhat subtle. When we use `plt.plot(x,y)` it assumes that `x` and `y` are arrays and that `x[i]` and `y[i]` are paired. We took care to make this be the case. So we can mix and match the input and output. If the x-axis corresponds to the input, we are directly plotting the likeilhood as it was evaluated. However, if we mix the x-axis and the input then we are reparametrizing the likelihood via plotting not via evaluation.

First consider this pair of plots. The first row is the direct evaluation of the original likelihood $L(\sigma)$. The second row is the direct evaluation of the reparametrized likelihood $L^\prime(V)$, but plotted against $\sqrt{V}$. The fact that they match shows that the value of the likelihood is invariant to reparameterization.

| Input  | Output  | x-axis for plot|
|:-----: | :-----: | :-----: |
| `sigma_for_plot` | `original_likelihood` | `sigma_for_plot` |
| `V_for_plot`     | `reparametrized_likelihood` | `np.sqrt(V_for_plot)`|

Note the use of a secondary axis on the top of the plot.

```python
fig, ax = plt.subplots(constrained_layout=True)

ax.plot(sigma_for_plot, -2.*np.log(original_likelihood), label=r'original $-2 \log L(\sigma))$', lw=2)
ax.plot(np.sqrt(V_for_plot), -2.*np.log(reparametrized_likelihood), label=r'reparameterized $-2 \log L^\prime(\sqrt{V})$', ls='dashed',lw=2)
plt.scatter(true_sigma, -2*np.log(my_likelihood(data,true_sigma)), label=r'$-2 \log L(\sigma=\sigma_{true}) $')
plt.scatter(other_sigma, -2*np.log(my_likelihood(data,other_sigma)), label=r'$-2 \log L(\sigma=\sigma_{other}) $')

ax.set_ylabel(r'$-2 \log L$')
ax.set_xlabel(r'$\sigma$')
ax.legend()
secax = ax.secondary_xaxis('top', functions=(sigma_to_V, V_to_sigma))
secax.set_xlabel(r'$V$');
```

The second plot is similar. The first row is the direct evaluation of the reparametrized likelihood $L^\prime(V)$.
The second row is the direct evaluation of the original likelihood $L(\sigma)$, but plotted against $\sigma^2$. The fact that they match shows, again, that the value of the likelihood is invariant to reparameterization.

| Input  | Output  | x-axis for plot|
|:-----: | :-----: | :-----: |
| `sigma_for_plot` | `original_likelihood` | `sigma_for_plot**2`|
| `V_for_plot`     | `reparametrized_likelihood` | `V_for_plot` |

Note the use of a secondary axis on the top of the plot.

```python
fig, ax = plt.subplots(constrained_layout=True)
ax.plot(sigma_for_plot**2, -2.*np.log(original_likelihood), label=r'original $-2 \log L(\sigma^2))$', lw=2)
ax.plot(V_for_plot, -2.*np.log(reparametrized_likelihood), label=r'reparameterized $-2 \log L^\prime(V)$', ls='dashed',lw=2)
plt.scatter(true_V, -2*np.log(my_reparametrized_likelihood(data,true_V)), label=r'$-2 \log L^\prime(V=V_{true}) $')
plt.scatter(other_V, -2*np.log(my_reparametrized_likelihood(data,other_V)), label=r'$-2 \log L^\prime(V=V_{other}) $')
ax.set_ylabel(r'$-2 \log L$')
ax.set_xlabel(r'$V$')
ax.set_xlim(.1,2.6) #need to avoid some error with secondary axis with lower lim = 0
ax.legend()
secax = ax.secondary_xaxis('top', functions=(V_to_sigma,sigma_to_V))
secax.set_xlabel(r'$\sigma $');
```

## Equivariance of the MLE

```{tip}

The **maximum likelihood** value of the parameters transform **equivariantly**.

Physicists often use the term *covariant* (or *contravariant*) in this context (eg. the way Lorentz vectors transform under a boost), but this term may be confused with the [covariance of two random variables](correlation).
```

For example, if

$$
\hat{\sigma}_{MLE} := \textrm{argmax}_\sigma L(\sigma)
$$

and

$$
\hat{V}_{MLE} := \textrm{argmax}_V L^\prime(V)
$$

then

$$
\hat{\sigma}_{MLE} = \sqrt{\hat{V}}_{MLE}
$$

and

$$
\hat{V}_{MLE} = \left ( \hat{\sigma}_{MLE} \right)^2
$$

```{warning}

Often people say that the maximum likelhood estimator is *invariant* to reparameterization, but this is sloppy language. Invariant would mean $\hat{\sigma} = \hat{V}$. Intuitively the point is that it doesn't matter which parameterization you use, you will get the same answer (and the transformation from $\sigma \to V$ is implied).

```

```{tip}

The equivariance condition can also be understood as the following commutative diagram representing $f(g·x) = g·f(x)$. Here $f$ would represent transforming from $\sigma \to V$ (eg. $X$ and $Y$ in the figure) and $g$ would represent finding the maximum likelihood for the parameter in question.

<br><a href="http://creativecommons.org/licenses/by-sa/3.0/" title="Creative Commons Attribution-Share Alike 3.0">CC BY-SA 3.0</a>, <a href="https://commons.wikimedia.org/w/index.php?curid=34670">Link</a>

```

### Check explicitly

Let's check this explicitly using `scipy.optimize`

```python
from scipy.optimize import minimize
```

```python
def likelihood_wrapper(sigma):
    return -2*np.log(my_likelihood(data, sigma))

x0 = np.array([other_sigma])
result_from_orig = minimize(likelihood_wrapper, x0, method='nelder-mead',  options={'xatol': 1e-8, 'disp': True})
sigma_MLE = result_from_orig.x
```

    Optimization terminated successfully.
             Current function value: 46.697141
             Iterations: 28
             Function evaluations: 56

```python
def reparametrized_likelihood_wrapper(sigma):
    return -2*np.log(my_reparametrized_likelihood(data, sigma))

x0 = np.array([other_V])
result_from_rep = minimize(reparametrized_likelihood_wrapper, x0, method='nelder-mead',  options={'xatol': 1e-8, 'disp': True})
V_MLE = result_from_rep.x
likelihood_at_V_MLE = np.exp(-result_from_rep.fun/2.)
```

    Optimization terminated successfully.
             Current function value: 46.697141
             Iterations: 31
             Function evaluations: 65

```python
sigma_MLE, np.sqrt(V_MLE)
```

    (array([1.14755414]), array([1.14755414]))

```python
sigma_MLE**2, V_MLE
```

    (array([1.31688049]), array([1.31688051]))

Fantastic!

## Comparison to maximum a posteriori (MAP) estimate

In a Bayesian analysis one would promote $\sigma$ to a random variable $\Sigma$ and also have a prior $p_\Sigma(\Sigma)$.

From this one would calculate the posterior using Bayes' theorem

$$
p_{\Sigma|X}(\Sigma | X=x) = \frac{p_{X|\Sigma}(X=x \mid \Sigma) p_\Sigma(\Sigma)}{p_X(X=x)}
$$

or more colloquially

$$
p(\sigma | x) = \frac{p(x \mid \sigma) p(\sigma)}{p(x)}
$$

From this Bayesian analysis often considers the [**maximum a posteriori**](https://en.wikipedia.org/wiki/Maximum_a_posteriori_estimation#Limitations) point estimate, or MAP.

$$
\hat{\sigma}_{MAP} := \textrm{argmax}_\sigma p(\sigma|x)
$$

Note that if we change variables from $\sigma \to V$, then the posterior will transform in a way that includes the Jacobian factor $|\partial V / \partial \sigma| = 2 \sigma = 2 \sqrt{V}$. This same Jacobian factor also applies to the prior $p(\theta) \to p(V)$, which makes sense given that the likelihood and the normalizing constant are invariant under reparametrization. One can ask, what is the MAP estimate for $V$?

$$
\hat{V}_{MAP} := \textrm{argmax}_V p(V|x)
$$

```{warning}

Unlike maximum likelihood estimators, the MAP estimate is not equivariant (covariant) to reparameterization.

Switching from one parameterization to another involves introducing a Jacobian that impacts on the location of the maximum.
```
Therefore,

$$
\hat{V}_{MAP}  \ne \hat{\sigma}_{MAP}^2
$$

and

$$
\hat{\sigma}_{MAP}  \ne \sqrt{\hat{V}_{MAP} }
$$

## The myth of the uninformative uniform prior

A common logical fallacy is [Confusion of the inverse](https://en.wikipedia.org/wiki/Confusion_of_the_inverse). Here is a snippet from Wikipedia

> Confusion of the inverse, also called the conditional probability fallacy or the inverse fallacy, is a logical fallacy whereupon a conditional probability is equated with its inverse; that is, given two events A and B, the probability of A happening given that B has happened is assumed to be about the same as the probability of B given A, when there is actually no evidence for this assumption. More formally, P(A|B) is assumed to be approximately equal to P(B|A).

This inverse fallacy is closely connected to the common tendency to think of the posterior and likelihood as being proportional $p(\theta|x) \propto p(x|\theta)$, which is the case if one were to place a uniform prior on $\theta$ (or implicitly setting $p(\theta)=1$ and not worrying about the normalization of the prior as long as the posterior is normalized appropriately).

Putting a uniform prior on a parameter $\theta$ is deceptively attractive. Often people say that this is an uninformative prior because it assigns equal probability (density) to all values of $\theta$.

```{warning}

A uniform prior in $\theta$ is **not** uniform in a different parameterization $\phi$.
```

As we saw in [*How do distributions transform under a change of variables?*](distributions/change-of-variables), the uniform distribution for the angle $x \in [0, 2\pi]$ was dramatically transformed when we changed variables to $\cos(x)$. Alternatively, any informative prior is uniform under the appropriate reparameterization.

So if we:
 * place a uniform prior on $\theta$
 * compute the posterior $p(\theta|x) \propto p(x|\theta)$
 * change variables from $\theta \to \phi$, which results in $p(\phi|x) = p(\phi|x) / |\partial \phi / \partial \theta | \propto p(x|\phi) / |\partial \phi / \partial \theta$

We will not get the same results as if we:
 * reparametrize from $\theta \to \phi$
 * place a uniform prior on $\phi$
 * compute the posterior $p^\prime(\phi | x) \propto p(x | \phi)$

```{tip}
This can also be thought of as **a violation of equivariance** in the following commutative diagram representing $f(g·x) = g·f(x)$. Here $f$ would represent would represent transforming from $\theta \to \phi$ (eg. $X$ and $Y$ in the diagram), and $g$ would be "derive a posterior by placing a uniform prior on the parameter in question".

<br><a href="http://creativecommons.org/licenses/by-sa/3.0/" title="Creative Commons Attribution-Share Alike 3.0">CC BY-SA 3.0</a>, <a href="https://commons.wikimedia.org/w/index.php?curid=34670">Link</a>
```

This is would not be the case if $\theta$ were discrete, and the change of variables from $\theta$ to $\phi$ was 1-to-1. In that case, the argument for a uniform prior being uninformative makes more sense.

## Demonstration of likelihood vs. posterior under reparameterization

Let's assume a uniform prior for $\sigma \in [0.5, 2.5]$, so $p(\sigma) = \frac{1}{2}$.

This will imply a prior for $V \in [0.5^2, 2.5^2]$ that is $p(V) = \frac{1}{2}\frac{1}{2 \sqrt{V}}$

Let's plot the likelihood and posterior vs. $\sigma$ and $V$.

### Sampling the posterior

It's easy to make mistakes when predicting the transformed distribution, so let's check by drawing samples $\{\sigma_i\}$ from the posterior, transforming them directly with $V_i = \sigma_i^2$, and then histograming them.

To do this we will use [the accept / reject algorithm](distributions/accept-reject) (aka [rejection sampling](prml_notebooks/ch11_Sampling_Methods.html#rejection-sampling) ).

```python
N_accep_rej = 100000
s_accep_rej = np.random.uniform(0.5,2.5, N_accep_rej)
y_accep_rej = np.random.uniform(0, np.max(original_likelihood), N_accep_rej)
mask = y_accep_rej<np.interp(s_accep_rej, sigma_for_plot, original_likelihood)
sigma_posterior_samples = s_accep_rej[mask]
```

### Normalizing the posterior

With a uniform prior in $\sigma$, the posterior is proportional to the likelihood, but we still need to normalize (the denominator in Bayes' theorem). We will use `scipy.integrate`.

```python
import scipy.integrate as integrate
```

```python
(posterior_sigma_norm, uncertainty) = integrate.quad(lambda s: np.interp(s, sigma_for_plot, original_likelihood), 0.5, 2.5)
posterior_sigma_norm
```

    4.048436794345585e-11

```python
def posterior_in_sigma(sigma):
    return np.interp(sigma, sigma_for_plot, original_likelihood)/posterior_sigma_norm

def prior_in_sigma(sigma):
    return 1./(2.5-0.5)*np.ones(sigma.size)
```

### Make the plot for $\sigma$

```python
fig, ax = plt.subplots(constrained_layout=True)

ax.hist(sigma_posterior_samples, np.linspace(0.5, 2.5,50), density=True, alpha=0.5, color='blue', label='posterior samples')
ax.plot(sigma_for_plot, posterior_in_sigma(sigma_for_plot), label=r'normalized posterior $p(\sigma | x)$', lw=2)
ax.plot(np.sqrt(V_for_plot), (original_likelihood)/posterior_sigma_norm, label=r'rescaled likelihood $L(\sigma))/Z$', ls='dashed',lw=2)
ax.plot(V_for_plot, prior_in_sigma(sigma_for_plot), label=r'uniform prior $p(\sigma)$', ls='dashed',lw=2)
ax.scatter(sigma_MLE, posterior_in_sigma(sigma_MLE), c='r', label='MLE / MAP in $\sigma$')

ax.set_ylabel(r'posterior')
ax.set_xlabel(r'$\sigma$')
ax.set_ylim(0)
ax.set_xlim(0.5, 2.5)
ax.legend()
secax = ax.secondary_xaxis('top', functions=(sigma_to_V, V_to_sigma))
secax.set_xlabel(r'$V$');
```

Notice the following:
 * The prior **is**  uniform in $\sigma$ (is it uninformative?)
 * The posterior and the likelihood have the same shape -- they are proportional to each other.
     * the MLE and MAP coincide
 * Our accept/reject samples agree with the posterior distribution

```python
sigma_MAP = sigma_MLE
```

### Make the same plot for $V$

First we transforms the samples from the prior deterministically. This is the most robust and least error prone way to check. It's also most closely tied the definition of what it means to change variables.

```python
V_posterior_samples = sigma_to_V(sigma_posterior_samples)
```

Now we will use the result from our change of variables formula to predict the posterior and prior in $V$.

```python
def posterior_in_V(V):
    sigma_ = V_to_sigma(V)
    jacobian = 2*sigma_ #doing it by hand
    return posterior_in_sigma(sigma_)/jacobian

def prior_in_V(V):
    sigma_ = V_to_sigma(V)
    jacobian = 2*sigma_ #doing it by hand
    uniform_prior_in_sigma = (1/(2.5-0.5))
    return uniform_prior_in_sigma/jacobian
```

Let's check that both the prior and posterior are normalized properly.

```python
#check normalization for posterior in V, should be 1
(V_posterior_norm, V_uncertainty) = integrate.quad(lambda V: posterior_in_V(V), 0.5**2, 2.5**2)
print('norm of posterior is {0} +/- {1}'.format(V_posterior_norm, V_uncertainty))
#don't worry about warning here, integration is good enough to make the point
```

    norm of posterior is 0.9997008924989026 +/- 7.28054934385769e-05

    <ipython-input-58-0d96b2dc5a03>:2: IntegrationWarning: The maximum number of subdivisions (50) has been achieved.
      If increasing the limit yields no improvement it is advised to analyze
      the integrand in order to determine the difficulties.  If the position of a
      local difficulty can be determined (singularity, discontinuity) one will
      probably gain from splitting up the interval and calling the integrator
      on the subranges.  Perhaps a special-purpose integrator should be used.
      (V_posterior_norm, V_uncertainty) = integrate.quad(lambda V: posterior_in_V(V), 0.5**2, 2.5**2)

```python
#check normalization for prior in V, should be 1
(V_prior_norm, V_uncertainty) = integrate.quad(lambda V: prior_in_V(V), 0.5**2, 2.5**2)
V_prior_norm
```

    1.0000000000000073

```python
#calculate integral of likelihood in V, just for plotting purposes
(V_L_norm, uncertainty) = integrate.quad(lambda V: np.interp(V, V_for_plot, reparametrized_likelihood), 0.5**2, 2.5**2)
V_L_norm
```

    1.0155480361220947e-10

let's find the MAP

```python
x0 = np.array([other_V])
result_from_rep = minimize(lambda V: -posterior_in_V(V), x0, method='nelder-mead',  options={'xatol': 1e-8, 'disp': True})
V_MAP = result_from_rep.x
posterior_at_V_MAP = -result_from_rep.fun
```

    Optimization terminated successfully.
             Current function value: -0.792190
             Iterations: 31
             Function evaluations: 62

```python
fig, ax = plt.subplots(constrained_layout=True)
ax.hist(V_posterior_samples, np.linspace(0.5**2, 2.5**2,50), density=True, alpha=0.5, color='blue', label='posterior samples')
ax.plot(V_for_plot, posterior_in_V(V_for_plot), label=r'normalized posterior $p(V| x)$', lw=2)
ax.plot(V_for_plot, (reparametrized_likelihood)/V_L_norm, label=r'rescaled likelihood $L^\prime(V)$', ls='dashed',lw=2)
ax.plot(V_for_plot, prior_in_V(V_for_plot), label=r'transformed prior $p(V)$$', ls='dashed',lw=2)
ax.scatter(V_MLE, likelihood_at_V_MLE/V_L_norm, c='r', label=r'$\hat{V}_{MLE}$')
ax.scatter(V_MAP, posterior_at_V_MAP, c='b', label=r'$\hat{V}_{MAP}$')

ax.set_ylabel(r'$posterior$')
ax.set_xlabel(r'$V$')
ax.set_xlim(.5**2,2.5**2) #need to avoid some error with secondary axis with lower lim = 0
ax.legend()
secax = ax.secondary_xaxis('top', functions=(V_to_sigma,sigma_to_V))
secax.set_xlabel(r'$\sigma $');
```

Check the MLE and the MAP for $V$.

```python
V_MLE, V_MAP
```

    (array([1.31688051]), array([1.23708871]))

### Violation of equivaraince for the MAP and posterior

Notice the following:
 * Remember, we know theand the MLE is equivariant and $\hat{\sigma}_{MLE}=\hat{\sigma}_{MAP}$, but
    * $\hat{V}_{MLE} \ne \hat{V}_{MAP}$. Therefore the MAP is not equivariant
 * Remember, we know the likelihood is invariant, but the posterior and the likelihood are **no longer** proportional to each other anymore.
     * Therefore we do not obtain the same posterior for $V$ if we apply a uniform prior in $V$.
     * The uniform prior in $\sigma$ **does not** correspond to a uniform prior $V$, thus it is not uninformative for $V$ even though this is just the resut of a reparameterization of the same likelihood, prior, and posterior. The converse also holds, a uniform prior in $V$ is not uninformative for $\sigma$.

```{warning}
Think carefully before you put a uniform prior on whatever parameters are presented to you, and do not fool yourself into thinking a uniform prior is uninformative in some universal, parameterization-independent way.
```

## Food for thought

```{admonition} Food for thought: Equipartion of energy
:class: tip

A key concept in statistical mechanics is the **equipartion of energy**, which assigns equal probability to states with the same energy. This is uniform distribution. If we are working with discrete states, then there is no ambiguity, but how do we understand equipartition of energy for continuous state spaces? In what variables is the system uniformly distributed?
```

```{admonition} Food for thought: Lorentz Invariant Phase space
:class: tip

In particle physics, the differential scattering cross-section is often factorized into the product of a squared-matrix element and a phase space term. This is like Fermi's golden rule that is a product of a transition rate( $\propto$ probability per unit time) and a density of states. It is also structurally similar to a product of a likelhood and a prior, where phase space plays the role of the prior. In what variables is the Lorentz invariant phase space uniform (and why)?
```

```python

```


## Data modelling

```python
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```

Let's generate some noisy data to play with

```python
np.random.seed(1234)
a = 0.1
N0, N1 = 0.1, 1
npts = 200
X = np.linspace(0, 20, npts)
Y0_clean = N0 + N1*(1-np.exp(-a*X))
Y1_clean = N1*np.exp(-a*X)
Y0 = N0 + N1*(1-np.exp(-a*X)) + np.random.randn(npts)*0.5
Y1 = N1*np.exp(-a*X) + np.random.randn(npts)*0.5
plt.plot(X, Y0, "o")
plt.plot(X, Y1, "o");
```

```python
from sympy import *
init_session(quiet=True)
alpha, N0, N1 = symbols("alpha, N0, N1", positive=True)
```

We have a model a we would like to find the parameters - rate $\alpha$ and initial numbers $N_0$ and $N_1$

```python
eqn = Eq(f(x).diff(x), alpha*g(x)), Eq(g(x).diff(x), -alpha*g(x))
eqn
```

The dsolve method can also calculate the integration constants if initial conditions are supplied

```python
sol = dsolve(eqn, (f(x), g(x)), ics={f(0): N0, g(0): N1})
sol
```

Convert the solution to numerical function

```python
fl = lambdify((x, N0, N1, alpha), sol[0].args[1])
gl = lambdify((x, N0, N1, alpha), sol[1].args[1])
```

and fit the model to our data

```python
import lmfit
p0 = lmfit.Parameters()
p0.add_many(("N0", 1), ("N1", 1), ("alpha", 1))
def model(p, x):
    pval = p.valuesdict()
    r0 = fl(x, pval["N0"], pval["N1"], pval["alpha"])
    r1 = gl(x, pval["N0"], pval["N1"], pval["alpha"])
    return (r0, r1)
def residual(p, x, data):
    r0, r1 = model(p, x)
    return np.hstack((r0-data[0], r1-data[1]))
minimizer = lmfit.Minimizer(residual, p0, (X, (Y0, Y1)))
res = minimizer.leastsq()
lmfit.report_fit(res)
```

    [[Fit Statistics]]
        # fitting method   = leastsq
        # function evals   = 39
        # data points      = 400
        # variables        = 3
        chi-square         = 93.7152421
        reduced chi-square = 0.23605854
        Akaike info crit   = -574.481481
        Bayesian info crit = -562.507087
    [[Variables]]
        N0:     0.09039005 +/- 0.07641406 (84.54%) (init = 1)
        N1:     1.06458638 +/- 0.07266232 (6.83%) (init = 1)
        alpha:  0.09072997 +/- 0.01093316 (12.05%) (init = 1)
    [[Correlations]] (unreported correlations are < 0.100)
        C(N0, N1)    = -0.791
        C(N0, alpha) = -0.786
        C(N1, alpha) =  0.560

The fitted values are within uncertainties equal to the true parameters, which were used to generate the data. The fit required 39 evaluations of the residual.

Lmfit was using numerical approximation of model jacobian. Can we improve it? Sympy has a method for calculating matrix jacobian

```python
F = Matrix([sol[0].args[1], sol[1].args[1]])
P = Matrix([N0, N1, alpha])
J = F.jacobian(P)
J
```

$$\left[\begin{matrix}1 & 1 - e^{- \alpha x} & N_{1} x e^{- \alpha x}\\0 & e^{- \alpha x} & - N_{1} x e^{- \alpha x}\end{matrix}\right]$$

we convert the symbolic jacobian into numerical function suitable for `leastsq` optimization

```python
ljac = [[lambdify((x, N0, N1, alpha), J[i, j]) for i in range(2)] for j in range(3)]
def Dfun(p, x, data):
    pval = p.valuesdict()
    r0 = [np.hstack((
        jel[0](x, pval["N0"], pval["N1"], pval["alpha"])*np.ones_like(x),
        jel[1](x, pval["N0"], pval["N1"], pval["alpha"])*np.ones_like(x)
    )) for jel in ljac]
    return np.array(r0).T
```

```python
res = minimizer.leastsq(Dfun=Dfun)
lmfit.report_fit(res)
```

    [[Fit Statistics]]
        # fitting method   = leastsq
        # function evals   = 12
        # data points      = 400
        # variables        = 3
        chi-square         = 93.7152421
        reduced chi-square = 0.23605854
        Akaike info crit   = -574.481481
        Bayesian info crit = -562.507087
    [[Variables]]
        N0:     0.09039004 +/- 0.07641405 (84.54%) (init = 1)
        N1:     1.06458638 +/- 0.07266232 (6.83%) (init = 1)
        alpha:  0.09072997 +/- 0.01093316 (12.05%) (init = 1)
    [[Correlations]] (unreported correlations are < 0.100)
        C(N0, N1)    = -0.791
        C(N0, alpha) = -0.786
        C(N1, alpha) =  0.560

Now we needed only 12 evaluations

```python
%matplotlib inline
plt.plot(X, Y0, "o", ms=2, label="data0")
plt.plot(X, Y1, "o", ms=2, label="data1")
plt.plot(X, model(res.params, X)[0], c="C0", label="fit0")
plt.plot(X, model(res.params, X)[1], c="C1", label="fit1")
plt.plot(X, Y0_clean, ":", c="C0", label="original0")
plt.plot(X, Y1_clean, ":", c="C1", label="original1")
```


## SVD - PCA: More Applications
---

```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
import os
```

### Eigenfaces reference

>- The seminal paper on Eigenfaces [MIT Media Lab](https://direct.mit.edu/jocn/article/3/1/71/3025/Eigenfaces-for-Recognition)

>- Above paper arranged as easy lecture notes on [ScholarPedia] by Dr. Zhang and Dr. Tucker (http://scholarpedia.org/article/Eigenfaces)

>- Chapter 1 from Textbook By Dr. Brunton

---

### Summary of the mathematics for eigenfaces
---
>- The Columns of matrix $X$ represent facial images after thorough preproessing (cropping, centering, alignment etc).

>- The mean-adjusted faces $\tilde{X} = X - \bar{X}$, where $\bar{X} = \frac{1}{M} \sum_{j=1}^M X_{:j}$ (called the mean face). (Note that the data here is not column centered but row centered.)

>- Find eigendecomposition of $S = \frac{1}{M-1}(X-\bar{X})^T (X-\bar{X})$ (one can also just use $M$ in place of $M-1$):
$$
SV = \Lambda V
$$

>- Equivalent SVD formulation: $(X-\bar{X}) = U \sum V^T$, implying $\tilde{X} V = U \sum$.

Note that in place of taking the usual approach of finding the eigen-decomposition of $(X-\bar{X}) (X-\bar{X})^T$, the above approach works better if the dimension of the images is larger compared to the number of images. The former would be preferred if the number of images is way more relative to the dimension.

>- **Face Space**: Columns of $U$ are called the eigenfaces of the facial image database given by matrix $X$. They form the face space whose origin is the average face and whose axes are the eigenfaces.

>- **Low rank ($k$ eigenfaces) representation** of the image database
$$\tilde{X}  = U_{(k)} \Sigma_{(k)} V_{(k)}^T$$

### Face Reconstruction
**Retriving** the $p$-th image from the low rank representation
$$
\begin{align}
X_{:p} - \bar{X} &\approx U_{(k)} \left[ \Sigma_{(k)} V^T_{(k)} \right]_{:p}\\
X_{:p} &\approx \bar{X} + U_{(k)} \left[ \Sigma_{(k)} V^T_{(k)} \right]_{:p}\\
&= \bar{X} + U_{(k)} \left[  V_{(k)} \Sigma_{(k)} \right]_{p:}\\
&= \bar{X} + \sum_{j=1}^k \alpha_j U_{:j} \quad \text{ where }\ \alpha_j = \sigma_j V_{pj} = \sqrt{\lambda_j (M-1)}\;V_{pj}
\end{align}
$$

### Face Detection

>- Projection of an image x on the face space $ U_{(k)}  U_{(k)}^T (x-\bar{x})$.

>- Distance of the projection from the original
$$
\delta = \|\tilde{x} - U_{(k)}  U_{(k)}^T \tilde{x}\|
$$

>- The distance of a face from the face space is smaller compared to other kind of images such as a doc, a tree, or cup etc.

### Face Recognition

>- Find the linear coding (or weight vector) in projecting an image $\tilde{x} = x - \bar{x}$ to the face space:
$$
\alpha =  U_{(k)}^T  \tilde{x}
$$

>- An image could belong to a class $k$ if the
$$
\|\alpha - \alpha_k\| \le \theta,\ \text{ a predefined threshold }
$$

>- If the threshold criteria is not met then the image is declared unknown.

#### Eigenface Example:

>-Following example is from a [blog by Nev Acar](https://towardsdatascience.com/eigenfaces-recovering-humans-from-ghosts-17606c328184). Only some minor modifications have been made to the original code.

```python
"""It helps visualising the portraits from the dataset."""
def plot_portraits(images, titles, h, w, n_row, n_col):
    plt.figure(figsize=(2.2 * n_col, 2.2 * n_row))
    plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.20)
    for i in range(n_row * n_col):
        plt.subplot(n_row, n_col, i + 1)
        plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
        plt.title(titles[i])
        plt.xticks(())
        plt.yticks(())
```

```python
dir='lfwcrop_grey/faces'
#dir='YALE/centered'
celebrity_photos=os.listdir(dir)[1:1001]
celebrity_images=[dir+'/' + photo for photo in celebrity_photos]
images=np.array([plt.imread(image) for image in celebrity_images], dtype=np.float64)
celebrity_names=[name[:name.find('0')-1].replace("_", " ") for name in celebrity_photos]
n_samples, h, w = images.shape
print("Dimensions:",images.shape)
plot_portraits(images, celebrity_names, h, w, n_row=4, n_col=4)
```

```python
def eigenfaces(X, n_pc):
    n_samples, n_features = X.shape
    mean = np.mean(X, axis=0)
    centered_data = X-mean
    pca_obj = PCA(n_components=n_pc)
    projected  = pca_obj.fit_transform(centered_data)
    #U, S, V = np.linalg.svd(centered_data)
    components = pca_obj.components_
    #projected = U[:,:n_pc]*S[:n_pc]

    return projected, components, mean, centered_data
```

```python

```

```python
n_components = 200
X = images.reshape(n_samples, h*w)
P, C, M, Y= eigenfaces(X, n_components)
```

```python
# The mean-face
plt.imshow(M.reshape((h, w)), cmap=plt.cm.gray)
plt.show()
```

```python
eigenfaces = C.reshape((n_components, h, w))
eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
plot_portraits(eigenfaces, eigenface_titles, h, w, 4, 4)
```

```python

def reconstruction(Y, C, M, h, w, image_index):
    n_samples, n_features = Y.shape
    weights = np.dot(Y, C.T)
    centered_vector=np.dot(weights[image_index, :], C)
    recovered_image=(M+centered_vector).reshape(h, w)
    return recovered_image
recovered_images=[reconstruction(Y, C, M, h, w, i) for i in range(len(images))]
plot_portraits(recovered_images, celebrity_names, h, w, n_row=4, n_col=4)
```

```python

```

#### Some observations on eigenfaces (Brunton)

>- First few eigenfaces 'capture the most common features shared among all human faces...'

>- '... while the other PCs will be more useful in distinguishing between individuals...'

>- '... additional PCs my capture differences in lighting angles.'

#### Alignment of data and SVD

"SVD is sensitive to the alignment in data. In fact the SVD rank explodes when objects in the columns translate, rotate or scale, which severely limits its use for data that has not been heavily preprocessed"

### Robust PCA
---
**Question**: Do you agree that finding the first-$k$ PCs is equivalent to solving the following problem? Provide your reasoning.

$$\large
\operatorname{minimize}\ \|\tilde{X}-L\|_F,  \textrm{ subject to }\ \operatorname{rank}(L) \leq k.
$$

Note: PCA is sensitive to presence of outliers and errors in dataset.

 Robust Principal Component Analysis : Decomposition as $X \approx L+S$, such that $L$ represents the low-rank structure in the data and $S$ represents sparse `noise' in $A$.

$$\large
\operatorname{minimize}\ \|L\|_* + \lambda\, \|S\|_1
$$

where $\|L\|_* = \sigma_1 + \cdots+ \sigma_r$ is called the **nuclear norm** of $L$ and $\lambda$ is a penalty parameter.

>- In some applications such as video surveillance, we are interested in 'noise'.

>- Choice of $\lambda = 1/ \sqrt{max(n,\,m)}$ works well, so we can avoid parameter tuning.

>- Principal component pursuit is a popular method for this optimization. Under certain non-stringent conditions it is possible to find the low-rank and sparse components with high probability.

[Reading 3](https://arxiv.org/abs/0912.3599)

#### Question: How does $L_1$ norm induce sparsity? LASSO vs Ridge.

[Image Source: WikiMedia](https://upload.wikimedia.org/wikipedia/commons/f/f8/L1_and_L2_balls.svg)

**READING: Augmented Lagrangian Method** for solving constrained optimization problems.

[University of Winsconsin Notes](http://pages.cs.wisc.edu/~swright/nd2016/IMA_augmentedLagrangian.pdf)

[Wikipedia](https://en.wikipedia.org/wiki/Augmented_Lagrangian_method)

>- Here is a detailed set of [notes on RPCA](https://nbviewer.jupyter.org/github/fastai/numerical-linear-algebra/blob/master/nbs/3.%20Background%20Removal%20with%20Robust%20PCA.ipynb)

>- Here is a quick [blog on RPCA](https://kojinoshiba.com/robust-pca/)

```python

```