Skip to content
Closed
Show file tree
Hide file tree
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
Oct 2, 2012
9c4afeb
initialize W with random_state
Oct 3, 2012
be2b734
moved verbose parameter to init
Oct 3, 2012
57243d3
removed empty main function
Oct 3, 2012
7016300
removed verbose from fit_transform
Oct 3, 2012
3fd5947
rename epochs to n_epochs
Oct 3, 2012
e7b4fc6
rename n_samples to n_particles
Oct 3, 2012
82ad100
support for sparse inputs
Oct 3, 2012
2c2cdfb
renamed epsilon to learning rate
Oct 3, 2012
ea2c5c9
rename class to full name
Oct 3, 2012
47af232
mistake in the documented complexity
Oct 3, 2012
92f7ea8
use n_features instead of n_visibles to be consistent with the codebase
Oct 3, 2012
dd79de0
rename parameters to be consistent with codebase
Oct 3, 2012
c02cdcf
30% speed-up thanks to in-place binomial from https://gist.github.com…
Oct 3, 2012
5e2abdf
12% with ingenious ordering of operations
Oct 3, 2012
e3182b4
inplace gradients for components_, 2% speed-up
Oct 3, 2012
b9e20cc
rename h_samples to h_samples_
Oct 4, 2012
8303ef2
use X instead of v as parameter to transform
Oct 4, 2012
930c173
use X instead of v as parameter to transform
Oct 4, 2012
548a357
clarify n_particles documentation
Oct 4, 2012
73de6f7
bugfix doctest
Oct 4, 2012
47ef7fa
added URI for RBM reference
Oct 4, 2012
f8e635d
improved docstring for transform
Oct 4, 2012
5f5b5c9
renamed _sigmoid to _logistic_sigmoid
Oct 4, 2012
33afdd3
use double backquotes around equations
Oct 4, 2012
4a34bcf
logistic_sigmoid moved to function
Oct 4, 2012
e4f5a53
transposed components_, no performance penalty
Oct 5, 2012
2163337
only compute pseudolikelihood if verbose=True
Oct 5, 2012
ae0c10e
more accurate pseudo-likelihood
Oct 5, 2012
45e2ca1
rename n_epochs to n_iter
Oct 8, 2012
41f355f
use iteration terminology
Oct 8, 2012
8c339d6
default n_components from 1024 to 256
Oct 8, 2012
103b7ef
clarify some method names (ex: mean_h -> mean_hiddens)
Oct 8, 2012
b6b5df2
added epoch time
Oct 12, 2012
56cc7fb
work in progress on an example
Oct 12, 2012
bd3120c
bugfix
Oct 13, 2012
2cba79f
use different class for example
Oct 13, 2012
e2cd801
switched to digits
Oct 15, 2012
87cbde2
moved rbms to neural_networks module
Oct 16, 2012
3be448f
add tests for rbm
Oct 23, 2012
7720148
trim whitespace
Oct 23, 2012
5413e9f
COSMIT RBM test in usual nose style + moved to proper module
larsmans Oct 28, 2012
978bb22
BUG + COSMIT + ENH RBMs
larsmans Oct 28, 2012
5a0e69b
Merge pull request #1 from larsmans/rbm
Oct 28, 2012
8891e0e
use train_test_split
Jan 1, 2013
a71b6cc
Added RBM to whats_new.rst
vene Jan 2, 2013
79e1a79
Added skeleton for RBM documentation
vene Jan 2, 2013
561fb99
FIX mistake in rst
vene Jan 3, 2013
11abf87
Rename RestrictedBolzmannMachine to BernoulliRBM
vene Jan 3, 2013
28c0093
FIX: make BernoulliRBM doctest pass
vene Jan 4, 2013
d8efeb6
Merge branch 'master' into rbm-docs
vene Jan 4, 2013
8dd07d7
Rename also in whats_new
vene Jan 4, 2013
e48c39a
FIX: BernoulliRBM check random state in fit, not in init
vene Jan 4, 2013
c38ce39
FIX: validation in `BernoulliRBM.transform`
vene Jan 4, 2013
b665631
DOC: first attempt at RBM documentation
vene Jan 4, 2013
1dbecad
Link to RBM docs from the unsupervised toctree
vene Jan 4, 2013
9e77703
FIX: uneven RBM image
vene Jan 4, 2013
9b7f5a6
Merge https://github.com/scikit-learn/scikit-learn into rbm
Jan 4, 2013
a13a762
DOC: PCD details and references
vene Jan 5, 2013
2b5767a
Merge branch 'rbm-docs' of https://github.com/vene/scikit-learn into …
Jan 7, 2013
234b087
neural_networks -> neural_network
Feb 2, 2013
f8e0110
rename n_particles to batch_size
Feb 3, 2013
ad4877a
bugfix test
Apr 15, 2013
5400735
bugfix test
Apr 15, 2013
6dfc317
added tests
Apr 15, 2013
83daf31
tests
Apr 15, 2013
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added doc/images/rbm_graph.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
20 changes: 20 additions & 0 deletions doc/modules/classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -860,6 +860,26 @@ Pairwise metrics
neighbors.radius_neighbors_graph


.. _neural_network_ref:

:mod:`sklearn.neural_network`: Neural network models
=====================================================

.. automodule:: sklearn.neural_network
:no-members:
:no-inherited-members:

**User guide:** See the :ref:`neural_network` section for further details.

.. currentmodule:: sklearn

.. autosummary::
:toctree: generated/
:template: class.rst

neural_network.BernoulliRBM


.. _pls_ref:

:mod:`sklearn.pls`: Partial Least Squares
Expand Down
146 changes: 146 additions & 0 deletions doc/modules/neural_networks.rst
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.

Copy link
Copy Markdown
Member

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.


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
1 change: 1 addition & 0 deletions doc/unsupervised_learning.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ Unsupervised learning
modules/covariance
modules/outlier_detection
modules/hmm
modules/neural_network


3 changes: 3 additions & 0 deletions doc/whats_new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ Changelog
of ``class_weight`` was reversed as erroneously higher weight meant less
positives of a given class in earlier releases.

- New transformer :ref:`neural_network.BernoulliRBM`
by `Yann Dauphin`_.

API changes summary
-------------------
- Renamed all occurences of ``n_atoms`` to ``n_components`` for consistency.
Expand Down
87 changes: 87 additions & 0 deletions examples/rbm_logistic_classification.py
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)))
6 changes: 6 additions & 0 deletions sklearn/neural_network/__init__.py
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
Loading