# Introduction to Principal Component Analysis

Contributers: Linghao Dong, Josh Beck, Jose Figueroa, Yuvraj Chopra

## Sections:

- [PCA (Principal Component Analysis)](#PCA-(Principal-Component-Analysis))
- [Origin](#Origin)
- [Learning Objective](#Learning-Objective)
- [PCA ](#PCA-)
- [Eigenvectors](#Eigenvectors)
- [Running PCA](#Running-PCA)
- [Homework](#Homework)

## Origin
- - - - - --  -
This notebook was adapted from amueller's notebook, "*1 - PCA*". Here is the link to his repository https://github.com/amueller/tutorial_ml_gkbionics.git .

This notebook provides examples for eigenvalues and eigenvectors in LaTeX and python.

## Learning Objective
- - - - - -
1. How the Principal Componenet Analysis (PCA) works.
2. How PCA can be used to do dimensionality reduction.
3. Understand how PCA deals with the covariance matrix by applying eigenvectors.

## PCA
- - - - --
PCA can always be used to simplify the data with high dimensions (larger than 2) into 2-dimensional data by eliminating the least influntial features on the data. However, we should know the elimination of data makes the independent variable less interpretable. Before we start to deal with the PCA, we need to first learn how PCA utilizes eigenvectors to gain a diagonalization covariance matrix.

## Eigenvectors
- - - - - - -
Eigenvectors and eigenvalues are the main tools used by PCA to obtain a diagnolization covariance matrix. The eigenvector is a vector whos direction will not be affected by the linear transformation, hence eigenvectors represents the direction of largest variance of data while the eigenvalue decides the magnitude of this variance in those directions.

Here we using a simple (2x2) matrix $A$ to explain it.
$$
A = \begin{bmatrix}
1 & 4 \\
3 & 2
\end{bmatrix}
$$

```python
# importing class
import sympy as sp
import numpy as np
import numpy.linalg as lg
A = np.matrix([[1,4],[3,2]])
```

In general, the eigenvector $v$ of a matrix $A$ is the vector where the following holds:
$$
Av = \lambda v
$$
for which $\lambda$ stands for the eigenvalue such that linear transformation on $v$ can be defined by $\lambda$

Also, we can solve the equation by:
$$
Av - \lambda v = 0 \\
v(A-\lambda I) = 0
$$
While $I$ is the identity matrix of A

$$
I = A^TA = AA^T
$$
In this case, if $v$ is none-zero vector than $Det(A - \lambda I) = 0$, since it cannot be invertible, and we can solve $v$ for $A$ depends on this relationship.
$$
I = \begin{bmatrix}
1 & 0 \\
0 & 1
\end{bmatrix} \\
$$

```python
def solveLambda(A = A,Lambda = sp.symbols("Lambda", real = True) ):
    I = A*A.I
    I = np.around(I, decimals =0)
    return (A - Lambda*I)
Lambda = sp.symbols("Lambda", real = True)
B = solveLambda(A = A, Lambda = Lambda)
B
```

    matrix([[-1.0*Lambda + 1, 4],
            [3, -1.0*Lambda + 2]], dtype=object)

$$
(A - \lambda I) = \begin{bmatrix}
1-\lambda & 4 \\
3 & 2 - \lambda
\end{bmatrix} \\
$$

To solve the $\lambda$ we can use the function solve in sympy or calculating.

```python
function = Lambda**2 - 3*Lambda - 10
answer = sp.solve(function, Lambda)
answer
```

    [-2, 5]

In this case, $\lambda_1 = -2$ and $\lambda_2 = 5$, and we can figure out the eigenvectors in two cases.

For $\lambda_1 = -2$

```python
identity = np.identity(len(A))
eigenvectors_1 = A - answer[0]*identity
eigenvectors_1
```

    matrix([[3.00000000000000, 4],
            [3, 4.00000000000000]], dtype=object)

Based on the matrix we can infer the eigenvector can be
$$
v_1 = \begin{bmatrix}
-4 \\
3\end{bmatrix}
$$

For $\lambda = 5$

```python
eigenvectors_2 = A - answer[1]*identity
eigenvectors_2
```

    matrix([[-4.00000000000000, 4],
            [3, -3.00000000000000]], dtype=object)

Based on the matrix we can infer the eigenvector can be
$$
v_2 = \begin{bmatrix}
1\\
1\end{bmatrix}
$$
All in all, the covariance matrix $A'$ now can be:
$$
A' = v * A \\
$$

Such that we can obtain the matrix $V$
$$
V = \begin{bmatrix}
-4 & 1 \\
3 & 1
\end{bmatrix}
$$
where $A' = V^{-1} A V$ for the diagnalization:

```python
V = np.matrix([[-4,1],[3,1]])
diagnalization = V.I * A * V
diagnalization
```

    matrix([[-2.,  0.],
            [-0.,  5.]])

Hence, the diagonalization covariance matrix is
$$
\begin{bmatrix}
-2 & 0\\
0 & 5
\end{bmatrix}
$$
Luckily, PCA can do all of this by applyng the function `pca.fit_transform(x)` and `np.cov()`

## Generating Data

To talking about PCA, we first create 200 random two-dimensional data points and have a look at the raw data.

```python
import numpy as np
import matplotlib.pyplot as plt
Cov = np.array([[2.9, -2.2], [-2.2, 6.5]])
X = np.random.multivariate_normal([1,2], Cov, size=200)
X
```

    array([[-0.3314,  3.89  ],
           [-0.7628,  3.1064],
           [ 1.6646,  0.7326],
           [-0.0324,  3.3294],
           [ 1.4957,  1.7005],
           [ 2.4818, -4.1281],
           [-1.0768,  0.5441],
           [-0.0016, -0.197 ],
           [ 2.1528, -3.6236],
           [ 0.7061,  5.6325],
           [ 1.9122, -3.3293],
           [ 0.7292,  2.2281],
           [-2.1433,  1.2667],
           [ 0.8705,  7.423 ],
           [-0.0862,  3.7529],
           [ 1.2707, -2.7226],
           [ 0.0611,  3.5154],
           [-1.7579, 10.868 ],
           [ 1.0198,  2.4983],
           [-0.0665,  2.5196],
           [-0.558 ,  4.4565],
           [ 2.1584,  1.4487],
           [-0.3084,  1.2216],
           [ 1.9434,  0.8833],
           [-0.0335,  0.0624],
           [ 1.199 , -2.2869],
           [ 1.6465,  1.6136],
           [ 1.374 , -1.2927],
           [ 2.1607,  2.5391],
           [ 0.1091,  7.8452],
           [ 1.1176, -2.4849],
           [ 3.2651, -0.5992],
           [ 4.03  ,  0.0084],
           [ 2.5643,  0.2302],
           [ 0.4196, -0.2854],
           [-0.6474, -1.4366],
           [ 0.6727,  2.1102],
           [ 2.2817,  1.1636],
           [-0.3117,  0.8201],
           [ 2.4958, -0.4984],
           [ 2.289 ,  0.6661],
           [ 0.2565,  2.3338],
           [-2.5811,  2.7491],
           [ 0.2393,  3.3853],
           [ 1.2671,  0.6598],
           [ 1.1784, -1.9555],
           [ 0.7458,  4.5397],
           [ 1.7347, -0.0982],
           [ 2.3371,  0.3336],
           [-1.2219,  2.6902],
           [ 5.8417, -2.0452],
           [ 2.4971, -4.8371],
           [ 0.8998,  3.7154],
           [ 3.1265,  1.4012],
           [ 0.5932, -0.6629],
           [ 4.7175,  0.306 ],
           [-0.6361,  2.9971],
           [ 1.5415,  3.6623],
           [-1.8985,  6.8546],
           [ 0.36  ,  3.0732],
           [ 0.3536,  1.9734],
           [ 1.2103,  0.9567],
           [ 1.1925,  4.6863],
           [ 0.2706,  3.2078],
           [ 1.6517,  6.0517],
           [-0.0253,  2.4021],
           [ 1.7716,  1.2569],
           [ 2.74  , -0.2166],
           [-0.4161,  2.5067],
           [ 1.3702,  2.6354],
           [-1.6332,  0.3802],
           [-0.9584,  5.4841],
           [ 4.2051, -1.9136],
           [ 1.7001, -1.057 ],
           [-2.1647,  3.797 ],
           [ 0.7634,  3.5773],
           [ 3.1714,  2.3534],
           [ 2.893 ,  2.1926],
           [ 1.6868,  2.0728],
           [ 1.1536,  1.4466],
           [ 2.3477,  2.9826],
           [ 0.0636,  3.1583],
           [ 1.4827,  4.5008],
           [-3.0736,  4.1688],
           [ 2.9109, -0.4089],
           [-0.1036,  5.9447],
           [-1.0138,  3.7213],
           [ 0.512 ,  2.0402],
           [ 0.9409,  1.8335],
           [-0.3748,  2.9108],
           [ 2.5172,  3.249 ],
           [ 1.6167, -2.2142],
           [ 0.9427,  2.962 ],
           [ 0.1689,  3.8406],
           [ 5.1565, -2.0153],
           [ 1.6778,  0.2878],
           [ 2.3773,  3.6426],
           [ 3.1883,  6.3567],
           [ 3.2663, -0.9719],
           [-0.8649,  1.3055],
           [ 2.9723,  1.3092],
           [-0.3873,  3.8015],
           [-0.6916,  0.2784],
           [ 1.5806,  2.8773],
           [-2.6898,  0.2236],
           [ 1.7335,  2.7428],
           [-2.8561,  4.9929],
           [ 0.5896,  3.5652],
           [ 1.3417,  4.2343],
           [-1.5769,  3.6546],
           [-0.2316,  4.0993],
           [ 2.0261,  2.2127],
           [ 0.6812,  4.2448],
           [ 2.5264, -0.1094],
           [-1.1219,  1.822 ],
           [ 1.7628,  4.6134],
           [ 1.4077, -1.5837],
           [-2.0643,  5.6098],
           [-1.5796, -0.9632],
           [ 0.8479,  1.6023],
           [ 0.5994,  2.7838],
           [ 1.748 ,  0.8479],
           [ 0.7111,  3.0203],
           [ 3.1584,  3.6146],
           [ 1.6388,  0.1935],
           [ 1.4178,  5.6603],
           [ 1.3809, -1.65  ],
           [-2.5293,  1.8252],
           [ 0.8411,  2.7598],
           [ 4.4251, -4.2378],
           [ 1.3662,  6.2816],
           [ 4.8566, -2.797 ],
           [ 2.4947,  3.5425],
           [ 2.6414,  3.4424],
           [ 3.0274, -1.8749],
           [ 1.8957,  4.1716],
           [ 0.3048,  2.5195],
           [-0.8176,  1.9724],
           [ 2.2711, -1.0521],
           [-1.4846,  6.1564],
           [ 1.5305,  2.4364],
           [-3.6281,  4.7268],
           [ 1.9209,  3.1358],
           [-0.1875,  1.3458],
           [ 1.5508,  1.1897],
           [-0.453 ,  3.157 ],
           [ 0.3166,  5.6812],
           [ 1.2475, -1.2925],
           [ 0.6289, -0.0265],
           [ 4.5071, -3.9719],
           [-4.6409,  7.5164],
           [ 0.6281,  2.217 ],
           [ 3.914 , -1.1867],
           [-1.4267,  5.0641],
           [-0.6267,  0.6514],
           [ 0.2353,  1.9975],
           [-0.5444,  4.3321],
           [ 0.2872,  1.536 ],
           [ 1.525 ,  2.8937],
           [ 3.0588, -2.5527],
           [ 0.4209,  3.2408],
           [ 0.7062,  1.4383],
           [ 2.6603, -2.1632],
           [ 1.8192, -4.1824],
           [-0.0446, -1.9047],
           [-0.6859,  1.9545],
           [ 2.4622,  5.5611],
           [ 0.8626,  0.7514],
           [ 0.1203,  0.3933],
           [ 3.4888, -0.1091],
           [-0.044 ,  5.6352],
           [ 0.1169,  7.151 ],
           [ 2.8861,  0.7694],
           [ 1.8575,  1.6054],
           [ 1.0553,  0.9859],
           [-1.6186,  5.4372],
           [ 0.1434,  2.5842],
           [-2.7287,  3.4333],
           [ 1.2537,  3.4039],
           [ 3.8895,  0.3228],
           [ 2.703 ,  2.7327],
           [ 2.1067, -0.8624],
           [ 2.1412, -2.6187],
           [ 0.4335,  1.0761],
           [ 2.4168,  0.7427],
           [ 1.2818,  2.3239],
           [ 0.9299, -0.7568],
           [ 2.7285,  4.723 ],
           [ 2.0622, -1.2527],
           [ 0.6134, -1.1116],
           [ 0.1832,  1.8245],
           [ 0.6402,  3.063 ],
           [ 0.0104,  0.6147],
           [-0.1717,  2.4591],
           [ 3.1577,  0.0922],
           [-0.5113,  1.2958],
           [-1.087 ,  2.3454],
           [ 5.1135,  1.6048],
           [ 1.1075,  3.9919],
           [ 3.1513,  6.5368]])

```python
np.set_printoptions(4, suppress=True) # show only four decimals
print (X[:10,:]) # print the first 10 rows of X (from 0 to 9)
```

    [[-0.3314  3.89  ]
     [-0.7628  3.1064]
     [ 1.6646  0.7326]
     [-0.0324  3.3294]
     [ 1.4957  1.7005]
     [ 2.4818 -4.1281]
     [-1.0768  0.5441]
     [-0.0016 -0.197 ]
     [ 2.1528 -3.6236]
     [ 0.7061  5.6325]]

We round the whole data for only 4 decimals.

However, there is no obvious relationship based on this 2-dimensional data, hence we plot it.

```python
plt.figure(figsize=(4,4))
plt.scatter(X[:,0], X[:,1], c= "b", edgecolor = "black")
plt.axis('equal') # equal scaling on both axis;
```

We can have a look at the actual covariance matrix,as well:

```python
print (np.cov(X,rowvar=False))
```

    [[ 3.0298 -2.0123]
     [-2.0123  6.9672]]

## Running PCA
- - -- - -- - -
We would now like to analyze the directions in which the data varies most. For that, we

1. place the point cloud in the center (0,0) and
2. rotate it, such that the direction with most variance is parallel to the x-axis.

Both steps can be done using PCA, which is conveniently available in sklearn.

We start by loading the PCA class from the sklearn package and creating an instance of the class:

```python
from sklearn.decomposition import PCA
pca = PCA()
```

Now, `pca` is an object which has a function `pca.fit_transform(x)` which performs both steps from above to its argument `x`, and returns the centered and rotated version of `x`.

```python
X_pca = pca.fit_transform(X)
```

```python
pca.components_
```

    array([[-0.3877,  0.9218],
           [-0.9218, -0.3877]])

```python
pca.mean_
```

    array([0.9667, 1.8289])

```python
plt.figure(figsize=(4,4))
plt.scatter(X_pca[:,0], X_pca[:,1],c = "b", edgecolor = "black")
plt.axis('equal');
```

The covariances between different axes should be zero now. We can double-check by having a look at the non-diagonal entries of the covariance matrix:

```python
print (np.cov(X_pca, rowvar=False))
```

    [[7.8137 0.    ]
     [0.     2.1833]]

## High-Dimensional Data

Our small example above was very easy, since we could get insight into the data by simply plotting it. This approach will not work once you have more than 3 dimensions, Let's use the famous iris dataset, which has the following 4 dimensions:
 * Sepal Length
 * Sepal Width
 * Pedal Length
 * Pedal Width

```python
!wget https://raw.githubusercontent.com/RPI-DATA/tutorials-intro/master/principal-components-clustering/notebooks/bezdekIris.data
```

    --2019-03-11 14:43:40--  https://raw.githubusercontent.com/RPI-DATA/tutorials-intro/master/principal-components-clustering/notebooks/bezdekIris.data
    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...
    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.0.133|:443... connected.
    HTTP request sent, awaiting response... 200 OK
    Length: 4551 (4.4K) [text/plain]
    Saving to: ‘bezdekIris.data.1’

    bezdekIris.data.1   100%[===================>]   4.44K  --.-KB/s    in 0s

    2019-03-11 14:43:40 (75.4 MB/s) - ‘bezdekIris.data.1’ saved [4551/4551]

```python
from io import open
data = open('bezdekIris.data', 'r').readlines()
iris_HD = np.matrix([np.array(val.split(',')[:4]).astype(float) for val in data[:-1]])
```

Lets look at the data again. First, the raw data:

```python
print (iris_HD[:10])
```

    [[5.1 3.5 1.4 0.2]
     [4.9 3.  1.4 0.2]
     [4.7 3.2 1.3 0.2]
     [4.6 3.1 1.5 0.2]
     [5.  3.6 1.4 0.2]
     [5.4 3.9 1.7 0.4]
     [4.6 3.4 1.4 0.3]
     [5.  3.4 1.5 0.2]
     [4.4 2.9 1.4 0.2]
     [4.9 3.1 1.5 0.1]]

Since each dimension has different scale in the Iris Database, we can use `StandardScaler` to standard the unit of all dimension onto unit scale.

```python
from sklearn.preprocessing import StandardScaler
iris_HD = StandardScaler().fit_transform(iris_HD)
iris_HD
```

    array([[-0.9007,  1.019 , -1.3402, -1.3154],
           [-1.143 , -0.132 , -1.3402, -1.3154],
           [-1.3854,  0.3284, -1.3971, -1.3154],
           [-1.5065,  0.0982, -1.2834, -1.3154],
           [-1.0218,  1.2492, -1.3402, -1.3154],
           [-0.5372,  1.9398, -1.1697, -1.0522],
           [-1.5065,  0.7888, -1.3402, -1.1838],
           [-1.0218,  0.7888, -1.2834, -1.3154],
           [-1.7489, -0.3622, -1.3402, -1.3154],
           [-1.143 ,  0.0982, -1.2834, -1.4471],
           [-0.5372,  1.4794, -1.2834, -1.3154],
           [-1.2642,  0.7888, -1.2266, -1.3154],
           [-1.2642, -0.132 , -1.3402, -1.4471],
           [-1.87  , -0.132 , -1.5107, -1.4471],
           [-0.0525,  2.17  , -1.4539, -1.3154],
           [-0.1737,  3.0908, -1.2834, -1.0522],
           [-0.5372,  1.9398, -1.3971, -1.0522],
           [-0.9007,  1.019 , -1.3402, -1.1838],
           [-0.1737,  1.7096, -1.1697, -1.1838],
           [-0.9007,  1.7096, -1.2834, -1.1838],
           [-0.5372,  0.7888, -1.1697, -1.3154],
           [-0.9007,  1.4794, -1.2834, -1.0522],
           [-1.5065,  1.2492, -1.5676, -1.3154],
           [-0.9007,  0.5586, -1.1697, -0.9205],
           [-1.2642,  0.7888, -1.056 , -1.3154],
           [-1.0218, -0.132 , -1.2266, -1.3154],
           [-1.0218,  0.7888, -1.2266, -1.0522],
           [-0.7795,  1.019 , -1.2834, -1.3154],
           [-0.7795,  0.7888, -1.3402, -1.3154],
           [-1.3854,  0.3284, -1.2266, -1.3154],
           [-1.2642,  0.0982, -1.2266, -1.3154],
           [-0.5372,  0.7888, -1.2834, -1.0522],
           [-0.7795,  2.4002, -1.2834, -1.4471],
           [-0.416 ,  2.6304, -1.3402, -1.3154],
           [-1.143 ,  0.0982, -1.2834, -1.3154],
           [-1.0218,  0.3284, -1.4539, -1.3154],
           [-0.416 ,  1.019 , -1.3971, -1.3154],
           [-1.143 ,  1.2492, -1.3402, -1.4471],
           [-1.7489, -0.132 , -1.3971, -1.3154],
           [-0.9007,  0.7888, -1.2834, -1.3154],
           [-1.0218,  1.019 , -1.3971, -1.1838],
           [-1.6277, -1.7434, -1.3971, -1.1838],
           [-1.7489,  0.3284, -1.3971, -1.3154],
           [-1.0218,  1.019 , -1.2266, -0.7889],
           [-0.9007,  1.7096, -1.056 , -1.0522],
           [-1.2642, -0.132 , -1.3402, -1.1838],
           [-0.9007,  1.7096, -1.2266, -1.3154],
           [-1.5065,  0.3284, -1.3402, -1.3154],
           [-0.6583,  1.4794, -1.2834, -1.3154],
           [-1.0218,  0.5586, -1.3402, -1.3154],
           [ 1.4015,  0.3284,  0.5354,  0.2641],
           [ 0.6745,  0.3284,  0.4217,  0.3958],
           [ 1.2803,  0.0982,  0.6491,  0.3958],
           [-0.416 , -1.7434,  0.1375,  0.1325],
           [ 0.7957, -0.5924,  0.4786,  0.3958],
           [-0.1737, -0.5924,  0.4217,  0.1325],
           [ 0.5533,  0.5586,  0.5354,  0.5274],
           [-1.143 , -1.5132, -0.2603, -0.2624],
           [ 0.9168, -0.3622,  0.4786,  0.1325],
           [-0.7795, -0.8226,  0.0807,  0.2641],
           [-1.0218, -2.4339, -0.1466, -0.2624],
           [ 0.0687, -0.132 ,  0.2512,  0.3958],
           [ 0.1898, -1.9736,  0.1375, -0.2624],
           [ 0.311 , -0.3622,  0.5354,  0.2641],
           [-0.2948, -0.3622, -0.0898,  0.1325],
           [ 1.038 ,  0.0982,  0.3649,  0.2641],
           [-0.2948, -0.132 ,  0.4217,  0.3958],
           [-0.0525, -0.8226,  0.1944, -0.2624],
           [ 0.4322, -1.9736,  0.4217,  0.3958],
           [-0.2948, -1.283 ,  0.0807, -0.1308],
           [ 0.0687,  0.3284,  0.5922,  0.7907],
           [ 0.311 , -0.5924,  0.1375,  0.1325],
           [ 0.5533, -1.283 ,  0.6491,  0.3958],
           [ 0.311 , -0.5924,  0.5354,  0.0009],
           [ 0.6745, -0.3622,  0.3081,  0.1325],
           [ 0.9168, -0.132 ,  0.3649,  0.2641],
           [ 1.1592, -0.5924,  0.5922,  0.2641],
           [ 1.038 , -0.132 ,  0.7059,  0.659 ],
           [ 0.1898, -0.3622,  0.4217,  0.3958],
           [-0.1737, -1.0528, -0.1466, -0.2624],
           [-0.416 , -1.5132,  0.0239, -0.1308],
           [-0.416 , -1.5132, -0.033 , -0.2624],
           [-0.0525, -0.8226,  0.0807,  0.0009],
           [ 0.1898, -0.8226,  0.7628,  0.5274],
           [-0.5372, -0.132 ,  0.4217,  0.3958],
           [ 0.1898,  0.7888,  0.4217,  0.5274],
           [ 1.038 ,  0.0982,  0.5354,  0.3958],
           [ 0.5533, -1.7434,  0.3649,  0.1325],
           [-0.2948, -0.132 ,  0.1944,  0.1325],
           [-0.416 , -1.283 ,  0.1375,  0.1325],
           [-0.416 , -1.0528,  0.3649,  0.0009],
           [ 0.311 , -0.132 ,  0.4786,  0.2641],
           [-0.0525, -1.0528,  0.1375,  0.0009],
           [-1.0218, -1.7434, -0.2603, -0.2624],
           [-0.2948, -0.8226,  0.2512,  0.1325],
           [-0.1737, -0.132 ,  0.2512,  0.0009],
           [-0.1737, -0.3622,  0.2512,  0.1325],
           [ 0.4322, -0.3622,  0.3081,  0.1325],
           [-0.9007, -1.283 , -0.4308, -0.1308],
           [-0.1737, -0.5924,  0.1944,  0.1325],
           [ 0.5533,  0.5586,  1.2743,  1.7121],
           [-0.0525, -0.8226,  0.7628,  0.9223],
           [ 1.5227, -0.132 ,  1.2175,  1.1856],
           [ 0.5533, -0.3622,  1.0469,  0.7907],
           [ 0.7957, -0.132 ,  1.1606,  1.3172],
           [ 2.1285, -0.132 ,  1.6153,  1.1856],
           [-1.143 , -1.283 ,  0.4217,  0.659 ],
           [ 1.765 , -0.3622,  1.4448,  0.7907],
           [ 1.038 , -1.283 ,  1.1606,  0.7907],
           [ 1.6438,  1.2492,  1.3311,  1.7121],
           [ 0.7957,  0.3284,  0.7628,  1.0539],
           [ 0.6745, -0.8226,  0.8764,  0.9223],
           [ 1.1592, -0.132 ,  0.9901,  1.1856],
           [-0.1737, -1.283 ,  0.7059,  1.0539],
           [-0.0525, -0.5924,  0.7628,  1.5805],
           [ 0.6745,  0.3284,  0.8764,  1.4488],
           [ 0.7957, -0.132 ,  0.9901,  0.7907],
           [ 2.2497,  1.7096,  1.6722,  1.3172],
           [ 2.2497, -1.0528,  1.7858,  1.4488],
           [ 0.1898, -1.9736,  0.7059,  0.3958],
           [ 1.2803,  0.3284,  1.1038,  1.4488],
           [-0.2948, -0.5924,  0.6491,  1.0539],
           [ 2.2497, -0.5924,  1.6722,  1.0539],
           [ 0.5533, -0.8226,  0.6491,  0.7907],
           [ 1.038 ,  0.5586,  1.1038,  1.1856],
           [ 1.6438,  0.3284,  1.2743,  0.7907],
           [ 0.4322, -0.5924,  0.5922,  0.7907],
           [ 0.311 , -0.132 ,  0.6491,  0.7907],
           [ 0.6745, -0.5924,  1.0469,  1.1856],
           [ 1.6438, -0.132 ,  1.1606,  0.5274],
           [ 1.8862, -0.5924,  1.3311,  0.9223],
           [ 2.492 ,  1.7096,  1.5016,  1.0539],
           [ 0.6745, -0.5924,  1.0469,  1.3172],
           [ 0.5533, -0.5924,  0.7628,  0.3958],
           [ 0.311 , -1.0528,  1.0469,  0.2641],
           [ 2.2497, -0.132 ,  1.3311,  1.4488],
           [ 0.5533,  0.7888,  1.0469,  1.5805],
           [ 0.6745,  0.0982,  0.9901,  0.7907],
           [ 0.1898, -0.132 ,  0.5922,  0.7907],
           [ 1.2803,  0.0982,  0.9333,  1.1856],
           [ 1.038 ,  0.0982,  1.0469,  1.5805],
           [ 1.2803,  0.0982,  0.7628,  1.4488],
           [-0.0525, -0.8226,  0.7628,  0.9223],
           [ 1.1592,  0.3284,  1.2175,  1.4488],
           [ 1.038 ,  0.5586,  1.1038,  1.7121],
           [ 1.038 , -0.132 ,  0.8196,  1.4488],
           [ 0.5533, -1.283 ,  0.7059,  0.9223],
           [ 0.7957, -0.132 ,  0.8196,  1.0539],
           [ 0.4322,  0.7888,  0.9333,  1.4488],
           [ 0.0687, -0.132 ,  0.7628,  0.7907]])

We can also try plot a few two-dimensional projections, with combinations of 2 features at a time:

```python
colorClass = [val.split(',')[-1].replace('\n', '') for val in data[:-1]]
for i in range(len(colorClass)):
    val = colorClass[i]
    if val == 'Iris-setosa':
        colorClass[i] ='r'
    elif val == 'Iris-versicolor':
        colorClass[i] ='b'
    elif val == 'Iris-virginica':
        colorClass[i] ='g'

plt.figure(figsize=(8,8))
for i in range(0,4):
    for j in range(0,4):
        plt.subplot(4, 4, i * 4 + j + 1)
        plt.scatter(iris_HD[:,i].tolist(), iris_HD[:,j].tolist(),c = colorClass, edgecolors = "black")
        plt.axis('equal')
        plt.gca().set_aspect('equal')
```

It is not easy to see that this is still a two-dimensional dataset!

However, if we now do PCA on it, you'll see that the last two dimensions do not matter at all:

```python
pca = PCA()
X_HE = pca.fit_transform(iris_HD)
print (X_HE[:10,:])
```

    [[-2.2647  0.48   -0.1277 -0.0242]
     [-2.081  -0.6741 -0.2346 -0.103 ]
     [-2.3642 -0.3419  0.0442 -0.0284]
     [-2.2994 -0.5974  0.0913  0.066 ]
     [-2.3898  0.6468  0.0157  0.0359]
     [-2.0756  1.4892  0.027  -0.0066]
     [-2.444   0.0476  0.3355  0.0368]
     [-2.2328  0.2231 -0.0887  0.0246]
     [-2.3346 -1.1153  0.1451  0.0269]
     [-2.1843 -0.469  -0.2538  0.0399]]

By looking at the data after PCA, it is easy to see the value of last two dimension, especially the last one, is pretty small such that the data can be considered as **still only two-dimensional**. To prove this we can use the code `PCA(0.95)` to told PCA choose the least number of PCA components such that 95% of the data can be kept.

Lets give a try on it!

```python
pca = PCA(0.95)
X_95 = pca.fit_transform(iris_HD)
print (X_95[:10,:])
```

    [[-2.2647  0.48  ]
     [-2.081  -0.6741]
     [-2.3642 -0.3419]
     [-2.2994 -0.5974]
     [-2.3898  0.6468]
     [-2.0756  1.4892]
     [-2.444   0.0476]
     [-2.2328  0.2231]
     [-2.3346 -1.1153]
     [-2.1843 -0.469 ]]

We can see that PCA eliminate ** the last two dimension** cause they are redundant under our requirment. Let's plot the two dimension

```python
plt.figure(figsize=(4,4))
plt.scatter(X_HE[:,0], X_HE[:,1], c = colorClass, edgecolor = "black")
plt.axis('equal')
plt.gca().set_aspect('equal')
```

We can have a look on the relationship between each dimention from following plots.

```python
plt.figure(figsize=(8,8))
for i in range(4):
    for j in range(4):
        plt.subplot(4, 4, i * 4 + j + 1)
        plt.scatter(X_HE[:,i], X_HE[:,j], c = colorClass, edgecolor = "black")
        plt.gca().set_xlim(-40,40)
        plt.gca().set_ylim(-40,40)
        plt.axis('equal')
        plt.gca().set_aspect('equal')
```

It is easy to see that the correlation between other dimensions (other than first two) was ambiguous and highly concentrated in either horizontal or vertical line. This fact suggests that there are large difference between the dimension we select so that **the weak dimension cant change too much on the shape of graph**.

## Dimension Reduction with PCA

We can see that there are actually only two dimensions in the dataset.

Let's throw away even more data -- the second dimension -- and reconstruct the original data in `D`.

```python
pca = PCA(1) # only keep one dimension!
X_E = pca.fit_transform(iris_HD)
print (X_E[:10,:])
```

    [[-2.2647]
     [-2.081 ]
     [-2.3642]
     [-2.2994]
     [-2.3898]
     [-2.0756]
     [-2.444 ]
     [-2.2328]
     [-2.3346]
     [-2.1843]]

Now lets plot the reconstructed data and compare to the original data D. We plot the original data in red, and the reconstruction with only one dimension in blue:

```python
X_reconstructed = pca.inverse_transform(X_E)
plt.figure(figsize=(8,8))
for i in range(4):
    for j in range(4):
        plt.subplot(4, 4, i * 4 + j + 1)
        plt.scatter(iris_HD[:,i].tolist(), iris_HD[:,j].tolist(),c=colorClass, edgecolor = "black")
        plt.scatter(X_reconstructed[:,i], X_reconstructed[:,j],c='purple', edgecolor = "black")
        plt.axis('equal')
```

## Homework
- - - - - - --- --- - - - -- -- - -
1) Do the PCA reduction on the ramdon 6-dimension data and plot it out.

2) Explan what PCA does on your data.

*The code for data are given.

```python
pca=PCA(6)
DATA = np.dot(X,np.random.uniform(0.2,3,(2,6))*(np.random.randint(0,2,(2,6))*2-1))
DATA
```

    array([[ -0.9461,   6.3453,   3.166 ,  -2.2627,   0.4518,  -0.4504],
           [  0.3008,   4.8023,   2.0398,  -1.4577,  -0.4948,   0.8638],
           [ -3.8406,   2.1131,   2.2898,  -1.6369,   3.0516,  -4.3269],
           ...,
           [-11.5245,   5.4092,   6.4547,  -4.6143,   9.2048, -13.0821],
           [ -4.0408,   7.2811,   4.6685,  -3.3368,   2.9501,  -4.0179],
           [ -9.454 ,  12.6343,   8.9567,  -6.4021,   7.129 ,  -9.8656]])

```python
## Answer:

pca=PCA(6)
DATA = np.dot(X,np.random.uniform(0.2,3,(2,6))*(np.random.randint(0,2,(2,6))*2-1))
DATA2 = pca.fit_transform(DATA)

plt.figure(figsize=(4,4))
plt.scatter(DATA2[:,0], DATA2[:,1], c = "b", edgecolor = "black")
plt.axis('equal')
plt.gca().set_aspect('equal')
```


# Chapter 5
____
### Would you rather lose an arm or a leg?

Statisticians can be a sour bunch. Instead of considering their winnings, they only measure how much they have lost. In fact, they consider their wins as *negative losses*. But what's interesting is *how they measure their losses.*

For example, consider the following example:

>   A meteorologist is predicting the probability of a possible hurricane striking his city. He estimates, with 95% confidence, that the probability of it *not* striking is between 99% - 100%. He is very happy with his precision and advises the city that a major evacuation is unnecessary. Unfortunately, the hurricane does strike and the city is flooded.

This stylized example shows the flaw in using a pure accuracy metric to measure outcomes. Using a measure that emphasizes estimation accuracy, while an appealing and *objective* thing to do, misses the point of why you are even performing the statistical inference in the first place: results of inference. The author Nassim Taleb of *The Black Swan* and *Antifragility* stresses the importance of the *payoffs* of decisions, *not the accuracy*. Taleb distills this quite succinctly: "I would rather be vaguely right than very wrong."

## Loss Functions

We introduce what statisticians and decision theorists call *loss functions*. A loss function is a function of the true parameter, and an estimate of that parameter

$$ L( \theta, \hat{\theta} ) = f( \theta, \hat{\theta} )$$

The important point of loss functions is that it measures how *bad* our current estimate is: the larger the loss, the worse the estimate is according to the loss function. A simple, and very common, example of a loss function is the *squared-error loss*:

$$ L( \theta, \hat{\theta} ) = ( \theta -  \hat{\theta} )^2$$

The squared-error loss function is used in estimators like linear regression, UMVUEs and many areas of machine learning. We can also consider an asymmetric squared-error loss function, something like:

$$ L( \theta, \hat{\theta} ) = \begin{cases} ( \theta -  \hat{\theta} )^2 & \hat{\theta} \lt \theta \\\\ c( \theta -  \hat{\theta} )^2 & \hat{\theta} \ge \theta, \;\; 0\lt c \lt 1 \end{cases}$$

which represents that estimating a value larger than the true estimate is preferable to estimating a value below. A situation where this might be useful is in estimating web traffic for the next month, where an over-estimated outlook is preferred so as to avoid an underallocation of server resources.

A negative property about the squared-error loss is that it puts a disproportionate emphasis on large outliers. This is because the loss increases quadratically, and not linearly, as the estimate moves away. That is, the penalty of being three units away is much less than being five units away, but the penalty is not much greater than being one unit away, though in both cases the magnitude of difference is the same:

$$ \frac{1^2}{3^2} \lt \frac{3^2}{5^2}, \;\; \text{although} \;\; 3-1 = 5-3 $$

This loss function imposes that large errors are *very* bad. A more *robust* loss function that increases linearly with the difference is the *absolute-loss*

$$ L( \theta, \hat{\theta} ) = | \theta -  \hat{\theta} | $$

Other popular loss functions include:

-  $ L( \theta, \hat{\theta} ) = \mathbb{1}_{ \hat{\theta} \neq \theta } $ is the zero-one loss often used in machine learning classification algorithms.
-  $ L( \theta, \hat{\theta} ) = -\hat{\theta}\log( \theta ) - (1-\hat{ \theta})\log( 1 - \theta ), \; \; \hat{\theta} \in {0,1}, \; \theta \in [0,1]$, called the *log-loss*, also used in machine learning.

Historically, loss functions have been motivated from 1) mathematical convenience, and 2) they are robust to application, i.e., they are objective measures of loss. The first reason has really held back the full breadth of loss functions. With computers being agnostic to mathematical convenience, we are free to design our own loss functions, which we take full advantage of later in this Chapter.

With respect to the second point, the above loss functions are indeed objective, in that they are most often a function of the difference between estimate and true parameter, independent of signage or payoff of choosing that estimate. This last point, its independence of payoff, causes quite pathological results though. Consider our hurricane example above: the statistician equivalently predicted that the probability of the hurricane striking was between 0% to 1%. But if he had ignored being precise and instead focused on outcomes (99% chance of no flood, 1% chance of flood), he might have advised differently.

By shifting our focus from trying to be incredibly precise about parameter estimation to focusing on the outcomes of our parameter estimation, we can customize our estimates to be optimized for our application. This requires us to design new loss functions that reflect our goals and outcomes. Some examples of more interesting loss functions:

- $ L( \theta, \hat{\theta} ) = \frac{ | \theta - \hat{\theta} | }{ \theta(1-\theta) }, \; \; \hat{\theta}, \theta \in [0,1] $ emphasizes an estimate closer to 0 or 1 since if the true value $\theta$ is near 0 or 1, the loss will be *very* large unless $\hat{\theta}$ is similarly close to 0 or 1.
This loss function might be used by a political pundit who's job requires him or her to give confident "Yes/No" answers. This loss reflects that if the true parameter is close to 1 (for example, if a political outcome is very likely to occur), he or she would want to strongly agree as to not look like a skeptic.

-  $L( \theta, \hat{\theta} ) =  1 - \exp \left( -(\theta -  \hat{\theta} )^2 \right) $ is bounded between 0 and 1 and reflects that the user is indifferent to sufficiently-far-away estimates. It is similar to the zero-one loss above, but not quite as penalizing to estimates that are close to the true parameter.
-  Complicated non-linear loss functions can programmed:

        def loss(true_value, estimate):
            if estimate*true_value > 0:
                return abs(estimate - true_value)
            else:
               return abs(estimate)*(estimate - true_value)**2

-  Another example is from the book *The Signal and The Noise*. Weather forecasters have a interesting loss function for their predictions. [2]

>  People notice one type of mistake — the failure to predict rain — more than other, false alarms. If it rains when it isn't supposed to, they curse the weatherman for ruining their picnic, whereas an unexpectedly sunny day is taken as a serendipitous bonus.

>  [The Weather Channel's bias] is limited to slightly exaggerating the probability of rain when it is unlikely to occur — saying there is a 20 percent change when they know it is really a 5 or 10 percent chance — covering their butts in the case of an unexpected sprinkle.

As you can see, loss functions can be used for good and evil: with great power, comes great — well you know.

##  Loss functions in the real world

So far we have been under the unrealistic assumption that we know the true parameter. Of course if we knew the true parameter, bothering to guess an estimate is pointless. Hence a loss function is really only practical when the true parameter is unknown.

In Bayesian inference, we have a mindset that the unknown parameters are really random variables with prior and posterior distributions. Concerning the posterior distribution, a value drawn from it is a *possible* realization of what the true parameter could be. Given that realization, we can compute a loss associated with an estimate. As we have a whole distribution of what the unknown parameter could be (the posterior), we should be more interested in computing the *expected loss* given an estimate. This expected loss is a better estimate of the true loss than comparing the given loss from only a single sample from the posterior.

First it will be useful to explain a *Bayesian point estimate*. The systems and machinery present in the modern world are not built to accept posterior distributions as input. It is also rude to hand someone over a distribution when all the asked for was an estimate.  In the course of an individual's day, when faced with uncertainty we still act by distilling our uncertainty down to a single action. Similarly, we need to distill our posterior distribution down to a single value (or vector in the multivariate case). If the value is chosen intelligently, we can avoid the flaw of frequentist methodologies that mask the uncertainty and provide a more informative result.The value chosen, if from a Bayesian posterior, is a Bayesian point estimate.

Suppose $P(\theta | X)$ is the posterior distribution of $\theta$ after observing data $X$, then the following function is understandable as the *expected loss of choosing estimate $\hat{\theta}$ to estimate $\theta$*:

$$ l(\hat{\theta} ) = E_{\theta}\left[ \; L(\theta, \hat{\theta}) \; \right] $$

This is also known as the *risk* of estimate $\hat{\theta}$. The subscript $\theta$ under the expectation symbol is used to denote that $\theta$ is the unknown (random) variable in the expectation, something that at first can be difficult to consider.

We spent all of last chapter discussing how to approximate expected values. Given $N$ samples $\theta_i,\; i=1,...,N$ from the posterior distribution, and a loss function $L$, we can approximate the expected loss of using estimate $\hat{\theta}$ by the Law of Large Numbers:

$$\frac{1}{N} \sum_{i=1}^N \;L(\theta_i, \hat{\theta} ) \approx E_{\theta}\left[ \; L(\theta, \hat{\theta}) \; \right]  = l(\hat{\theta} ) $$

Notice that measuring your loss via an *expected value* uses more information from the distribution than the MAP estimate which, if you recall, will only find the maximum value of the distribution and ignore the shape of the distribution. Ignoring information can over-expose yourself to tail risks, like the unlikely hurricane, and leaves your estimate ignorant of how ignorant you really are about the parameter.

Similarly, compare this with frequentist methods, that traditionally only aim to minimize the error, and do not consider the *loss associated with the result of that error*. Compound this with the fact that frequentist methods are almost guaranteed to never be absolutely accurate. Bayesian point estimates fix this by planning ahead: your estimate is going to be wrong, you might as well err on the right side of wrong.

##### Example: Optimizing for the *Showcase* on *The Price is Right*

Bless you if you are ever chosen as a contestant on the Price is Right, for here we will show you how to optimize your final price on the *Showcase*. For those who forget the rules:

1. Two contestants compete in *The Showcase*.
2. Each contestant is shown a unique suite of prizes.
3. After the viewing, the contestants are asked to bid on the price for their unique suite of prizes.
4. If a bid price is over the actual price, the bid's owner is disqualified from winning.
5. If a bid price is under the true price by less than $250, the winner is awarded both prizes.

The difficulty in the game is balancing your uncertainty in the prices, keeping your bid low enough so as to not bid over, and trying to bid close to the price.

Suppose we have recorded the *Showcases* from previous *The Price is Right* episodes and have *prior* beliefs about what distribution the true price follows. For simplicity, suppose it follows a Normal:

$$\text{True Price} \sim \text{Normal}(\mu_p, \sigma_p )$$

In a later chapter, we will actually use *real Price is Right Showcase data* to form the historical prior, but this requires some advanced PyMC use so we will not use it here. For now, we will assume $\mu_p = 35 000$ and $\sigma_p = 7500$.

We need a model of how we should be playing the *Showcase*. For each prize in the prize suite, we have an idea of what it might cost, but this guess could differ significantly from the true price. (Couple this with increased pressure being onstage and you can see why some bids are so wildly off). Let's suppose your beliefs about the prices of prizes also follow Normal distributions:

$$ \text{Prize}_i \sim \text{Normal}(\mu_i, \sigma_i ),\;\; i=1,2$$

This is really why Bayesian analysis is great: we can specify what we think a fair price is through the $\mu_i$ parameter, and express uncertainty of our guess in the $\sigma_i$ parameter.

We'll assume two prizes per suite for brevity, but this can be extended to any number.
The true price of the prize suite is then given by $\text{Prize}_1 + \text{Prize}_2 + \epsilon$,
where $\epsilon$ is some error term.

We are interested in the updated $\text{True Price}$ given we have observed both prizes and have belief distributions about them. We can perform this using PyMC.

Lets make some values concrete. Suppose there are two prizes in the observed prize suite:

1. A trip to wonderful Toronto, Canada!
2. A lovely new snowblower!

We have some guesses about the true prices of these objects, but we are also pretty uncertain about them. I can express this uncertainty through the parameters of the Normals:

\begin{align}
& \text{snowblower} \sim \text{Normal}(3 000, 500 )\\\\
& \text{Toronto} \sim \text{Normal}(12 000, 3000 )\\\\
\end{align}

For example, I believe that the true price of the trip to Toronto is 12 000 dollars, and that there is a 68.2% chance the price falls 1 standard deviation away from this, i.e. my confidence is that there is a 68.2% chance the trip is in [9 000, 15 000].

We can create some PyMC code to perform inference on the true price of the suite.

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

figsize(12.5, 9)

norm_pdf = stats.norm.pdf

plt.subplot(311)
x = np.linspace(0, 60000, 200)
sp1 = plt.fill_between(x, 0, norm_pdf(x, 35000, 7500),
                       color="#348ABD", lw=3, alpha=0.6,
                       label="historical total prices")
p1 = plt.Rectangle((0, 0), 1, 1, fc=sp1.get_facecolor()[0])
plt.legend([p1], [sp1.get_label()])

plt.subplot(312)
x = np.linspace(0, 10000, 200)
sp2 = plt.fill_between(x, 0, norm_pdf(x, 3000, 500),
                       color="#A60628", lw=3, alpha=0.6,
                       label="snowblower price guess")

p2 = plt.Rectangle((0, 0), 1, 1, fc=sp2.get_facecolor()[0])
plt.legend([p2], [sp2.get_label()])

plt.subplot(313)
x = np.linspace(0, 25000, 200)
sp3 = plt.fill_between(x, 0, norm_pdf(x, 12000, 3000),
                       color="#7A68A6", lw=3, alpha=0.6,
                       label="Trip price guess")
plt.autoscale(tight=True)
p3 = plt.Rectangle((0, 0), 1, 1, fc=sp3.get_facecolor()[0])
plt.legend([p3], [sp3.get_label()]);
```

```
import pymc as pm

data_mu = [3e3, 12e3]

data_std = [5e2, 3e3]

mu_prior = 35e3
std_prior = 75e2

true_price = pm.Normal("true_price", mu_prior, 1.0 / std_prior ** 2)

prize_1 = pm.Normal("first_prize", data_mu[0], 1.0 / data_std[0] ** 2)
prize_2 = pm.Normal("second_prize", data_mu[1], 1.0 / data_std[1] ** 2)
price_estimate = prize_1 + prize_2

@pm.potential
def error(true_price=true_price, price_estimate=price_estimate):
        return pm.normal_like(true_price, price_estimate, 1 / (3e3) ** 2)

mcmc = pm.MCMC([true_price, prize_1, prize_2, price_estimate, error])
mcmc.sample(50000, 10000)

price_trace = mcmc.trace("true_price")[:]
```

    [****************100%******************]  50000 of 50000 complete

```
figsize(12.5, 4)

import scipy.stats as stats

x = np.linspace(5000, 40000)
plt.plot(x, stats.norm.pdf(x, 35000, 7500), c="k", lw=2,
         label="prior dist. of suite price")

_hist = plt.hist(price_trace, bins=35, normed=True, histtype="stepfilled")
plt.title("Posterior of the true price estimate")
plt.vlines(mu_prior, 0, 1.1 * np.max(_hist[0]), label="prior's mean",
           linestyles="--")
plt.vlines(price_trace.mean(), 0, 1.1 * np.max(_hist[0]),
           label="posterior's mean", linestyles="-.")
plt.legend(loc="upper left")
```

Notice that because of our two observed prizes and subsequent guesses (including uncertainty about those guesses), we shifted our mean price estimate down about $15 000 dollars from the previous mean price.

A frequentist, seeing the two prizes and having the same beliefs about their prices, would bid $\mu_1 + \mu_2 = 35000$, regardless of any uncertainty. Meanwhile, the *naive Bayesian* would simply pick the mean of the posterior distribution. But we have more information about our eventual outcomes; we should incorporate this into our bid. We will use the loss function above to find the *best* bid (*best* according to our loss).

What might a contestant's loss function look like? I would think it would look something like:

    def showcase_loss(guess, true_price, risk=80000):
        if true_price < guess:
            return risk
        elif abs(true_price - guess) <= 250:
            return -2*np.abs(true_price)
        else:
            return np.abs(true_price - guess - 250)

where `risk` is a parameter that defines of how bad it is if your guess is over the true price. A lower `risk` means that you are more comfortable with the idea of going over. If we do bid under and the difference is less than $250, we receive both prizes (modeled here as receiving twice the original prize). Otherwise, when we bid under the `true_price` we want to be as close as possible, hence the `else` loss is a increasing function of the distance between the guess and true price.

For every possible bid, we calculate the *expected loss* associated with that bid. We vary the `risk` parameter to see how it affects our loss:

```
figsize(12.5, 7)
# numpy friendly showdown_loss

def showdown_loss(guess, true_price, risk=80000):
        loss = np.zeros_like(true_price)
        ix = true_price < guess
        loss[~ix] = np.abs(guess - true_price[~ix])
        close_mask = [abs(true_price - guess) <= 250]
        loss[close_mask] = -2 * true_price[close_mask]
        loss[ix] = risk
        return loss

guesses = np.linspace(5000, 50000, 70)
risks = np.linspace(30000, 150000, 6)
expected_loss = lambda guess, risk: \
    showdown_loss(guess, price_trace, risk).mean()

for _p in risks:
    results = [expected_loss(_g, _p) for _g in guesses]
    plt.plot(guesses, results, label="%d" % _p)

plt.title("Expected loss of different guesses, \nvarious risk-levels of \
overestimating")
plt.legend(loc="upper left", title="Risk parameter")
plt.xlabel("price bid")
plt.ylabel("expected loss")
plt.xlim(5000, 30000);
```

### Minimizing our losses

It would be wise to choose the estimate that minimizes our expected loss. This corresponds to the minimum point on each of the curves above. More formally, we would like to minimize our expected loss by finding the solution to

$$ \text{arg} \min_{\hat{\theta}} \;\;E_{\theta}\left[ \; L(\theta, \hat{\theta}) \; \right] $$

The minimum of the expected loss is called the *Bayes action*. We can solve for the Bayes action using Scipy's optimization routines. The function in `fmin` in `scipy.optimize` module uses an intelligent search to find a minimum (not necessarily a *global* minimum) of any uni- or multivariate function. For most purposes, `fmin` will provide you with a good answer.

We'll compute the minimum loss for the *Showcase* example above:

```
import scipy.optimize as sop

ax = plt.subplot(111)

for _p in risks:
    _color = ax._get_lines.color_cycle.next()
    _min_results = sop.fmin(expected_loss, 15000, args=(_p,), disp=False)
    _results = [expected_loss(_g, _p) for _g in guesses]
    plt.plot(guesses, _results, color=_color)
    plt.scatter(_min_results, 0, s=60,
                color=_color, label="%d" % _p)
    plt.vlines(_min_results, 0, 120000, color=_color, linestyles="--")
    print "minimum at risk %d: %.2f" % (_p, _min_results)

plt.title("Expected loss & Bayes actions of different guesses, \n \
various risk-levels of overestimating")
plt.legend(loc="upper left", scatterpoints=1, title="Bayes action at risk:")
plt.xlabel("price guess")
plt.ylabel("expected loss")
plt.xlim(7000, 30000)
plt.ylim(-1000, 80000)
```

As intuition suggests, as we decrease the risk threshold (care about overbidding less), we increase our bid, willing to edge closer to the true price. It is interesting how far away our optimized loss is from the posterior mean, which was about 20 000.

Suffice to say, in higher dimensions being able to eyeball the minimum expected loss is impossible. Hence why we require use of Scipy's `fmin` function.

______

### Shortcuts

For some loss functions, the Bayes action is known in closed form. We list some of them below:

-  If using the mean-squared loss, the Bayes action is the mean of the posterior distribution, i.e. the value
$$ E_{\theta}\left[ \theta \right] $$

>  minimizes $E_{\theta}\left[ \; (\theta - \hat{\theta})^2 \; \right]$. Computationally this requires us to calculate the average of the posterior samples [See chapter 4 on The Law of Large Numbers]

-  Whereas the *median* of the posterior distribution minimizes the expected absolute-loss. The sample median of the posterior samples is an appropriate and very accurate approximation to the true median.

-  In fact, it is possible to show that the MAP estimate is the solution to using a loss function that shrinks to the zero-one loss.

Maybe it is clear now why the first-introduced loss functions are used most often in the mathematics of Bayesian inference: no complicated optimizations are necessary. Luckily, we have machines to do the complications for us.

##  Machine Learning via Bayesian Methods

Whereas frequentist methods strive to achieve the best precision about all possible parameters, machine learning cares to achieve the best *prediction* among all possible parameters. Of course, one way to achieve accurate predictions is to aim for accurate predictions, but often your prediction measure and what frequentist methods are optimizing for are very different.

For example, least-squares linear regression is the most simple active machine learning algorithm. I say active as it engages in some learning, whereas predicting the sample mean is technically *simpler*, but is learning very little if anything. The loss that determines the coefficients of the regressors is a squared-error loss. On the other hand, if your prediction loss function (or score function, which is the negative loss) is not a squared-error, like AUC, ROC, precision, etc., your least-squares line will not be optimal for the prediction loss function. This can lead to prediction results that are suboptimal.

Finding Bayes actions is equivalent to finding parameters that optimize *not parameter accuracy* but an arbitrary performance measure, however we wish to define performance (loss functions, AUC, ROC, precision/recall etc.).

The next two examples demonstrate these ideas. The first example is a linear model where we can choose to predict using the least-squares loss or a novel, outcome-sensitive loss.

The second example is adapted from a Kaggle data science project. The loss function associated with our predictions is incredibly complicated.

##### Example: Financial prediction

Suppose the future return of a stock price is very small, say 0.01 (or 1%). We have a model that predicts the stock's future price, and our profit and loss is directly tied to us acting on the prediction.  How should we measure the loss associated with the model's predictions, and subsequent future predictions? A squared-error loss is agnostic to the signage and would penalize a prediction of -0.01 equally as bad a prediction of 0.03:

$$ (0.01 - (-0.01))^2 = (0.01 - 0.03)^2 = 0.004$$

If you had made a bet based on your model's prediction, you would have earned money with a prediction of 0.03, and lost money with a prediction of -0.01, yet our loss did not capture this. We need a better loss that takes into account the *sign* of the prediction and true value. We design a new loss that is better for financial applications below:

```
figsize(12.5, 4)

def stock_loss(true_return, yhat, alpha=100.):
    if true_return * yhat < 0:
        # opposite signs, not good
        return alpha * yhat ** 2 - np.sign(true_return) * yhat \
            + abs(true_return)
    else:
        return abs(true_return - yhat)

true_value = .05
pred = np.linspace(-.04, .12, 75)

plt.plot(pred, [stock_loss(true_value, _p) for _p in pred],
         label="Loss associated with\n prediction if true value = 0.05", lw=3)
plt.vlines(0, 0, .25, linestyles="--")

plt.xlabel("prediction")
plt.ylabel("loss")
plt.xlim(-0.04, .12)
plt.ylim(0, 0.25)

true_value = -.02
plt.plot(pred, [stock_loss(true_value, _p) for _p in pred], alpha=0.6,
         label="Loss associated with\n prediction if true value = -0.02", lw=3)
plt.legend()
plt.title("Stock returns loss if true value = 0.05, -0.02");
```

Note the change in the shape of the loss as the prediction crosses zero. This loss reflects that the user really does not want to guess the wrong sign, especially be wrong *and* a large magnitude.

Why would the user care about the magnitude? Why is the loss not 0 for predicting the correct sign? Surely, if the return is 0.01 and we bet millions we will still be (very) happy.

Financial institutions treat downside risk, as in predicting a lot on the wrong side, and upside risk, as in predicting a lot on the right side, similarly. Both are seen as risky behaviour and discouraged. Hence why we have an increasing loss as we move further away from the true price. (With less extreme loss in the direction of the correct sign.)

We will perform a regression on a trading signal that we believe predicts future returns well. Our dataset is artificial, as most financial data is not even close to linear. Below, we plot the data along with the least-squares line.

```
# Code to create artificial data
N = 100
X = 0.025 * np.random.randn(N)
Y = 0.5 * X + 0.01 * np.random.randn(N)

ls_coef_ = np.cov(X, Y)[0, 1] / np.var(X)
ls_intercept = Y.mean() - ls_coef_ * X.mean()

plt.scatter(X, Y, c="k")
plt.xlabel("trading signal")
plt.ylabel("returns")
plt.title("Empirical returns vs trading signal")
plt.plot(X, ls_coef_ * X + ls_intercept, label="Least-squares line")
plt.xlim(X.min(), X.max())
plt.ylim(Y.min(), Y.max())
plt.legend(loc="upper left");
```

We perform a simple Bayesian linear regression on this dataset. We look for a model like:

$$ R = \alpha + \beta x + \epsilon$$

where $\alpha, \beta$ are our unknown parameters and $\epsilon \sim \text{Normal}(0, 1/\tau)$. The most common priors on $\beta$ and $\alpha$ are Normal priors. We will also assign a prior on $\tau$, so that $\sigma = 1/\sqrt{\tau}$ is uniform over 0 to 100 (equivalently then $\tau = 1/\text{Uniform}(0, 100)^2$).

```
import pymc as pm
from pymc.Matplot import plot as mcplot

std = pm.Uniform("std", 0, 100, trace=False)  # this needs to be explained.

@pm.deterministic
def prec(U=std):
    return 1.0 / (U) ** 2

beta = pm.Normal("beta", 0, 0.0001)
alpha = pm.Normal("alpha", 0, 0.0001)

@pm.deterministic
def mean(X=X, alpha=alpha, beta=beta):
    return alpha + beta * X

obs = pm.Normal("obs", mean, prec, value=Y, observed=True)
mcmc = pm.MCMC([obs, beta, alpha, std, prec])

mcmc.sample(100000, 80000)
mcplot(mcmc)
```

It appears the MCMC has converged so we may continue.

For a specific trading signal, call it $x$, the distribution of possible returns has the form:

$$R_i(x) =  \alpha_i + \beta_ix + \epsilon $$

where $\epsilon \sim \text{Normal}(0, 1/\tau_i) $ and $i$ indexes our posterior samples. We wish to find the solution to

$$ \arg \min_{r} \;\;E_{R(x)}\left[ \; L(R(x), r) \; \right] $$

according to the loss given above. This $r$ is our Bayes action for trading signal $x$. Below we plot the Bayes action over different trading signals. What do you notice?

```
figsize(12.5, 6)
from scipy.optimize import fmin

def stock_loss(price, pred, coef=500):
    """vectorized for numpy"""
    sol = np.zeros_like(price)
    ix = price * pred < 0
    sol[ix] = coef * pred ** 2 - np.sign(price[ix]) * pred + abs(price[ix])
    sol[~ix] = abs(price[~ix] - pred)
    return sol

tau_samples = mcmc.trace("prec")[:]
alpha_samples = mcmc.trace("alpha")[:]
beta_samples = mcmc.trace("beta")[:]

N = tau_samples.shape[0]

noise = 1. / np.sqrt(tau_samples) * np.random.randn(N)

possible_outcomes = lambda signal: alpha_samples + beta_samples * signal \
    + noise

opt_predictions = np.zeros(50)
trading_signals = np.linspace(X.min(), X.max(), 50)
for i, _signal in enumerate(trading_signals):
    _possible_outcomes = possible_outcomes(_signal)
    tomin = lambda pred: stock_loss(_possible_outcomes, pred).mean()
    opt_predictions[i] = fmin(tomin, 0, disp=False)

plt.xlabel("trading signal")
plt.ylabel("prediction")
plt.title("Least-squares prediction vs. Bayes action prediction")
plt.plot(X, ls_coef_ * X + ls_intercept, label="Least-squares prediction")
plt.xlim(X.min(), X.max())
plt.plot(trading_signals, opt_predictions, label="Bayes action prediction")
plt.legend(loc="upper left");
```

What is interesting about the above graph is that when the signal is near 0, and many of the possible  returns outcomes are possibly both positive and negative, our best (with respect to our loss) prediction is to predict close to 0, hence *take on no position*. Only when we are very confident do we enter into a position. I call this style of model a *sparse prediction*, where we feel uncomfortable with our uncertainty so choose not to act. (Compare with the least-squares prediction which will rarely, if ever, predict zero).

A good sanity check that our model is still reasonable: as the signal becomes more and more extreme, and we feel more and more confident about the positive/negativeness of returns, our position converges with that of the least-squares line.

The sparse-prediction model is not trying to *fit* the data the best (according to a *squared-error loss* definition of *fit*). That honor would go to the least-squares model. The sparse-prediction model is trying to find the best prediction *with respect to our `stock_loss`-defined loss*. We can turn this reasoning around: the least-squares model is not trying to *predict* the best (according to a *`stock-loss`* definition of *predict*). That honor would go the *sparse prediction* model. The least-squares model is trying to find the best fit of the data *with respect to the squared-error loss*.

##### Example: Kaggle contest on *Observing Dark World*

A personal motivation for learning Bayesian methods was trying to piece together the winning solution to Kaggle's [*Observing Dark Worlds*](http://www.kaggle.com/c/DarkWorlds) contest. From the contest's website:

>There is more to the Universe than meets the eye. Out in the cosmos exists a form of matter that outnumbers the stuff we can see by almost 7 to 1, and we don’t know what it is. What we do know is that it does not emit or absorb light, so we call it Dark Matter. Such a vast amount of aggregated matter does not go unnoticed. In fact we observe that this stuff aggregates and forms massive structures called Dark Matter Halos. Although dark, it warps and bends spacetime such that any light from a background galaxy which passes close to the Dark Matter will have its path altered and changed. This bending causes the galaxy to appear as an ellipse in the sky.

The contest required predictions about where dark matter was likely to be. The winner, [Tim Salimans](http://timsalimans.com/), used Bayesian inference to find the best locations for the halos (interestingly, the second-place winner also used Bayesian inference). With Tim's permission, we provided his solution [1] here:

1. Construct a prior distribution for the halo positions $p(x)$, i.e. formulate our expectations about the halo positions before looking at the data.
2. Construct a probabilistic model for the data (observed ellipticities of the galaxies) given the positions of the dark matter halos: $p(e | x)$.
3. Use Bayes’ rule to get the posterior distribution of the halo positions, i.e. use to the data to guess where the dark matter halos might be.
4. Minimize the expected loss with respect to the posterior distribution over the predictions for the halo positions: $ \hat{x} = \arg \min_{\text{prediction} } E_{p(x|e)}[ L( \text{prediction}, x) ]$ , i.e. tune our predictions to be as good as possible for the given error metric.

The loss function in this problem is very complicated. For the very determined, the loss function is contained in the file DarkWorldsMetric.py in the parent folder. Though I suggest not reading it all, suffice to say the loss function is about 160 lines of code — not something that can be written down in a single mathematical line. The loss function attempts to measure the accuracy of prediction, in a Euclidean distance sense, such that no shift-bias is present. More details can be found on the metric's [main page](http://www.kaggle.com/c/DarkWorlds/details/evaluation).

We will attempt to implement Tim's winning solution using PyMC and our knowledge of loss functions.

### The Data

The dataset is actually 300 separate files, each representing a sky. In each file, or sky, are between 300 and 720 galaxies. Each galaxy has an $x$ and $y$ position associated with it, ranging from 0 to 4200, and measures of ellipticity: $e_1$ and $e_2$. Information about what these measures mean can be found [here](https://www.kaggle.com/c/DarkWorlds/details/an-introduction-to-ellipticity), but for our purposes it does not matter besides for visualization purposes. Thus a typical sky might look like the following:

```
from draw_sky2 import draw_sky

n_sky = 3  # choose a file/sky to examine.
data = np.genfromtxt("data/Train_Skies/Train_Skies/\
Training_Sky%d.csv" % (n_sky),
                      dtype=None,
                      skip_header=1,
                      delimiter=",",
                      usecols=[1, 2, 3, 4])
print "Data on galaxies in sky %d." % n_sky
print "position_x, position_y, e_1, e_2 "
print data[:3]

fig = draw_sky(data)
plt.title("Galaxy positions and ellipcities of sky %d." % n_sky)
plt.xlabel("x-position")
plt.ylabel("y-position");
```

### Priors

Each sky has one, two or three dark matter halos in it. Tim's solution details that his prior distribution of halo positions was uniform, i.e.

\begin{align}
& x_i \sim \text{Uniform}( 0, 4200)\\\\
& y_i \sim \text{Uniform}( 0, 4200), \;\; i=1,2,3\\\\
\end{align}

Tim and other competitors noted that most skies had one large halo and other halos, if present, were much smaller. Larger halos, having more mass, will influence the surrounding galaxies more. He decided that the large halos would have a mass distributed as a *log*-uniform random variable between 40 and 180 i.e.

$$  m_{\text{large} } = \log \text{Uniform}( 40, 180 ) $$

and in PyMC,

    exp_mass_large = pm.Uniform("exp_mass_large", 40, 180)
    @pm.deterministic
    def mass_large(u = exp_mass_large):
       return np.log(u)

(This is what we mean when we say *log*-uniform.) For smaller galaxies, Tim set the mass to be the logarithm of 20. Why did Tim not create a prior for the smaller mass, nor treat it as a unknown? I believe this decision was made to speed up convergence of the algorithm. This is not too restrictive, as by construction the smaller halos have less influence on the galaxies.

Tim logically assumed that the ellipticity of each galaxy is dependent on the position of the halos, the distance between the galaxy and halo, and the mass of the halos. Thus the vector of ellipticity of each galaxy, $\mathbf{e}_i$, are *children* variables of the vector of halo positions $(\mathbf{x},\mathbf{y})$, distance (which we will formalize), and halo masses.

Tim conceived a relationship to connect positions and ellipticity by reading literature and forum posts. He supposed the following was a reasonable relationship:

$$ e_i | ( \mathbf{x}, \mathbf{y} ) \sim \text{Normal}( \sum_{j = \text{halo positions} }d_{i,j} m_j f( r_{i,j} ), \sigma^2 ) $$

where $d_{i,j}$ is the *tangential direction* (the direction in which halo $j$ bends the light of galaxy $i$), $m_j$ is the mass of halo $j$, $f(r_{i,j})$ is a *decreasing function* of the Euclidean distance between halo $j$ and galaxy $i$.

Tim's function $f$ was defined:

$$ f( r_{i,j} ) = \frac{1}{\min( r_{i,j}, 240 ) } $$

for large halos, and for small halos

$$ f( r_{i,j} ) = \frac{1}{\min( r_{i,j}, 70 ) } $$

This fully bridges our observations and unknown. This model is incredibly simple, and Tim mentions this simplicity was purposefully designed: it prevents the model from overfitting.

### Training & PyMC implementation

For each sky, we run our Bayesian model to find the posteriors for the halo positions — we ignore the (known) halo position. This is slightly different than perhaps traditional approaches to Kaggle competitions, where this model uses no data from other skies nor the known halo location. That does not mean other data are not necessary — in fact, the model was created by comparing different skies.

```
def euclidean_distance(x, y):
    return np.sqrt(((x - y) ** 2).sum(axis=1))

def f_distance(gxy_pos, halo_pos, c):
    # foo_position should be a 2-d numpy array
    return np.maximum(euclidean_distance(gxy_pos, halo_pos), c)[:, None]

def tangential_distance(glxy_position, halo_position):
    # foo_position should be a 2-d numpy array
    delta = glxy_position - halo_position
    t = (2 * np.arctan(delta[:, 1] / delta[:, 0]))[:, None]
    return np.concatenate([-np.cos(t), -np.sin(t)], axis=1)

import pymc as pm

# set the size of the halo's mass
mass_large = pm.Uniform("mass_large", 40, 180, trace=False)

# set the initial prior position of the halos, it's a 2-d Uniform dist.
halo_position = pm.Uniform("halo_position", 0, 4200, size=(1, 2))

@pm.deterministic
def mean(mass=mass_large, h_pos=halo_position, glx_pos=data[:, :2]):
    return mass / f_distance(glx_pos, h_pos, 240) *\
        tangential_distance(glx_pos, h_pos)
```

```
ellpty = pm.Normal("ellipcity", mean, 1. / 0.05, observed=True,
                   value=data[:, 2:])
mcmc = pm.MCMC([ellpty, mean, halo_position, mass_large])
map_ = pm.MAP([ellpty, mean, halo_position, mass_large])
map_.fit()
mcmc.sample(200000, 140000, 3)
```

    [****************100%******************]  200000 of 200000 complete

Below we plot a "heatmap" of the posterior distribution. (Which is just a scatter plot of the posterior, but we can visualize it as a heatmap.)

```
t = mcmc.trace("halo_position")[:].reshape(20000, 2)

fig = draw_sky(data)
plt.title("Galaxy positions and ellipcities of sky %d." % n_sky)
plt.xlabel("x-position")
plt.ylabel("y-position")
#scatter(t[:, 0], t[:, 1], alpha=0.015, c="r")
plt.scatter(t[:, 0], t[:, 1], alpha=0.015, c="r")
plt.xlim(0, 4200)
plt.ylim(0, 4200);
```

The most probable position reveals itself like a lethal wound.

Associated with each sky is another data point, located in `./data/Training_halos.csv` that holds the locations of up to three dark matter halos contained in the sky. For example, the night sky we trained on has halo locations:

```
halo_data = np.genfromtxt("data/Training_halos.csv",
                          delimiter=",",
                          usecols=[1, 2, 3, 4, 5, 6, 7, 8, 9],
                          skip_header=1)
print halo_data[n_sky]
```

    [  1.00000000e+00   1.40861000e+03   1.68586000e+03   1.40861000e+03
       1.68586000e+03   0.00000000e+00   0.00000000e+00   0.00000000e+00
       0.00000000e+00]

The third and fourth column represent the true $x$ and $y$ position of the halo. It appears that the Bayesian method has located the halo within a tight vicinity.

```
fig = draw_sky(data)
plt.title("Galaxy positions and ellipcities of sky %d." % n_sky)
plt.xlabel("x-position")
plt.ylabel("y-position")
plt.scatter(t[:, 0], t[:, 1], alpha=0.015, c="r")
plt.scatter(halo_data[n_sky - 1][3], halo_data[n_sky - 1][4],
            label="True halo position",
            c="k", s=70)
plt.legend(scatterpoints=1, loc="lower left")
plt.xlim(0, 4200)
plt.ylim(0, 4200);

print "True halo location:", halo_data[n_sky][3], halo_data[n_sky][4]
```

Perfect. Our next step is to use the loss function to optimize our location. A naive strategy would be to simply choose the mean:

```
mean_posterior = t.mean(axis=0).reshape(1, 2)
print mean_posterior
```

    [[ 2324.20009135  1124.70975607]]

```
from DarkWorldsMetric import main_score

_halo_data = halo_data[n_sky - 1]

nhalo_all = _halo_data[0].reshape(1, 1)
x_true_all = _halo_data[3].reshape(1, 1)
y_true_all = _halo_data[4].reshape(1, 1)
x_ref_all = _halo_data[1].reshape(1, 1)
y_ref_all = _halo_data[2].reshape(1, 1)
sky_prediction = mean_posterior

print "Using the mean:"
main_score(nhalo_all, x_true_all, y_true_all,
           x_ref_all, y_ref_all, sky_prediction)

# what's a bad score?
print
random_guess = np.random.randint(0, 4200, size=(1, 2))
print "Using a random location:", random_guess
main_score(nhalo_all, x_true_all, y_true_all,
           x_ref_all, y_ref_all, random_guess)
print
```

    Using the mean:
    Your average distance in pixels you are away from the true halo is 43.5808980792
    Your average angular vector is 1.0
    Your score for the training data is 1.04358089808

    Using a random location: [[1999 2399]]
    Your average distance in pixels you are away from the true halo is 1354.61074516
    Your average angular vector is 1.0
    Your score for the training data is 2.35461074516

This is a good guess, it is not very far from the true location, but it ignores the loss function that was provided to us. We also need to extend our code to allow for up to two additional, *smaller* halos: Let's create a function for automatizing our PyMC.

```
from pymc.Matplot import plot as mcplot

def halo_posteriors(n_halos_in_sky, galaxy_data,
                    samples=5e5, burn_in=34e4, thin=4):
    # set the size of the halo's mass
    """
    exp_mass_large = pm.Uniform("exp_mass_large", 40, 180)
    @pm.deterministic
    def mass_large(exp_mass_large = exp_mass_large):
        return np.log(exp_mass_large)
    """

    mass_large = pm.Uniform("mass_large", 40, 180)

    mass_small_1 = 20
    mass_small_2 = 20

    masses = np.array([mass_large, mass_small_1, mass_small_2], dtype=object)

    # set the initial prior positions of the halos, it's a 2-d Uniform dist.
    halo_positions = pm.Uniform("halo_positions", 0, 4200,
                                size=(n_halos_in_sky, 2))  # notice this size

    fdist_constants = np.array([240, 70, 70])

    @pm.deterministic
    def mean(mass=masses, h_pos=halo_positions, glx_pos=data[:, :2],
             n_halos_in_sky=n_halos_in_sky):

        _sum = 0
        for i in range(n_halos_in_sky):
            _sum += mass[i] / f_distance(glx_pos, h_pos[i, :], fdist_constants[i]) *\
                tangential_distance(glx_pos, h_pos[i, :])

        return _sum

    ellpty = pm.Normal("ellipcity", mean, 1. / 0.05, observed=True,
                       value=data[:, 2:])

    map_ = pm.MAP([ellpty, mean, halo_positions, mass_large])
#    map_.fit(method="fmin_powell)
    map_.fit(method="fmin_powell")

    mcmc = pm.MCMC([ellpty, mean, halo_positions, mass_large])
    mcmc.sample(samples, burn_in, thin)
    return mcmc.trace("halo_positions")[:]
```

```
n_sky = 215
data = np.genfromtxt("data/Train_Skies/Train_Skies/\
Training_Sky%d.csv" % (n_sky),
                      dtype=None,
                      skip_header=1,
                      delimiter=",",
                      usecols=[1, 2, 3, 4])
```

```
# there are 3 halos in this file.
samples = 10.5e5
traces = halo_posteriors(3, data, samples=samples,
                         burn_in=9.5e5,
                         thin=10)
```

```

fig = draw_sky(data)
plt.title("Galaxy positions and ellipcities of sky %d." % n_sky)
plt.xlabel("x-position")
plt.ylabel("y-position")

colors = ["#467821", "#A60628", "#7A68A6"]

for i in range(traces.shape[1]):
    plt.scatter(traces[:, i, 0], traces[:, i, 1], c=colors[i], alpha=0.02)

for i in range(traces.shape[1]):
    plt.scatter(halo_data[n_sky - 1][3 + 2 * i], halo_data[n_sky - 1][4 + 2 * i],
                label="True halo position",
                c="k", s=90)

# plt.legend(scatterpoints = 1)
plt.xlim(0, 4200)
plt.ylim(0, 4200);
```

This looks pretty good, though it took a long time for the system to (sort of) converge. Our optimization step would look something like this:

```
_halo_data = halo_data[n_sky - 1]
print traces.shape

mean_posterior = traces.mean(axis=0).reshape(1, 4)
print mean_posterior

nhalo_all = _halo_data[0].reshape(1, 1)
x_true_all = _halo_data[3].reshape(1, 1)
y_true_all = _halo_data[4].reshape(1, 1)
x_ref_all = _halo_data[1].reshape(1, 1)
y_ref_all = _halo_data[2].reshape(1, 1)
sky_prediction = mean_posterior

print "Using the mean:"
main_score([1], x_true_all, y_true_all,
           x_ref_all, y_ref_all, sky_prediction)

# what's a bad score?
print
random_guess = np.random.randint(0, 4200, size=(1, 2))
print "Using a random location:", random_guess
main_score([1], x_true_all, y_true_all,
           x_ref_all, y_ref_all, random_guess)
print
```

## References
1. Antifragile: Things That Gain from Disorder. New York: Random House. 2012. ISBN 978-1-4000-6782-4.
1.  [Tim Saliman's solution to the Dark World's Contest](http://www.timsalimans.com/observing-dark-worlds)
2. Silver, Nate. The Signal and the Noise: Why So Many Predictions Fail — but Some Don't. 1. Penguin Press HC, The, 2012. Print.

```
from IPython.core.display import HTML

def css_styling():
    styles = open("../styles/custom.css", "r").read()
    return HTML(styles)
css_styling()
```

```

```