Repository navigation
Added Restricted Boltzmann machines #1200
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
66 commits
Select commit
Hold shift + click to select a range
f192a8f
added class for Restricted Boltzmann machines
9c4afeb
initialize W with random_state
be2b734
moved verbose parameter to init
57243d3
removed empty main function
7016300
removed verbose from fit_transform
3fd5947
rename epochs to n_epochs
e7b4fc6
rename n_samples to n_particles
82ad100
support for sparse inputs
2c2cdfb
renamed epsilon to learning rate
ea2c5c9
rename class to full name
47af232
mistake in the documented complexity
92f7ea8
use n_features instead of n_visibles to be consistent with the codebase
dd79de0
rename parameters to be consistent with codebase
c02cdcf
30% speed-up thanks to in-place binomial from https://gist.github.com…
5e2abdf
12% with ingenious ordering of operations
e3182b4
inplace gradients for components_, 2% speed-up
b9e20cc
rename h_samples to h_samples_
8303ef2
use X instead of v as parameter to transform
930c173
use X instead of v as parameter to transform
548a357
clarify n_particles documentation
73de6f7
bugfix doctest
47ef7fa
added URI for RBM reference
f8e635d
improved docstring for transform
5f5b5c9
renamed _sigmoid to _logistic_sigmoid
33afdd3
use double backquotes around equations
4a34bcf
logistic_sigmoid moved to function
e4f5a53
transposed components_, no performance penalty
2163337
only compute pseudolikelihood if verbose=True
ae0c10e
more accurate pseudo-likelihood
45e2ca1
rename n_epochs to n_iter
41f355f
use iteration terminology
8c339d6
default n_components from 1024 to 256
103b7ef
clarify some method names (ex: mean_h -> mean_hiddens)
b6b5df2
added epoch time
56cc7fb
work in progress on an example
bd3120c
bugfix
2cba79f
use different class for example
e2cd801
switched to digits
87cbde2
moved rbms to neural_networks module
3be448f
add tests for rbm
7720148
trim whitespace
5413e9f
COSMIT RBM test in usual nose style + moved to proper module
larsmans 978bb22
BUG + COSMIT + ENH RBMs
larsmans 5a0e69b
Merge pull request #1 from larsmans/rbm
8891e0e
use train_test_split
a71b6cc
Added RBM to whats_new.rst
vene 79e1a79
Added skeleton for RBM documentation
vene 561fb99
FIX mistake in rst
vene 11abf87
Rename RestrictedBolzmannMachine to BernoulliRBM
vene 28c0093
FIX: make BernoulliRBM doctest pass
vene d8efeb6
Merge branch 'master' into rbm-docs
vene 8dd07d7
Rename also in whats_new
vene e48c39a
FIX: BernoulliRBM check random state in fit, not in init
vene c38ce39
FIX: validation in `BernoulliRBM.transform`
vene b665631
DOC: first attempt at RBM documentation
vene 1dbecad
Link to RBM docs from the unsupervised toctree
vene 9e77703
FIX: uneven RBM image
vene 9b7f5a6
Merge https://github.com/scikit-learn/scikit-learn into rbm
a13a762
DOC: PCD details and references
vene 2b5767a
Merge branch 'rbm-docs' of https://github.com/vene/scikit-learn into …
234b087
neural_networks -> neural_network
f8e0110
rename n_particles to batch_size
ad4877a
bugfix test
5400735
bugfix test
6dfc317
added tests
83daf31
tests
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| .. _neural_network: | ||
|
|
||
| ==================================== | ||
| Neural network models (unsupervised) | ||
| ==================================== | ||
|
|
||
| .. currentmodule:: sklearn.neural_network | ||
|
|
||
|
|
||
| .. _rbm: | ||
|
|
||
| Restricted Boltzmann Machines | ||
| ============================= | ||
|
|
||
| Restricted Boltzmann Machines (RBM) are unsupervised nonlinear feature learners | ||
| based on a probabilistic model. The features extracted by an RBM give good | ||
| results when fed into a linear classifier such as a linear SVM or perceptron. | ||
|
|
||
| The training method is based on an approximation, for efficiency. It prevents | ||
| the representations from straying far from the input data, which makes them | ||
| capture interesting regularities, but makes the model less useful for small | ||
| datasets, and usually not useful for density estimation. | ||
|
|
||
| Deep neural networks that are notoriously difficult to train from scratch can | ||
| be simplified by initializing each layer's weights with the weights of an RBM. | ||
|
|
||
| The makes assumptions regarding the distribution of inputs. At the moment, | ||
| scikit-learn only provides :class:`BernoulliRBM`, which assumes the input are | ||
| either binary values or values between 0 and 1, each encoding the probability | ||
| that the specific feature would be turned on. | ||
|
|
||
| Graphical model and parametrization | ||
| ----------------------------------- | ||
|
|
||
| The graphical model of an RBM is a fully-connected bipartite graph. | ||
|
|
||
| .. image:: ../images/rbm_graph.png | ||
| :align: center | ||
|
|
||
| The nodes are random variables whose states depend on the state of the other | ||
| nodes they are connected to. The model is therefore parameterized by the | ||
| weights of the connections, as well as one intercept (bias) term for each | ||
| visible and hidden unit, ommited from the image for simplicity. | ||
|
|
||
| The energy function measures the quality of a joint assignment: | ||
|
|
||
| .. math:: | ||
|
|
||
| E(\mathbf{v}, \mathbf{h}) = \sum_i \sum_j w_{ij}v_ih_j + \sum_i b_iv_i | ||
| + \sum_j c_jh_j | ||
|
|
||
| In the formula above, :math:`\mathbf{b}` and :math:`\mathbf{c}` are the | ||
| intercept vectors for the visible and hidden layers, respectively. The | ||
| joint probability of the model is defined in terms of the energy: | ||
|
|
||
| .. math:: | ||
|
|
||
| P(\mathbf{v}, \mathbf{h}) = \frac{e^{-E(\mathbf{v}, \mathbf{h})}}{Z} | ||
|
|
||
|
|
||
| The word *restricted* refers to the bipartite structure of the model, which | ||
| prohibits direct interaction between hidden units, or between visible units. | ||
| This makes inference much easier by assuming the following conditional | ||
| independencies: | ||
|
|
||
| .. math:: | ||
|
|
||
| h_i \bot h_j | \mathbf{v} \\ | ||
| v_i \bot v_j | \mathbf{h} | ||
|
|
||
|
|
||
| Bernoulli Restricted Boltzmann Machines | ||
| --------------------------------------- | ||
|
|
||
| In the :class:`BernoulliRBM`, all units are binary stochastic units. This | ||
| means that the input data should either be binary, or real-valued between 0 and | ||
| 1 signifying the probability that the visible unit would turn on or off. This | ||
| is a good model for character recognition, where the interest is on which | ||
| pixels are active and which aren't. For images of natural scenes it no longer | ||
| fits because of background, depth and the tendency of neighbouring pixels to | ||
| take the same values. | ||
|
|
||
| The conditional probability distribution of each unit is given by the | ||
| logistic sigmoid activation function of the input it receives: | ||
|
|
||
| .. math:: | ||
|
|
||
| P(v_i=1|\mathbf{h}) = \sigma(\sum_j w_{ij}h_j + b_i) \\ | ||
| P(h_i=1|\mathbf{v}) = \sigma(\sum_i w_{ij}v_i + c_j) | ||
|
|
||
| where :math:`\sigma` is the logistic sigmoid function: | ||
|
|
||
| .. math:: | ||
|
|
||
| \sigma(x) = \frac{1}{1 + e^{-x}} | ||
|
|
||
| Stochastic Maximum Likelihood Learning | ||
| -------------------------------------- | ||
|
|
||
| The training algorithm implemented in :class:`BernoulliRBM` is known as | ||
| Stochastic Maximum Likelihood (SML) or Persistent Contrastive Divergence | ||
| (PCD). Optimizing Maximum Likelihood directly is infeasible because of | ||
| the shape of the data likelihood: | ||
|
|
||
| .. math:: | ||
|
|
||
| \log P(v) = \log \sum_h e^{-E(v, h)} - \log \sum_{x, y} e^{-E(x, y)} | ||
|
|
||
| For simplicity the equation above is written for a single training example, | ||
| but often in practice, as well as in this implementation, it is optimized by | ||
| averaging over mini-batches. The gradient with respect to the weights is | ||
| formed of two terms corresponding to the ones above. They are usually known as | ||
| the positive gradient and the negative gradient, because of their respective | ||
| signs. | ||
|
|
||
| In maximizing the log likelihood, the positive gradient makes the model prefer | ||
| hidden states that are compatible with the observed training data. Because of | ||
| the the bipartite structure of RBMs, it can be computed efficiently. The | ||
| negative gradient, however, is intractable. Its goal is to lower the energy of | ||
| joint states that the model prefers, therefore making it stay true to the data | ||
| and not fantasize. It can be approximated by Markov Chain Monte Carlo using | ||
| block Gibbs sampling by iteratively sampling each of :math:`v` and :math:`h` | ||
| given the other, until the chain mixes. Samples generated in this way are | ||
| sometimes refered as fantasy particles. This is inefficient and it's difficult | ||
| to determine whether the Markov chain mixes. | ||
|
|
||
| The Contrastive Divergence method suggests to stop the chain after a small | ||
| number of iterations, :math:`k`, usually even 1. This method is fast and has | ||
| low variance, but the samples are far from the true distribution. | ||
|
|
||
| Persistent Contrastive Divergence addresses this. Instead of starting a new | ||
| chain each time the gradient is needed, and sampling after one Gibbs step, in | ||
| PCD we keep a number of chains (fantasy particles) that are updated :math:`k` | ||
| Gibbs steps after each weight update. This allows the particles to explore the | ||
| space more thoroughly. | ||
|
|
||
| .. topic:: References: | ||
|
|
||
| * `"A fast learning algorithm for deep belief nets" | ||
| <http://www.cs.toronto.edu/~hinton/absps/fastnc.pdf>`_ | ||
| G. Hinton, S. Osindero, Y.-W. Teh, 2006 | ||
|
|
||
| * `"Training Restricted Boltzmann Machines using Approximations to | ||
| the Likelihood Gradient" | ||
| <http://www.cs.toronto.edu/~tijmen/pcd/pcd.pdf>`_ | ||
| T. Tieleman, 2008 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,5 +14,6 @@ Unsupervised learning | |
| modules/covariance | ||
| modules/outlier_detection | ||
| modules/hmm | ||
| modules/neural_network | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| #!/usr/bin/python | ||
| # -*- coding: utf-8 -*- | ||
|
|
||
| """ | ||
| ========================================================= | ||
| Pipelining: chaining a RBM and a logistic regression | ||
| ========================================================= | ||
|
|
||
| The BernoulliRBM does unsupervised feature extraction, | ||
| while the logistic regression does the prediction. | ||
|
|
||
| We use a GridSearchCV to set the number of hidden units and the learning rate | ||
| of the Bernoulli Restricted Boltzmann Machine. | ||
|
|
||
| We also train a simple logistic regression for comparison. The example shows | ||
| that the features extracted by the BernoulliRBM help improve | ||
| the classification accuracy. | ||
|
|
||
| """ | ||
| print __doc__ | ||
|
|
||
|
|
||
| # Code source: Yann N. Dauphin | ||
| # License: BSD | ||
|
|
||
|
|
||
| import numpy as np | ||
|
|
||
| from sklearn import linear_model, datasets, metrics, preprocessing | ||
| from sklearn.cross_validation import train_test_split | ||
| from sklearn.neural_network import BernoulliRBM | ||
| from sklearn.pipeline import Pipeline | ||
| from sklearn.grid_search import GridSearchCV | ||
|
|
||
| ############################################################################### | ||
| # Setting up | ||
|
|
||
| np.random.seed(0xfeeb) | ||
|
|
||
| # Load Data | ||
| digits = datasets.load_digits() | ||
| X = np.asarray(digits.data, 'float32') / digits.data.max() | ||
| Y = digits.target | ||
| X_train, X_test, Y_train, Y_test = train_test_split(X, Y, | ||
| test_size=0.2, random_state=0xfeeb) | ||
|
|
||
| # Models we will use | ||
| logistic = linear_model.LogisticRegression() | ||
| rbm = BernoulliRBM() | ||
|
|
||
| pipe = Pipeline(steps=[('rbm', rbm), ('logistic', logistic)]) | ||
|
|
||
| ############################################################################### | ||
| # Training | ||
|
|
||
| # Hyper-parameters | ||
| n_components = [350, 400, 450] | ||
| learning_rate = [0.01, 0.01] | ||
| Cs = np.logspace(-4, 4, 2) | ||
| n_iter = [20, 30] | ||
|
|
||
| # Training RBM-Logistic Pipeline | ||
| estimator = GridSearchCV(pipe, | ||
| dict(rbm__n_components=n_components, | ||
| rbm__learning_rate=learning_rate, | ||
| rbm__n_iter=n_iter, | ||
| logistic__C=Cs)) | ||
| estimator.fit(X_train, Y_train) | ||
| classifier = estimator.best_estimator_ | ||
|
|
||
| # Training Logistic regression | ||
| logistic_estimator = GridSearchCV(logistic, | ||
| dict(C=Cs)) | ||
| logistic_estimator.fit(X_train, Y_train) | ||
| logistic_classifier = logistic_estimator.best_estimator_ | ||
|
|
||
|
|
||
| ############################################################################### | ||
| # Evaluation | ||
|
|
||
| print "Classification report for classifier %s:\n%s\n" % ( | ||
| classifier, metrics.classification_report(Y_test, | ||
| classifier.predict(X_test))) | ||
|
|
||
| print "Classification report for classifier %s:\n%s\n" % ( | ||
| logistic_classifier, metrics.classification_report(Y_test, | ||
| logistic_classifier.predict(X_test))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| """ | ||
| The :mod:`sklearn.neural_network` module includes models based on neural | ||
| networks. | ||
| """ | ||
|
|
||
| from .rbm import BernoulliRBM |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think that the above paragraph can be much shortened. I don't see how it is useful to the end user.