
\c           @  sI  d  Z  d d l m Z d d l Z d d l Z d d l Z d d l m Z d d l Z	 d d l
 m Z d d l m Z m Z d d l m Z m Z m Z d d	 l m Z d d
 l m Z m Z m Z m Z d d l m Z m Z d d l m Z d d l m  Z  m! Z! m" Z" m# Z# d d d e% d d e% d e& d 	 Z' d d d d d e% d d d e% d e& d  Z( e& e& d e& d  Z) d d d d d d d e& d e& e& e& d  Z* d d d e% d d d e& e% d d d d e& d e& e& e& d  Z+ d e f d     YZ, d e e, f d     YZ- d e e, f d      YZ. d! e e, f d"     YZ/ d S(#   s    Dictionary learning
i(   t   print_functionN(   t   ceil(   t   linalgi   (   t   BaseEstimatort   TransformerMixin(   t   Parallelt   delayedt   effective_n_jobs(   t   zip(   t   check_arrayt   check_random_statet   gen_even_slicest   gen_batches(   t   randomized_svdt	   row_norms(   t   check_is_fitted(   t   Lassot   orthogonal_mp_gramt	   LassoLarst   Larst
   lasso_larsi  i    c         C  sr  |  j  d k r+ |  d d  t j f }  n  |  j \ } } | j d } | j d |  j d k r t d j | j |  j    n  | d k r | d k r t } t j | |  j	  } n  | d k rVt
 |  | } zn t j d d  } t d	 | d
 t d |
 d t d | d t d |  } | j | j	 |  j	 d | | j } Wd t j |   Xn| d k rt
 |  | } t d	 | d
 t d t d | d | d t d |  } | d k	 r| | _ n  | j | j	 |  j	 d |	 | j } nj| d k ryzt t j d d  } t d
 t d |
 d t d | d t |  d t d |  } | j | j	 |  j	 d | | j } Wd t j |   Xn | d k rt j |  t j t j |  | d  j	 } | rOt j | d d d | qOnv | d k r?| rt d   n  t d | d | d t |  d d d t |  d t d |  j	 } n t d |   | j  d  k rn| j | |  S| S(!   s	  Generic sparse coding

    Each column of the result is the solution to a Lasso problem.

    Parameters
    ----------
    X : array of shape (n_samples, n_features)
        Data matrix.

    dictionary : array of shape (n_components, n_features)
        The dictionary matrix against which to solve the sparse coding of
        the data. Some of the algorithms assume normalized rows.

    gram : None | array, shape=(n_components, n_components)
        Precomputed Gram matrix, dictionary * dictionary'
        gram can be None if method is 'threshold'.

    cov : array, shape=(n_components, n_samples)
        Precomputed covariance, dictionary * X'

    algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'}
        lars: uses the least angle regression method (linear_model.lars_path)
        lasso_lars: uses Lars to compute the Lasso solution
        lasso_cd: uses the coordinate descent method to compute the
        Lasso solution (linear_model.Lasso). lasso_lars will be faster if
        the estimated components are sparse.
        omp: uses orthogonal matching pursuit to estimate the sparse solution
        threshold: squashes to zero all coefficients less than regularization
        from the projection dictionary * data'

    regularization : int | float
        The regularization parameter. It corresponds to alpha when
        algorithm is 'lasso_lars', 'lasso_cd' or 'threshold'.
        Otherwise it corresponds to n_nonzero_coefs.

    init : array of shape (n_samples, n_components)
        Initialization value of the sparse code. Only used if
        `algorithm='lasso_cd'`.

    max_iter : int, 1000 by default
        Maximum number of iterations to perform if `algorithm='lasso_cd'`.

    copy_cov : boolean, optional
        Whether to copy the precomputed covariance matrix; if False, it may be
        overwritten.

    check_input : boolean, optional
        If False, the input arrays X and dictionary will not be checked.

    verbose : int
        Controls the verbosity; the higher, the more messages. Defaults to 0.

    positive: boolean
        Whether to enforce a positivity constraint on the sparse code.

        .. versionadded:: 0.20

    Returns
    -------
    code : array of shape (n_components, n_features)
        The sparse codes

    See also
    --------
    sklearn.linear_model.lars_path
    sklearn.linear_model.orthogonal_mp
    sklearn.linear_model.Lasso
    SparseCoder
    i   Ni    sR   Dictionary and X have different numbers of features:dictionary.shape: {} X.shape{}t   lasso_cdR   t   allt   ignoret   alphat   fit_interceptt   verboset	   normalizet
   precomputet   fit_patht   positivet   Xyt   max_itert
   warm_startt   check_inputt   larst   n_nonzero_coefst	   thresholdt   outt   omps:   Positive constraint not supported for "omp" coding method.t   Gramt   tolt   norms_squaredt   squaredt   copy_Xys]   Sparse coding method must be "lasso_lars" "lasso_cd",  "lasso", "threshold" or "omp", got %s.i   (   t   ndimt   npt   newaxist   shapet
   ValueErrort   formatt   Nonet   Falset   dott   Tt   floatt   seterrR   t   fitt   coef_R   t   TrueR   t   intt   signt   maximumt   abst   clipR   R   t   reshape(   t   Xt
   dictionaryt   gramt   covt	   algorithmt   regularizationt   copy_covt   initR    R"   R   R   t	   n_samplest
   n_featurest   n_componentsR   t   err_mgtR   t   new_codet   clfR#   (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyt   _sparse_encode   sr    I			#
c           sK  | r`  d k rE t   d d d d  t    d d d d   q` t     t       n    j \ } }  j d }  d k r  d k r t j   j   n   d k r  d k r t  t j    j   n   d k r"| 	 	 d k r=t t | d
 d  |  	 q=n | 	 	 d k r=d 	 n  t	 |
  d k s[ d k rt
     d  d  d 	 d  d  d  d t d | d  	} | St j | | f  } t t | t	 |
    } t d |
 d |            	 f
 d   | D  } x' t | |  D] \ } } | | | <q-W| S(   s  Sparse coding

    Each row of the result is the solution to a sparse coding problem.
    The goal is to find a sparse array `code` such that::

        X ~= code * dictionary

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

    Parameters
    ----------
    X : array of shape (n_samples, n_features)
        Data matrix

    dictionary : array of shape (n_components, n_features)
        The dictionary matrix against which to solve the sparse coding of
        the data. Some of the algorithms assume normalized rows for meaningful
        output.

    gram : array, shape=(n_components, n_components)
        Precomputed Gram matrix, dictionary * dictionary'

    cov : array, shape=(n_components, n_samples)
        Precomputed covariance, dictionary' * X

    algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'}
        lars: uses the least angle regression method (linear_model.lars_path)
        lasso_lars: uses Lars to compute the Lasso solution
        lasso_cd: uses the coordinate descent method to compute the
        Lasso solution (linear_model.Lasso). lasso_lars will be faster if
        the estimated components are sparse.
        omp: uses orthogonal matching pursuit to estimate the sparse solution
        threshold: squashes to zero all coefficients less than alpha from
        the projection dictionary * X'

    n_nonzero_coefs : int, 0.1 * n_features by default
        Number of nonzero coefficients to target in each column of the
        solution. This is only used by `algorithm='lars'` and `algorithm='omp'`
        and is overridden by `alpha` in the `omp` case.

    alpha : float, 1. by default
        If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
        penalty applied to the L1 norm.
        If `algorithm='threshold'`, `alpha` is the absolute value of the
        threshold below which coefficients will be squashed to zero.
        If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of
        the reconstruction error targeted. In this case, it overrides
        `n_nonzero_coefs`.

    copy_cov : boolean, optional
        Whether to copy the precomputed covariance matrix; if False, it may be
        overwritten.

    init : array of shape (n_samples, n_components)
        Initialization value of the sparse codes. Only used if
        `algorithm='lasso_cd'`.

    max_iter : int, 1000 by default
        Maximum number of iterations to perform if `algorithm='lasso_cd'`.

    n_jobs : int or None, optional (default=None)
        Number of parallel jobs to run.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    check_input : boolean, optional
        If False, the input arrays X and dictionary will not be checked.

    verbose : int, optional
        Controls the verbosity; the higher, the more messages. Defaults to 0.

    positive : boolean, optional
        Whether to enforce positivity when finding the encoding.

        .. versionadded:: 0.20

    Returns
    -------
    code : array of shape (n_samples, n_components)
        The sparse codes

    See also
    --------
    sklearn.linear_model.lars_path
    sklearn.linear_model.orthogonal_mp
    sklearn.linear_model.Lasso
    SparseCoder
    R   t   ordert   Ct   dtypet   float64i    R%   R#   R'   i
   i   g      ?RE   RF   RG   RH   RI   R    R"   R   R   t   n_jobsc         3  s   |  ] } t  t    |    d  k	 rA  d  d   | f n d   d 	 d  d  d  k	 rl  | n d  d  d t d  Vq d  S(   NRG   RH   RI   R    R"   R   (   R   RP   R3   R4   (   t   .0t
   this_slice(
   RB   RF   RH   RE   RC   RD   RI   R    R   RG   (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pys	   <genexpr>A  s   	N(   R#   R'   (   R	   R0   R3   R.   R5   R6   R4   t   mint   maxR   RP   t   emptyt   listR   R   R   (   RB   RC   RD   RE   RF   R$   R   RH   RI   R    RU   R"   R   R   RJ   RK   RL   t   codet   slicest
   code_viewsRW   t	   this_view(    (
   RB   RF   RH   RE   RC   RD   RI   R    R   RG   sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyt   sparse_encode   sN    ]"		'	c      	   C  s  t  |  } | j d } t |  } t j d |  | | f  \ }	 t j d |  | f  \ }
 t j d |  f  \ } |	 d |  | d |  } x9t |  D]+} |
 d |  d d  | f | | d d  f d | d	 t } t j | | | d d  f  |  d d  | f <| rSt j	 |  d d  | f d d d
 |  d d  | f n  | |  d d  | f  } | d k  rl| d k rt j j d  t j j   n | rt d  n  | j |  |  d d  | f <| rt j	 |  d d  | f d d d
 |  d d  | f n  d | | d d  f <| |  d d  | f  } |  d d  | f c | :<q |  d d  | f c | :<|
 d |  d d  | f | | d d  f d | d	 t } q W| r| |  d } |  | f S|  S(   s  Update the dense dictionary factor in place.

    Parameters
    ----------
    dictionary : array of shape (n_features, n_components)
        Value of the dictionary at the previous iteration.

    Y : array of shape (n_features, n_samples)
        Data matrix.

    code : array of shape (n_components, n_samples)
        Sparse coding of the data against which to optimize the dictionary.

    verbose:
        Degree of output the procedure will print.

    return_r2 : bool
        Whether to compute and return the residual sum of squares corresponding
        to the computed solution.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    positive : boolean, optional
        Whether to enforce positivity when finding the dictionary.

        .. versionadded:: 0.20

    Returns
    -------
    dictionary : array of shape (n_features, n_components)
        Updated dictionary.

    i    t   gemmt   gert   nrm2g      g      ?Nt   at   overwrite_aR&   g|=i   t   +s   Adding new random atomg        g       @(   Ra   (   Rb   (   Rc   (   t   lenR0   R
   R   t   get_blas_funcst   rangeR;   R.   R5   R@   R3   t   syst   stdoutt   writet   flusht   printt   randn(   RC   t   YR\   R   t	   return_r2t   random_stateR   RL   RK   Ra   Rb   Rc   t   Rt   kt	   atom_norm(    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyt   _update_dictP  s>    '>2<<B
id   g:0yE>R#   c         C  s  | d k r t  d |   n  d | } t j   } t |  } t |  } | d k	 r | d k	 r t j | d d } | } n; t j |  d t	 \ } } } | d d  t j
 f | } t |  } | | k r| d d  d |  f } | d |  d d  f } nY t j | t j t |  | | f  f } t j | t j | | | j d	 f  f } t j | d d } d
 } g  } t j } |
 d	 k rt d d d n  d } xt |  D]} t j   | } |
 d	 k rt j j d  t j j   n' |
 r/t d | | | d | f  n  t |  | d | d | d | d | d | } t | j |  j | j d |
 d t d | d | \ } } | j } d | | t j t j |   } | j |  | d
 k r8| d | d } | | | d k  r8|
 d	 k rt d  n |
 r1t d |  n  Pq8n  | d d
 k r|	 d k	 r|	 t    qqW| r| | | | d	 f S| | | f Sd S(    s9  Solves a dictionary learning matrix factorization problem.

    Finds the best dictionary and the corresponding sparse code for
    approximating the data matrix X by solving::

        (U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1
                     (U,V)
                    with || V_k ||_2 = 1 for all  0 <= k < n_components

    where V is the dictionary and U is the sparse code.

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

    Parameters
    ----------
    X : array of shape (n_samples, n_features)
        Data matrix.

    n_components : int,
        Number of dictionary atoms to extract.

    alpha : int,
        Sparsity controlling parameter.

    max_iter : int,
        Maximum number of iterations to perform.

    tol : float,
        Tolerance for the stopping condition.

    method : {'lars', 'cd'}
        lars: uses the least angle regression method to solve the lasso problem
        (linear_model.lars_path)
        cd: uses the coordinate descent method to compute the
        Lasso solution (linear_model.Lasso). Lars will be faster if
        the estimated components are sparse.

    n_jobs : int or None, optional (default=None)
        Number of parallel jobs to run.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    dict_init : array of shape (n_components, n_features),
        Initial value for the dictionary for warm restart scenarios.

    code_init : array of shape (n_samples, n_components),
        Initial value for the sparse code for warm restart scenarios.

    callback : callable or None, optional (default: None)
        Callable that gets invoked every five iterations

    verbose : bool, optional (default: False)
        To control the verbosity of the procedure.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    return_n_iter : bool
        Whether or not to return the number of iterations.

    positive_dict : bool
        Whether to enforce positivity when finding the dictionary.

        .. versionadded:: 0.20

    positive_code : bool
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

    Returns
    -------
    code : array of shape (n_samples, n_components)
        The sparse code factor in the matrix factorization.

    dictionary : array of shape (n_components, n_features),
        The dictionary factor in the matrix factorization.

    errors : array
        Vector of errors at each iteration.

    n_iter : int
        Number of iterations run. Returned only if `return_n_iter` is
        set to True.

    See also
    --------
    dict_learning_online
    DictionaryLearning
    MiniBatchDictionaryLearning
    SparsePCA
    MiniBatchSparsePCA
    R#   t   cds2   Coding method %r not supported as a fit algorithm.t   lasso_RQ   t   Ft   full_matricesNi   i    s   [dict_learning]t   endt    it   .sC   Iteration % 3i (elapsed time: % 3is, % 4.1fmn, current cost % 7.3f)i<   RF   R   RI   RU   R   R   Rq   Rr   g      ?it    s+   --- Convergence reached after %d iterationsi   (   R#   Rw   (   R1   t   timeR7   R
   R3   R.   t   arrayR   t   svdR4   R/   Rg   t   c_t   zerost   r_R0   t   nanRn   Ri   Rj   Rk   Rl   Rm   R`   Rv   R6   R;   t   sumR?   t   appendt   locals(   RB   RL   R   R    R)   t   methodRU   t	   dict_initt	   code_initt   callbackR   Rr   t   return_n_itert   positive_dictt   positive_codet   t0R\   RC   t   St   rt	   residualst   errorst   current_costt   iit   dtt   dE(    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyt   dict_learning  sp    f
	,	$		$i   i   c   &      C  s^  | d k r |  j d } n  | d" k r7 t d   n  d | } t j   } |  j \ } } t |  } t |  } | d k	 r | } n; t |  | d | \ } } } | d d  t j f | } t	 |  } | | k r | d |  d d  f } n- t j
 | t j | | | j d f  f } | d k rGt d d	 d
 n  |	 ri|  j   } | j |  n |  } t | j d d d t j d t } t j | d d } t | d d d t j d t } t | |  } t j |  } | d k r t j | | f  } t j | | f  } n  | d j   } | d j   } | d } xt t | | |  |  D]\ } } | | }  t j   | }! | d k rt j j d  t j j   nM | r| d k s| t d |  d k rt d | |! |! d f  qn  t |  | j d | d | d |
 d t d | j }" | | d k  r`t | d |  }# n t | d | d |  }# |# d | |# d }$ | |$ 9} | t j |" |" j  7} | |$ 9} | t j |  j |" j  7} t  | | | d | d | d | } | d k	 rg| t!    qgqgW| r_| rI| j | | f | | d f S| j | | f f Sn  | r8| d k rt d d	 d
 n | d k rt d  d	 d
 n  t |  | j d | d | d |
 d t d | }% | d k r
t j   | }! t d! |! |! d f  n  | r(|% | j | | d f S|% | j f Sn  | rS| j | | d f S| j Sd S(#   s  Solves a dictionary learning matrix factorization problem online.

    Finds the best dictionary and the corresponding sparse code for
    approximating the data matrix X by solving::

        (U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1
                     (U,V)
                     with || V_k ||_2 = 1 for all  0 <= k < n_components

    where V is the dictionary and U is the sparse code. This is
    accomplished by repeatedly iterating over mini-batches by slicing
    the input data.

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

    Parameters
    ----------
    X : array of shape (n_samples, n_features)
        Data matrix.

    n_components : int,
        Number of dictionary atoms to extract.

    alpha : float,
        Sparsity controlling parameter.

    n_iter : int,
        Number of iterations to perform.

    return_code : boolean,
        Whether to also return the code U or just the dictionary V.

    dict_init : array of shape (n_components, n_features),
        Initial value for the dictionary for warm restart scenarios.

    callback : callable or None, optional (default: None)
        callable that gets invoked every five iterations

    batch_size : int,
        The number of samples to take in each batch.

    verbose : bool, optional (default: False)
        To control the verbosity of the procedure.

    shuffle : boolean,
        Whether to shuffle the data before splitting it in batches.

    n_jobs : int or None, optional (default=None)
        Number of parallel jobs to run.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    method : {'lars', 'cd'}
        lars: uses the least angle regression method to solve the lasso problem
        (linear_model.lars_path)
        cd: uses the coordinate descent method to compute the
        Lasso solution (linear_model.Lasso). Lars will be faster if
        the estimated components are sparse.

    iter_offset : int, default 0
        Number of previous iterations completed on the dictionary used for
        initialization.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    return_inner_stats : boolean, optional
        Return the inner statistics A (dictionary covariance) and B
        (data approximation). Useful to restart the algorithm in an
        online setting. If return_inner_stats is True, return_code is
        ignored

    inner_stats : tuple of (A, B) ndarrays
        Inner sufficient statistics that are kept by the algorithm.
        Passing them at initialization is useful in online settings, to
        avoid loosing the history of the evolution.
        A (n_components, n_components) is the dictionary covariance matrix.
        B (n_features, n_components) is the data approximation matrix

    return_n_iter : bool
        Whether or not to return the number of iterations.

    positive_dict : bool
        Whether to enforce positivity when finding the dictionary.

        .. versionadded:: 0.20

    positive_code : bool
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

    Returns
    -------
    code : array of shape (n_samples, n_components),
        the sparse code (only returned if `return_code=True`)

    dictionary : array of shape (n_components, n_features),
        the solutions to the dictionary learning problem

    n_iter : int
        Number of iterations run. Returned only if `return_n_iter` is
        set to `True`.

    See also
    --------
    dict_learning
    DictionaryLearning
    MiniBatchDictionaryLearning
    SparsePCA
    MiniBatchSparsePCA

    i   R#   Rw   s/   Coding method not supported as a fit algorithm.Rx   Rr   Ns   [dict_learning]R{   R|   RQ   Ry   RS   t   copyt   requirementst   WRR   i    R}   i
   g      Y@s.   Iteration % 3i (elapsed time: % 3is, % 4.1fmn)i<   RF   R   RU   R"   R   i   R   s   Learning code...t   |s"   done (total time: % 3is, % 4.1fmn)(   R#   Rw   ("   R3   R0   R1   R   R7   R
   R   R.   R/   Rg   R   R   Rn   R   t   shuffleR	   R6   RT   R4   t   requireR   t	   itertoolst   cycleR   Ri   Rj   Rk   Rl   Rm   R   R`   R5   Rv   R   (&   RB   RL   R   t   n_itert   return_codeR   R   t
   batch_sizeR   R   RU   R   t   iter_offsetRr   t   return_inner_statst   inner_statsR   R   R   R   RJ   RK   RC   t   _R   R   t   X_traint   batchest   At   BR   t   batcht   this_XR   t	   this_codet   thetat   betaR\   (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyt   dict_learning_online]  s    |
		$	!
)
&

		t   SparseCodingMixinc           B  s2   e  Z d  Z d d d e d e d  Z d   Z RS(   s   Sparse coding mixinR'   c         C  sC   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ d  S(   N(   RL   t   transform_algorithmt   transform_n_nonzero_coefst   transform_alphat
   split_signRU   R   (   t   selfRL   R   R   R   R   RU   R   (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyt   _set_sparse_coding_paramsW  s    						c         C  s   t  |  d  t |  } t | |  j d |  j d |  j d |  j d |  j d |  j } |  j	 r | j
 \ } } t j | d | f  } t j | d  | d	 d	  d	 |  f <t j | d  | d	 d	  | d	  f <| } n  | S(
   s  Encode the data as a sparse combination of the dictionary atoms.

        Coding method is determined by the object parameter
        `transform_algorithm`.

        Parameters
        ----------
        X : array of shape (n_samples, n_features)
            Test data to be transformed, must have the same number of
            features as the data used to train the model.

        Returns
        -------
        X_new : array, shape (n_samples, n_components)
            Transformed data

        t   components_RF   R$   R   RU   R   i   i    N(   R   R	   R`   R   R   R   R   RU   R   R   R0   R.   RZ   R>   t   minimum(   R   RB   R\   RJ   RK   t
   split_code(    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyt	   transformd  s    		()	N(   t   __name__t
   __module__t   __doc__R3   R4   R   R   (    (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyR   T  s   	t   SparseCoderc           B  s>   e  Z d  Z d g Z d d d e d e d  Z d d  Z RS(   s
  Sparse coding

    Finds a sparse representation of data against a fixed, precomputed
    dictionary.

    Each row of the result is the solution to a sparse coding problem.
    The goal is to find a sparse array `code` such that::

        X ~= code * dictionary

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

    Parameters
    ----------
    dictionary : array, [n_components, n_features]
        The dictionary atoms used for sparse coding. Lines are assumed to be
        normalized to unit norm.

    transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp',     'threshold'}
        Algorithm used to transform the data:
        lars: uses the least angle regression method (linear_model.lars_path)
        lasso_lars: uses Lars to compute the Lasso solution
        lasso_cd: uses the coordinate descent method to compute the
        Lasso solution (linear_model.Lasso). lasso_lars will be faster if
        the estimated components are sparse.
        omp: uses orthogonal matching pursuit to estimate the sparse solution
        threshold: squashes to zero all coefficients less than alpha from
        the projection ``dictionary * X'``

    transform_n_nonzero_coefs : int, ``0.1 * n_features`` by default
        Number of nonzero coefficients to target in each column of the
        solution. This is only used by `algorithm='lars'` and `algorithm='omp'`
        and is overridden by `alpha` in the `omp` case.

    transform_alpha : float, 1. by default
        If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
        penalty applied to the L1 norm.
        If `algorithm='threshold'`, `alpha` is the absolute value of the
        threshold below which coefficients will be squashed to zero.
        If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of
        the reconstruction error targeted. In this case, it overrides
        `n_nonzero_coefs`.

    split_sign : bool, False by default
        Whether to split the sparse feature vector into the concatenation of
        its negative part and its positive part. This can improve the
        performance of downstream classifiers.

    n_jobs : int or None, optional (default=None)
        Number of parallel jobs to run.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    positive_code : bool
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

    Attributes
    ----------
    components_ : array, [n_components, n_features]
        The unchanged dictionary atoms

    See also
    --------
    DictionaryLearning
    MiniBatchDictionaryLearning
    SparsePCA
    MiniBatchSparsePCA
    sparse_encode
    RC   R'   c         C  s3   |  j  | j d | | | | | |  | |  _ d  S(   Ni    (   R   R0   R   (   R   RC   R   R   R   R   RU   R   (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyt   __init__  s    	c         C  s   |  S(   sF  Do nothing and return the estimator unchanged

        This method is just there to implement the usual API and hence
        work in pipelines.

        Parameters
        ----------
        X : Ignored

        y : Ignored

        Returns
        -------
        self : object
            Returns the object itself
        (    (   R   RB   t   y(    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyR9     s    N(   R   R   R   t   _required_parametersR3   R4   R   R9   (    (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyR     s   I	t   DictionaryLearningc           B  sS   e  Z d  Z d d d d d d d d d d d e e d e e d  Z d d  Z RS(	   s  Dictionary learning

    Finds a dictionary (a set of atoms) that can best be used to represent data
    using a sparse code.

    Solves the optimization problem::

        (U^*,V^*) = argmin 0.5 || Y - U V ||_2^2 + alpha * || U ||_1
                    (U,V)
                    with || V_k ||_2 = 1 for all  0 <= k < n_components

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

    Parameters
    ----------
    n_components : int,
        number of dictionary elements to extract

    alpha : float,
        sparsity controlling parameter

    max_iter : int,
        maximum number of iterations to perform

    tol : float,
        tolerance for numerical error

    fit_algorithm : {'lars', 'cd'}
        lars: uses the least angle regression method to solve the lasso problem
        (linear_model.lars_path)
        cd: uses the coordinate descent method to compute the
        Lasso solution (linear_model.Lasso). Lars will be faster if
        the estimated components are sparse.

        .. versionadded:: 0.17
           *cd* coordinate descent method to improve speed.

    transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp',     'threshold'}
        Algorithm used to transform the data
        lars: uses the least angle regression method (linear_model.lars_path)
        lasso_lars: uses Lars to compute the Lasso solution
        lasso_cd: uses the coordinate descent method to compute the
        Lasso solution (linear_model.Lasso). lasso_lars will be faster if
        the estimated components are sparse.
        omp: uses orthogonal matching pursuit to estimate the sparse solution
        threshold: squashes to zero all coefficients less than alpha from
        the projection ``dictionary * X'``

        .. versionadded:: 0.17
           *lasso_cd* coordinate descent method to improve speed.

    transform_n_nonzero_coefs : int, ``0.1 * n_features`` by default
        Number of nonzero coefficients to target in each column of the
        solution. This is only used by `algorithm='lars'` and `algorithm='omp'`
        and is overridden by `alpha` in the `omp` case.

    transform_alpha : float, 1. by default
        If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
        penalty applied to the L1 norm.
        If `algorithm='threshold'`, `alpha` is the absolute value of the
        threshold below which coefficients will be squashed to zero.
        If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of
        the reconstruction error targeted. In this case, it overrides
        `n_nonzero_coefs`.

    n_jobs : int or None, optional (default=None)
        Number of parallel jobs to run.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    code_init : array of shape (n_samples, n_components),
        initial value for the code, for warm restart

    dict_init : array of shape (n_components, n_features),
        initial values for the dictionary, for warm restart

    verbose : bool, optional (default: False)
        To control the verbosity of the procedure.

    split_sign : bool, False by default
        Whether to split the sparse feature vector into the concatenation of
        its negative part and its positive part. This can improve the
        performance of downstream classifiers.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    positive_code : bool
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

    positive_dict : bool
        Whether to enforce positivity when finding the dictionary

        .. versionadded:: 0.20

    Attributes
    ----------
    components_ : array, [n_components, n_features]
        dictionary atoms extracted from the data

    error_ : array
        vector of errors at each iteration

    n_iter_ : int
        Number of iterations run.

    Notes
    -----
    **References:**

    J. Mairal, F. Bach, J. Ponce, G. Sapiro, 2009: Online dictionary learning
    for sparse coding (http://www.di.ens.fr/sierra/pdfs/icml09.pdf)

    See also
    --------
    SparseCoder
    MiniBatchDictionaryLearning
    SparsePCA
    MiniBatchSparsePCA
    i   i  g:0yE>R#   R'   c         C  st   |  j  | | | | | |	 |  | |  _ | |  _ | |  _ | |  _ |
 |  _ | |  _ | |  _ | |  _ | |  _	 d  S(   N(
   R   R   R    R)   t   fit_algorithmR   R   R   Rr   R   (   R   RL   R   R    R)   R   R   R   R   RU   R   R   R   R   Rr   R   R   (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyR   u  s    									c         C  s   t  |  j  } t |  } |  j d k r: | j d } n	 |  j } t | | |  j d |  j d |  j	 d |  j
 d |  j d |  j d |  j d |  j d	 | d
 t d |  j d |  j \ } } } |  _ | |  _ | |  _ |  S(   sq  Fit the model from data in X.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training vector, where n_samples in the number of samples
            and n_features is the number of features.

        y : Ignored

        Returns
        -------
        self : object
            Returns the object itself
        i   R)   R    R   RU   R   R   R   Rr   R   R   R   N(   R
   Rr   R	   RL   R3   R0   R   R   R)   R    R   RU   R   R   R   R;   R   R   t   n_iter_R   t   error_(   R   RB   R   Rr   RL   t   Vt   Ut   E(    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyR9     s(    									N(   R   R   R   R3   R4   R   R9   (    (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyR     s   t   MiniBatchDictionaryLearningc           B  sb   e  Z d  Z d	 d d d d	 d e d	 d d	 d	 e e d	 e e d  Z d	 d  Z d	 d	 d  Z RS(
   sr  Mini-batch dictionary learning

    Finds a dictionary (a set of atoms) that can best be used to represent data
    using a sparse code.

    Solves the optimization problem::

       (U^*,V^*) = argmin 0.5 || Y - U V ||_2^2 + alpha * || U ||_1
                    (U,V)
                    with || V_k ||_2 = 1 for all  0 <= k < n_components

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

    Parameters
    ----------
    n_components : int,
        number of dictionary elements to extract

    alpha : float,
        sparsity controlling parameter

    n_iter : int,
        total number of iterations to perform

    fit_algorithm : {'lars', 'cd'}
        lars: uses the least angle regression method to solve the lasso problem
        (linear_model.lars_path)
        cd: uses the coordinate descent method to compute the
        Lasso solution (linear_model.Lasso). Lars will be faster if
        the estimated components are sparse.

    n_jobs : int or None, optional (default=None)
        Number of parallel jobs to run.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    batch_size : int,
        number of samples in each mini-batch

    shuffle : bool,
        whether to shuffle the samples before forming batches

    dict_init : array of shape (n_components, n_features),
        initial value of the dictionary for warm restart scenarios

    transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp',     'threshold'}
        Algorithm used to transform the data.
        lars: uses the least angle regression method (linear_model.lars_path)
        lasso_lars: uses Lars to compute the Lasso solution
        lasso_cd: uses the coordinate descent method to compute the
        Lasso solution (linear_model.Lasso). lasso_lars will be faster if
        the estimated components are sparse.
        omp: uses orthogonal matching pursuit to estimate the sparse solution
        threshold: squashes to zero all coefficients less than alpha from
        the projection dictionary * X'

    transform_n_nonzero_coefs : int, ``0.1 * n_features`` by default
        Number of nonzero coefficients to target in each column of the
        solution. This is only used by `algorithm='lars'` and `algorithm='omp'`
        and is overridden by `alpha` in the `omp` case.

    transform_alpha : float, 1. by default
        If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
        penalty applied to the L1 norm.
        If `algorithm='threshold'`, `alpha` is the absolute value of the
        threshold below which coefficients will be squashed to zero.
        If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of
        the reconstruction error targeted. In this case, it overrides
        `n_nonzero_coefs`.

    verbose : bool, optional (default: False)
        To control the verbosity of the procedure.

    split_sign : bool, False by default
        Whether to split the sparse feature vector into the concatenation of
        its negative part and its positive part. This can improve the
        performance of downstream classifiers.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    positive_code : bool
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

    positive_dict : bool
        Whether to enforce positivity when finding the dictionary.

        .. versionadded:: 0.20

    Attributes
    ----------
    components_ : array, [n_components, n_features]
        components extracted from the data

    inner_stats_ : tuple of (A, B) ndarrays
        Internal sufficient statistics that are kept by the algorithm.
        Keeping them is useful in online settings, to avoid loosing the
        history of the evolution, but they shouldn't have any use for the
        end user.
        A (n_components, n_components) is the dictionary covariance matrix.
        B (n_features, n_components) is the data approximation matrix

    n_iter_ : int
        Number of iterations run.

    Notes
    -----
    **References:**

    J. Mairal, F. Bach, J. Ponce, G. Sapiro, 2009: Online dictionary learning
    for sparse coding (http://www.di.ens.fr/sierra/pdfs/icml09.pdf)

    See also
    --------
    SparseCoder
    DictionaryLearning
    SparsePCA
    MiniBatchSparsePCA

    i   i  R#   i   R'   c         C  s}   |  j  | |	 |
 | | | |  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _	 | |  _
 d  S(   N(   R   R   R   R   R   R   R   R   R   Rr   R   (   R   RL   R   R   R   RU   R   R   R   R   R   R   R   R   Rr   R   R   (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyR   2  s    										c         C  s   t  |  j  } t |  } t | |  j |  j d |  j d t d |  j d |  j	 d |  j
 d |  j d |  j d |  j d	 | d
 t d t d |  j d |  j \ } \ } } |  _ | |  _ | | f |  _ |  j |  _ |  S(   st  Fit the model from data in X.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training vector, where n_samples in the number of samples
            and n_features is the number of features.

        y : Ignored

        Returns
        -------
        self : object
            Returns the instance itself.
        R   R   R   RU   R   R   R   R   Rr   R   R   R   R   (   R
   Rr   R	   R   RL   R   R   R4   R   RU   R   R   R   R   R;   R   R   R   R   t   inner_stats_t   iter_offset_(   R   RB   R   Rr   R   R   R   (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyR9   H  s"    			c   	       C  sF  t  |  d  s$ t |  j  |  _ n  t |  } t  |  d  rK |  j } n	 |  j } t |  d d  } | d k r t |  d d  } n  t	 | |  j
 |  j d |  j d |  j d |  j d	 | d
 t |  d t d |  j d t d | d |  j d t d | d |  j d |  j \ } \ } } | |  _ | | f |  _ | |  j |  _ |  S(   s  Updates the model using the data in X as a mini-batch.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training vector, where n_samples in the number of samples
            and n_features is the number of features.

        y : Ignored

        iter_offset : integer, optional
            The number of iteration on data batches that has been
            performed before this call to partial_fit. This is optional:
            if no number is passed, the memory of the object is
            used.

        Returns
        -------
        self : object
            Returns the instance itself.
        t   random_state_R   R   R   i    R   R   RU   R   R   R   R   R   R   Rr   R   R   R   R   N(   t   hasattrR
   Rr   R   R	   R   R   t   getattrR3   R   RL   R   R   R   RU   Rg   R4   R   R;   R   R   R   R   (	   R   RB   R   R   R   R   R   R   R   (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyt   partial_fitm  s.    			N(	   R   R   R   R3   R;   R4   R   R9   R   (    (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyR     s   				%(0   R   t
   __future__R    R   Rj   R   t   mathR   t   numpyR.   t   scipyR   t   baseR   R   t   utils._joblibR   R   R   t   externals.six.movesR   t   utilsR	   R
   R   R   t   utils.extmathR   R   t   utils.validationR   t   linear_modelR   R   R   R   R3   R;   R4   RP   R`   Rv   R   R   R   R   R   R   (    (    (    sB   lib/python2.7/site-packages/sklearn/decomposition/dict_learning.pyt   <module>   sP   ""	R					7j