ó
‡ˆ\c           @   sê   d  Z  d d l Z d d l Z d d l j Z d d l m Z d d l	 m
 Z
 d d l	 m Z d d l m Z d d l m Z d d	 l m Z d d
 l m Z d d l m Z d d l m Z d d l m Z d e
 e f d „  ƒ  YZ d S(   s   Restricted Boltzmann Machine
iÿÿÿÿN(   t   expiti   (   t   BaseEstimator(   t   TransformerMixin(   t   xrange(   t   check_array(   t   check_random_state(   t   gen_even_slices(   t   safe_sparse_dot(   t   log_logistic(   t   check_is_fittedt   BernoulliRBMc           B   s‰   e  Z d  Z d d d d d d d „ Z d „  Z d „  Z d „  Z d	 „  Z d
 „  Z	 d „  Z
 d d „ Z d „  Z d „  Z d d „ Z RS(   s¾	  Bernoulli Restricted Boltzmann Machine (RBM).

    A Restricted Boltzmann Machine with binary visible units and
    binary hidden units. Parameters are estimated using Stochastic Maximum
    Likelihood (SML), also known as Persistent Contrastive Divergence (PCD)
    [2].

    The time complexity of this implementation is ``O(d ** 2)`` assuming
    d ~ n_features ~ n_components.

    Read more in the :ref:`User Guide <rbm>`.

    Parameters
    ----------
    n_components : int, optional
        Number of binary hidden units.

    learning_rate : float, optional
        The learning rate for weight updates. It is *highly* recommended
        to tune this hyper-parameter. Reasonable values are in the
        10**[0., -3.] range.

    batch_size : int, optional
        Number of examples per minibatch.

    n_iter : int, optional
        Number of iterations/sweeps over the training dataset to perform
        during training.

    verbose : int, optional
        The verbosity level. The default, zero, means silent mode.

    random_state : integer or RandomState, optional
        A random number generator instance to define the state of the
        random permutations generator. If an integer is given, it fixes the
        seed. Defaults to the global numpy random number generator.

    Attributes
    ----------
    intercept_hidden_ : array-like, shape (n_components,)
        Biases of the hidden units.

    intercept_visible_ : array-like, shape (n_features,)
        Biases of the visible units.

    components_ : array-like, shape (n_components, n_features)
        Weight matrix, where n_features in the number of
        visible units and n_components is the number of hidden units.

    Examples
    --------

    >>> import numpy as np
    >>> from sklearn.neural_network import BernoulliRBM
    >>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
    >>> model = BernoulliRBM(n_components=2)
    >>> model.fit(X)
    BernoulliRBM(batch_size=10, learning_rate=0.1, n_components=2, n_iter=10,
           random_state=None, verbose=0)

    References
    ----------

    [1] Hinton, G. E., Osindero, S. and Teh, Y. A fast learning algorithm for
        deep belief nets. Neural Computation 18, pp 1527-1554.
        https://www.cs.toronto.edu/~hinton/absps/fastnc.pdf

    [2] Tieleman, T. Training Restricted Boltzmann Machines using
        Approximations to the Likelihood Gradient. International Conference
        on Machine Learning (ICML) 2008
    i   gš™™™™™¹?i
   i    c         C   s:   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ d  S(   N(   t   n_componentst   learning_ratet
   batch_sizet   n_itert   verboset   random_state(   t   selfR   R   R   R   R   R   (    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyt   __init__c   s    					c         C   s5   t  |  d ƒ t | d d d t j ƒ} |  j | ƒ S(   s`  Compute the hidden layer activation probabilities, P(h=1|v=X).

        Parameters
        ----------
        X : {array-like, sparse matrix} shape (n_samples, n_features)
            The data to be transformed.

        Returns
        -------
        h : array, shape (n_samples, n_components)
            Latent representations of the data.
        t   components_t   accept_sparset   csrt   dtype(   R	   R   t   npt   float64t   _mean_hiddens(   R   t   X(    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyt	   transforml   s    c         C   s2   t  | |  j j ƒ } | |  j 7} t | d | ƒS(   sN  Computes the probabilities P(h=1|v).

        Parameters
        ----------
        v : array-like, shape (n_samples, n_features)
            Values of the visible layer.

        Returns
        -------
        h : array-like, shape (n_samples, n_components)
            Corresponding mean field values for the hidden layer.
        t   out(   R   R   t   Tt   intercept_hidden_R    (   R   t   vt   p(    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyR   ~   s    c         C   s(   |  j  | ƒ } | j d | j ƒ | k  S(   sŠ  Sample from the distribution P(h|v).

        Parameters
        ----------
        v : array-like, shape (n_samples, n_features)
            Values of the visible layer to sample from.

        rng : RandomState
            Random number generator to use.

        Returns
        -------
        h : array-like, shape (n_samples, n_components)
            Values of the hidden layer.
        t   size(   R   t   random_samplet   shape(   R   R   t   rngR    (    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyt   _sample_hiddens   s    c         C   sK   t  j | |  j ƒ } | |  j 7} t | d | ƒ| j d | j ƒ | k  S(   sŠ  Sample from the distribution P(v|h).

        Parameters
        ----------
        h : array-like, shape (n_samples, n_components)
            Values of the hidden layer to sample from.

        rng : RandomState
            Random number generator to use.

        Returns
        -------
        v : array-like, shape (n_samples, n_features)
            Values of the visible layer.
        R   R!   (   R   t   dotR   t   intercept_visible_R    R"   R#   (   R   t   hR$   R    (    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyt   _sample_visibles¢   s    c         C   sC   t  | |  j ƒ t j d t  | |  j j ƒ |  j ƒ j d d ƒ S(   sH  Computes the free energy F(v) = - log sum_h exp(-E(v,h)).

        Parameters
        ----------
        v : array-like, shape (n_samples, n_features)
            Values of the visible layer.

        Returns
        -------
        free_energy : array-like, shape (n_samples,)
            The value of the free energy.
        i    t   axisi   (   R   R'   R   t	   logaddexpR   R   R   t   sum(   R   R   (    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyt   _free_energy·   s    c         C   s_   t  |  d ƒ t |  d ƒ s1 t |  j ƒ |  _ n  |  j | |  j ƒ } |  j | |  j ƒ } | S(   sV  Perform one Gibbs sampling step.

        Parameters
        ----------
        v : array-like, shape (n_samples, n_features)
            Values of the visible layer to start from.

        Returns
        -------
        v_new : array-like, shape (n_samples, n_features)
            Values of the visible layer after one Gibbs step.
        R   t   random_state_(   R	   t   hasattrR   R   R.   R%   R)   (   R   R   t   h_t   v_(    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyt   gibbsÈ   s    c         C   s$  t  | d d d t j ƒ} t |  d ƒ s? t |  j ƒ |  _ n  t |  d ƒ s‹ t j |  j j d d |  j	 | j
 d f ƒ d	 d
 ƒ|  _ n  t |  d ƒ s² t j |  j	 ƒ |  _ n  t |  d ƒ sÝ t j | j
 d ƒ |  _ n  t |  d ƒ st j |  j |  j	 f ƒ |  _ n  |  j | |  j ƒ d S(   s3  Fit the model to the data X which should contain a partial
        segment of the data.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training data.

        Returns
        -------
        self : BernoulliRBM
            The fitted model.
        R   R   R   R.   R   i    g{®Gáz„?i   t   ordert   FR   R'   t
   h_samples_N(   R   R   R   R/   R   R   R.   t   asarrayt   normalR   R#   R   t   zerosR   R'   R   R5   t   _fit(   R   R   t   y(    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyt   partial_fitÝ   s"    	!c         C   s9  |  j  | ƒ } |  j |  j | ƒ } |  j  | ƒ } t |  j ƒ | j d } t | j | d t ƒj } | t	 j
 | j | ƒ 8} |  j | | 7_ |  j | | j d d ƒ | j d d ƒ 7_ |  j | t	 j | j d d ƒ ƒ j ƒ  | j d d ƒ 7_ d | | j d | j ƒ | k  <t	 j | | ƒ |  _ d S(   sw  Inner fit for one mini-batch.

        Adjust the parameters to maximize the likelihood of v using
        Stochastic Maximum Likelihood (SML).

        Parameters
        ----------
        v_pos : array-like, shape (n_samples, n_features)
            The data to use for training.

        rng : RandomState
            Random number generator to use for sampling.
        i    t   dense_outputR*   g      ð?R!   N(   R   R)   R5   t   floatR   R#   R   R   t   TrueR   R&   R   R   R,   R'   R6   t   squeezet   uniformt   floor(   R   t   v_posR$   t   h_post   v_negt   h_negt   lrt   update(    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyR9   ÿ   s    /c   	      C   s  t  |  d ƒ t | d d ƒ} t |  j ƒ } t j | j d ƒ | j d | j d | j d ƒ f } t j	 | ƒ r¶ d | | d } | t j
 | j j ƒ  | f d | j ƒ} n | j ƒ  } d | | | | <|  j | ƒ } |  j | ƒ } | j d t | | ƒ S(   sz  Compute the pseudo-likelihood of X.

        Parameters
        ----------
        X : {array-like, sparse matrix} shape (n_samples, n_features)
            Values of the visible layer. Must be all-boolean (not checked).

        Returns
        -------
        pseudo_likelihood : array-like, shape (n_samples,)
            Value of the pseudo-likelihood (proxy for likelihood).

        Notes
        -----
        This method is not deterministic: it computes a quantity called the
        free energy on X, then on a randomly corrupted version of X, and
        returns the log of the logistic function of the difference.
        R   R   R   i    i   iþÿÿÿR#   (   R	   R   R   R   R   t   arangeR#   t   randintt   spt   issparset
   csr_matrixt   At   ravelt   copyR-   R   (	   R   R   R   R$   t   indt   dataR1   t   fet   fe_(    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyt   score_samples  s    &.c         C   s¦  t  | d d d t j ƒ} | j d } t |  j ƒ } t j | j d d |  j | j d f ƒ d d ƒ|  _	 t j
 |  j ƒ |  _ t j
 | j d ƒ |  _ t j
 |  j |  j f ƒ |  _ t t j t | ƒ |  j ƒ ƒ } t t | |  j | | ƒ ƒ } |  j } t j ƒ  } x t d |  j d ƒ D]w }	 x" | D] }
 |  j | |
 | ƒ q4W| r't j ƒ  } d	 t |  ƒ j |	 |  j | ƒ j ƒ  | | f GH| } q'q'W|  S(
   s  Fit the model to the data X.

        Parameters
        ----------
        X : {array-like, sparse matrix} shape (n_samples, n_features)
            Training data.

        Returns
        -------
        self : BernoulliRBM
            The fitted model.
        R   R   R   i    g{®Gáz„?i   R3   R4   s9   [%s] Iteration %d, pseudo-likelihood = %.2f, time = %.2fs(   R   R   R   R#   R   R   R6   R7   R   R   R8   R   R'   R   R5   t   intt   ceilR=   t   listR   R   t   timeR   R   R9   t   typet   __name__RT   t   mean(   R   R   R:   t	   n_samplesR$   t	   n_batchest   batch_slicesR   t   begint	   iterationt   batch_slicet   end(    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyt   fitC  s0    %"	N(   RZ   t
   __module__t   __doc__t   NoneR   R   R   R%   R)   R-   R2   R;   R9   RT   Rc   (    (    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyR
      s   G							"		&(   Re   RX   t   numpyR   t   scipy.sparset   sparseRJ   t   scipy.specialR    t   baseR   R   t   externals.six.movesR   t   utilsR   R   R   t   utils.extmathR   R   t   utils.validationR	   R
   (    (    (    s9   lib/python2.7/site-packages/sklearn/neural_network/rbm.pyt   <module>   s   