In [1]:
from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
import numpy as np
np.set_printoptions(suppress=True)

digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target)

Removing mean and scaling variance


In [2]:
from sklearn.preprocessing import StandardScaler

1) Instantiate the model


In [3]:
scaler = StandardScaler()

2) Fit using only the data.


In [5]:
scaler.fit(X_train)


Out[5]:
StandardScaler(copy=True, with_mean=True, with_std=True)

3) transform the data (not predict).


In [6]:
X_train_scaled = scaler.transform(X_train)

In [7]:
X_train.shape


Out[7]:
(1347, 64)

In [8]:
X_train_scaled.shape


Out[8]:
(1347, 64)

The transformed version of the data has the mean removed:


In [9]:
X_train_scaled.mean(axis=0)


Out[9]:
array([ 0.,  0.,  0.,  0., -0., -0.,  0., -0., -0., -0., -0., -0., -0.,
        0.,  0.,  0.,  0., -0., -0.,  0.,  0., -0.,  0., -0., -0., -0.,
        0., -0.,  0., -0.,  0., -0.,  0., -0., -0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0., -0., -0., -0.,  0.,  0.,  0.,  0., -0., -0., -0.,
        0.,  0.,  0.,  0., -0., -0.,  0.,  0., -0., -0.,  0.,  0.])

In [10]:
X_train_scaled.std(axis=0)


Out[10]:
array([ 0.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
        1.,  1.,  1.,  1.,  1.,  1.,  0.,  1.,  1.,  1.,  1.,  1.,  1.,
        0.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

In [11]:
X_test_transformed = scaler.transform(X_test)

Principal Component Analysis

0) Import the model


In [12]:
from sklearn.decomposition import PCA

1) Instantiate the model


In [13]:
pca = PCA(n_components=2)

2) Fit to training data


In [14]:
pca.fit(X_train)


Out[14]:
PCA(copy=True, n_components=2, whiten=False)

3) Transform to lower-dimensional representation


In [15]:
print(X_train.shape)
X_pca = pca.transform(X_train)
X_pca.shape


(1347, 64)
Out[15]:
(1347, 2)

Visualize


In [16]:
import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_train)


Out[16]:
<matplotlib.collections.PathCollection at 0x7f3cce5997d0>

In [ ]: