# Prewhitening in Python
A notebook on how to prewhiten your data in Python. 

Implementation as described in:

Representational fMRI analysis: an introductory tutorial. Alexander Walther, Naveed Ejaz, Nikolaus Kriegeskorte, Jörn Diedrichsen. [Link](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.721.4570&rep=rep1&type=pdf).


```python
import numpy as np
from scipy.linalg import sqrtm
import matplotlib.pyplot as plt
%matplotlib inline
```

Let's generate some correlated data:


```python
C = np.array([[1, .9], [.9, 1]])
x = np.random.multivariate_normal([0, 0], C, 10000)

plt.scatter(x[:, 0], x[:, 1])
plt.title('Original data')
plt.show()
```

Now, let's prewhiten the data as follows:

\begin{align}
X_{prewhitened} = (X'X)^{-1/2}X
\end{align}


```python
D = sqrtm(np.linalg.inv(np.cov(x.T)))  # D = prewhitening matrix
xw = D.dot(x.T).T
plt.title('Prewhitened')
plt.scatter(xw[:, 0], xw[:, 1])
plt.show()
```

Now, the covariance-matrix of X should (approximately) be the identity-matrix ($I$):


```python
np.cov(xw.T)
```




    array([[  1.00000000e+00,   2.53914523e-15],
           [  2.53914523e-15,   1.00000000e+00]])



643bb72db2fd6273d53f96f2261b7d685f41624b
ipynb
Jupyter Notebook
prewhitening.ipynb
lukassnoek/random_notebooks
d7df507ce2b6949726c29de0022aae2d0dc583ac
MIT
2018-05-28T13:45:11.000Z
2021-08-31T11:41:34.000Z
prewhitening.ipynb
lukassnoek/random_notebooks
d7df507ce2b6949726c29de0022aae2d0dc583ac
MIT
prewhitening.ipynb
lukassnoek/random_notebooks
d7df507ce2b6949726c29de0022aae2d0dc583ac
MIT
2018-05-28T13:46:05.000Z
2018-06-11T15:25:59.000Z
Qwen/Qwen-72B
1. YES
2. YES