|
| 1 | +#!/usr/bin/python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +========================================================= |
| 5 | +Importance of Feature Scaling |
| 6 | +========================================================= |
| 7 | +
|
| 8 | +Feature scaling though standardization (or Z-score normalization) |
| 9 | +can be an important preprocessing step for many machine learning |
| 10 | +algorithms. Standardization involves rescaling the features such |
| 11 | +that they have the properties of a standard normal distribution |
| 12 | +with a mean of zero and a standard deviation of one. |
| 13 | +
|
| 14 | +While many algorithms (such as SVM, K-nearest neighbors, and logistic |
| 15 | +regression) require features to be normalized, intuitively we can |
| 16 | +think of Principle Component Analysis (PCA) as being a prime example |
| 17 | +of when normalization is important. In PCA we are interested in the |
| 18 | +components that maximize the variance. If one component (e.g. human |
| 19 | +height) varies less than another (e.g. weight) because of their |
| 20 | +respective scales (meters vs. kilos), PCA might determine that the |
| 21 | +direction of maximal variance more closely corresponds with the |
| 22 | +'weight' axis, if those features are not scaled. As a change in |
| 23 | +height of one meter can be considered much more important than the |
| 24 | +change in weight of one kilogram, this is clearly incorrect. |
| 25 | +
|
| 26 | +To illustrate this, PCA is performed comparing the use of data with |
| 27 | +:class:`StandardScaler <sklearn.preprocessing.StandardScaler>` applied, |
| 28 | +to unscaled data. The results are visualized and a clear difference noted. |
| 29 | +The 1st principal component in the unscaled set can be seen. It can be seen |
| 30 | +that feature #13 dominates the direction, being a whole two orders of |
| 31 | +magnitude above the other features. This is contrasted when observing |
| 32 | +the principal component for the scaled version of the data. In the scaled |
| 33 | +version, the orders of magnitude are roughly the same across all the features. |
| 34 | +
|
| 35 | +The dataset used is the Wine Dataset available at UCI. This dataset |
| 36 | +has continuous features that are heterogeneous in scale due to differing |
| 37 | +properties that they measure (i.e alcohol content, and malic acid). |
| 38 | +
|
| 39 | +The transformed data is then used to train a naive Bayes classifier, and a |
| 40 | +clear difference in prediction accuracies is observed wherein the dataset |
| 41 | +which is scaled before PCA vastly outperforms the unscaled version. |
| 42 | +
|
| 43 | +""" |
| 44 | +from __future__ import print_function |
| 45 | +from sklearn.model_selection import train_test_split |
| 46 | +from sklearn.preprocessing import StandardScaler |
| 47 | +from sklearn.decomposition import PCA |
| 48 | +from sklearn.naive_bayes import GaussianNB |
| 49 | +from sklearn import metrics |
| 50 | +import matplotlib.pyplot as plt |
| 51 | +from sklearn.datasets import load_wine |
| 52 | +from sklearn.pipeline import make_pipeline |
| 53 | +print(__doc__) |
| 54 | + |
| 55 | +# Code source: Tyler Lanigan <[email protected]> |
| 56 | +# Sebastian Raschka <[email protected]> |
| 57 | + |
| 58 | +# License: BSD 3 clause |
| 59 | + |
| 60 | +RANDOM_STATE = 42 |
| 61 | +FIG_SIZE = (10, 7) |
| 62 | + |
| 63 | + |
| 64 | +features, target = load_wine(return_X_y=True) |
| 65 | + |
| 66 | +# Make a train/test split using 30% test size |
| 67 | +X_train, X_test, y_train, y_test = train_test_split(features, target, |
| 68 | + test_size=0.30, |
| 69 | + random_state=RANDOM_STATE) |
| 70 | + |
| 71 | +# Fit to data and predict using pipelined GNB and PCA. |
| 72 | +unscaled_clf = make_pipeline(PCA(n_components=2), GaussianNB()) |
| 73 | +unscaled_clf.fit(X_train, y_train) |
| 74 | +pred_test = unscaled_clf.predict(X_test) |
| 75 | + |
| 76 | +# Fit to data and predict using pipelined scaling, GNB and PCA. |
| 77 | +std_clf = make_pipeline(StandardScaler(), PCA(n_components=2), GaussianNB()) |
| 78 | +std_clf.fit(X_train, y_train) |
| 79 | +pred_test_std = std_clf.predict(X_test) |
| 80 | + |
| 81 | +# Show prediction accuracies in scaled and unscaled data. |
| 82 | +print('\nPrediction accuracy for the normal test dataset with PCA') |
| 83 | +print('{:.2%}\n'.format(metrics.accuracy_score(y_test, pred_test))) |
| 84 | + |
| 85 | +print('\nPrediction accuracy for the standardized test dataset with PCA') |
| 86 | +print('{:.2%}\n'.format(metrics.accuracy_score(y_test, pred_test_std))) |
| 87 | + |
| 88 | +# Extract PCA from pipeline |
| 89 | +pca = unscaled_clf.named_steps['pca'] |
| 90 | +pca_std = std_clf.named_steps['pca'] |
| 91 | + |
| 92 | +# Show first principal componenets |
| 93 | +print('\nPC 1 without scaling:\n', pca.components_[0]) |
| 94 | +print('\nPC 1 with scaling:\n', pca_std.components_[0]) |
| 95 | + |
| 96 | +# Scale and use PCA on X_train data for visualization. |
| 97 | +scaler = std_clf.named_steps['standardscaler'] |
| 98 | +X_train_std = pca_std.transform(scaler.transform(X_train)) |
| 99 | + |
| 100 | +# visualize standardized vs. untouched dataset with PCA performed |
| 101 | +fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=FIG_SIZE) |
| 102 | + |
| 103 | + |
| 104 | +for l, c, m in zip(range(0, 3), ('blue', 'red', 'green'), ('^', 's', 'o')): |
| 105 | + ax1.scatter(X_train[y_train == l, 0], X_train[y_train == l, 1], |
| 106 | + color=c, |
| 107 | + label='class %s' % l, |
| 108 | + alpha=0.5, |
| 109 | + marker=m |
| 110 | + ) |
| 111 | + |
| 112 | +for l, c, m in zip(range(0, 3), ('blue', 'red', 'green'), ('^', 's', 'o')): |
| 113 | + ax2.scatter(X_train_std[y_train == l, 0], X_train_std[y_train == l, 1], |
| 114 | + color=c, |
| 115 | + label='class %s' % l, |
| 116 | + alpha=0.5, |
| 117 | + marker=m |
| 118 | + ) |
| 119 | + |
| 120 | +ax1.set_title('Training dataset after PCA') |
| 121 | +ax2.set_title('Standardized training dataset after PCA') |
| 122 | + |
| 123 | +for ax in (ax1, ax2): |
| 124 | + ax.set_xlabel('1st principal component') |
| 125 | + ax.set_ylabel('2nd principal component') |
| 126 | + ax.legend(loc='upper right') |
| 127 | + ax.grid() |
| 128 | + |
| 129 | +plt.tight_layout() |
| 130 | + |
| 131 | +plt.show() |
0 commit comments