scikit-learn/examples/plot_rbm_logistic_classific...

142 lines
4.5 KiB
Python
Raw Normal View History

2012-10-13 05:01:19 +08:00
"""
2013-07-24 20:32:07 +08:00
==============================================================
Restricted Boltzmann Machine features for digit classification
==============================================================
For greyscale image data where pixel values can be interpreted as degrees of
blackness on a white background, like handwritten digit recognition, the
Bernoulli Restricted Boltzmann machine model (:class:`BernoulliRBM
<sklearn.neural_network.BernoulliRBM>`) can perform effective non-linear
feature extraction.
In order to learn good latent representations from a small dataset, we
artificially generate more labeled data by perturbing the training data with
linear shifts of 1 pixel in each direction.
This example shows how to build a classification pipeline with a BernoulliRBM
feature extractor and a :class:`LogisticRegression
2013-07-22 23:13:28 +08:00
<sklearn.linear_model.LogisticRegression>` classifier. The hyperparameters
of the entire model (learning rate, hidden layer size, regularization)
were optimized by grid search, but the search is not reproduced here because
of runtime constraints.
Logistic regression on raw pixel values is presented for comparison. The
example shows that the features extracted by the BernoulliRBM help improve the
classification accuracy.
2012-10-13 05:01:19 +08:00
"""
2013-07-22 20:52:45 +08:00
2013-07-24 20:32:07 +08:00
from __future__ import print_function
2012-10-13 05:01:19 +08:00
2013-07-24 20:32:07 +08:00
print(__doc__)
2012-10-13 05:01:19 +08:00
# Authors: Yann N. Dauphin, Vlad Niculae, Gabriel Synnaeve
2012-10-13 05:01:19 +08:00
# License: BSD
import numpy as np
2013-07-24 20:32:07 +08:00
import matplotlib.pyplot as plt
2012-10-13 05:01:19 +08:00
from scipy.ndimage import convolve
2013-05-07 06:28:07 +08:00
from sklearn import linear_model, datasets, metrics
2013-01-01 23:37:29 +08:00
from sklearn.cross_validation import train_test_split
2013-02-03 01:07:37 +08:00
from sklearn.neural_network import BernoulliRBM
2012-10-13 05:01:19 +08:00
from sklearn.pipeline import Pipeline
2013-07-22 20:52:45 +08:00
2012-10-13 05:01:19 +08:00
###############################################################################
# Setting up
def nudge_dataset(X, Y):
"""
This produces a dataset 5 times bigger than the original one,
by moving the 8x8 images in X around by 1px to left, right, down, up
"""
direction_vectors = [
[[0, 1, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[1, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 1],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 1, 0]]]
shift = lambda x, w: convolve(x.reshape((8, 8)), mode='constant',
weights=w).ravel()
X = np.concatenate([X] +
[np.apply_along_axis(shift, 1, X, vector)
for vector in direction_vectors])
2013-07-24 21:31:12 +08:00
Y = np.concatenate([Y for _ in range(5)], axis=0)
return X, Y
2012-10-13 05:01:19 +08:00
# Load Data
2012-10-16 06:51:19 +08:00
digits = datasets.load_digits()
X = np.asarray(digits.data, 'float32')
X, Y = nudge_dataset(X, digits.target)
2013-07-22 20:52:45 +08:00
X = (X - np.min(X, 0)) / (np.max(X, 0) + 0.0001) # 0-1 scaling
2013-01-01 23:37:29 +08:00
X_train, X_test, Y_train, Y_test = train_test_split(X, Y,
2013-05-09 20:16:35 +08:00
test_size=0.2,
2013-05-09 21:20:49 +08:00
random_state=0)
2012-10-13 05:01:19 +08:00
# Models we will use
logistic = linear_model.LogisticRegression()
rbm = BernoulliRBM(random_state=0, verbose=True)
2012-10-13 05:01:19 +08:00
2013-05-07 06:28:07 +08:00
classifier = Pipeline(steps=[('rbm', rbm), ('logistic', logistic)])
2012-10-13 05:01:19 +08:00
###############################################################################
# Training
2013-05-09 20:04:36 +08:00
# Hyper-parameters. These were set by cross-validation,
# using a GridSearchCV. Here we are not performing cross-validation to
2013-05-07 06:28:07 +08:00
# save time.
rbm.learning_rate = 0.06
rbm.n_iter = 20
2013-05-09 20:04:36 +08:00
# More components tend to give better prediction performance, but larger
2013-05-07 06:28:07 +08:00
# fitting time
rbm.n_components = 100
logistic.C = 6000.0
2012-10-13 05:01:19 +08:00
# Training RBM-Logistic Pipeline
2013-05-07 06:28:07 +08:00
classifier.fit(X_train, Y_train)
2012-10-13 05:01:19 +08:00
# Training Logistic regression
logistic_classifier = linear_model.LogisticRegression(C=100.0)
2013-05-07 06:28:07 +08:00
logistic_classifier.fit(X_train, Y_train)
2012-10-13 05:01:19 +08:00
###############################################################################
# Evaluation
2013-07-24 20:32:07 +08:00
print()
print("Logistic regression using RBM features:\n%s\n" % (
metrics.classification_report(
2013-05-09 20:16:35 +08:00
Y_test,
2013-07-24 20:32:07 +08:00
classifier.predict(X_test))))
2012-10-13 05:01:19 +08:00
2013-07-24 20:32:07 +08:00
print("Logistic regression using raw pixel features:\n%s\n" % (
metrics.classification_report(
2013-05-09 20:16:35 +08:00
Y_test,
2013-07-24 20:32:07 +08:00
logistic_classifier.predict(X_test))))
2013-05-07 06:28:07 +08:00
###############################################################################
# Plotting
2013-07-24 20:32:07 +08:00
plt.figure(figsize=(4.2, 4))
for i, comp in enumerate(rbm.components_):
2013-07-24 20:32:07 +08:00
plt.subplot(10, 10, i + 1)
plt.imshow(comp.reshape((8, 8)), cmap=plt.cm.gray_r,
interpolation='nearest')
plt.xticks(())
plt.yticks(())
plt.suptitle('100 components extracted by RBM', fontsize=16)
plt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23)
plt.show()