ó
¾÷Xc           @@  s¦   d  d l  m Z d  d l Z d  d l Z d  d l Z d  d l Z d d l m Z d d l	 m
 Z
 d e f d „  ƒ  YZ d e f d	 „  ƒ  YZ d
 e f d „  ƒ  YZ d S(   i    (   t   absolute_importNi   (   t   to_categorical(   t
   Sequentialt   BaseWrapperc           B@  sJ   e  Z d  Z d d „ Z d „  Z d „  Z d „  Z d „  Z d d „ Z	 RS(   s8  Base class for the Keras scikit-learn wrapper.

    Warning: This class should not be used directly.
    Use descendant classes instead.

    # Arguments
        build_fn: callable function or class instance
        **sk_params: model parameters & fitting parameters

    The build_fn should construct, compile and return a Keras model, which
    will then be used to fit/predict. One of the following
    three values could be passed to build_fn:
    1. A function
    2. An instance of a class that implements the __call__ method
    3. None. This means you implement a class that inherits from either
    `KerasClassifier` or `KerasRegressor`. The __call__ method of the
    present class will then be treated as the default build_fn.

    `sk_params` takes both model parameters and fitting parameters. Legal model
    parameters are the arguments of `build_fn`. Note that like all other
    estimators in scikit-learn, 'build_fn' should provide default values for
    its arguments, so that you could create the estimator without passing any
    values to `sk_params`.

    `sk_params` could also accept parameters for calling `fit`, `predict`,
    `predict_proba`, and `score` methods (e.g., `epochs`, `batch_size`).
    fitting (predicting) parameters are selected in the following order:

    1. Values passed to the dictionary arguments of
    `fit`, `predict`, `predict_proba`, and `score` methods
    2. Values passed to `sk_params`
    3. The default values of the `keras.models.Sequential`
    `fit`, `predict`, `predict_proba` and `score` methods

    When using scikit-learn's `grid_search` API, legal tunable parameters are
    those you could pass to `sk_params`, including fitting parameters.
    In other words, you could use `grid_search` to search for the best
    `batch_size` or `epochs` as well as the model parameters.
    c         K@  s#   | |  _  | |  _ |  j | ƒ d  S(   N(   t   build_fnt	   sk_paramst   check_params(   t   selfR   R   (    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyt   __init__6   s    		c         C@  s  t  j t  j t  j t  j g } |  j d k r@ | j |  j ƒ nR t	 |  j t
 j ƒ r‚ t	 |  j t
 j ƒ r‚ | j |  j j ƒ n | j |  j ƒ g  } x% | D] } | t j | ƒ d 7} qŸ Wt | ƒ } xA | D]9 } | | k rÓ | d k rt d j | ƒ ƒ ‚ qqÓ qÓ Wd S(   sÚ   Checks for user typos in "params".

        # Arguments
            params: dictionary; the parameters to be checked

        # Raises
            ValueError: if any member of `params` is not a valid argument.
        i    t   nb_epochs   {} is not a legal parameterN(   R   t   fitt   predictt   predict_classest   evaluateR   t   Nonet   appendt   __call__t
   isinstancet   typest   FunctionTypet
   MethodTypet   inspectt
   getargspect   sett
   ValueErrort   format(   R   t   paramst   legal_params_fnst   legal_paramst   fnt   params_name(    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyR   ;   s"    	c         K@  s-   t  j |  j ƒ } | j i |  j d 6ƒ | S(   sÓ   Gets parameters for this estimator.

        # Arguments
            **params: ignored (exists for API compatiblity).

        # Returns
            Dictionary of parameter names mapped to their values.
        R   (   t   copyt   deepcopyR   t   updateR   (   R   R   t   res(    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyt
   get_paramsY   s    	c         K@  s!   |  j  | ƒ |  j j | ƒ |  S(   s´   Sets the parameters of this estimator.

        # Arguments
            **params: Dictionary of parameter names mapped to their values.

        # Returns
            self
        (   R   R   R!   (   R   R   (    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyt
   set_paramsf   s    	c         K@  s9  |  j  d k r0 |  j |  j |  j ƒ   |  _ nn t |  j  t j ƒ r€ t |  j  t j ƒ r€ |  j  |  j |  j  j ƒ   |  _ n |  j  |  j |  j  ƒ   |  _ |  j j	 } t
 | d ƒ rÅ | j } n  | d k rõ t | j ƒ d k rõ t | ƒ } n  t j |  j t j ƒ ƒ } | j | ƒ |  j j | | |  } | S(   st  Constructs a new model with `build_fn` & fit the model to `(x, y)`.

        # Arguments
            x : array-like, shape `(n_samples, n_features)`
                Training samples where n_samples in the number of samples
                and n_features is the number of features.
            y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`
                True labels for X.
            **kwargs: dictionary arguments
                Legal arguments are the arguments of `Sequential.fit`

        # Returns
            history : object
                details about the training history at each epoch.
        t   __name__t   categorical_crossentropyi   N(   R   R   R   t   filter_sk_paramst   modelR   R   R   R   t   losst   hasattrR%   t   lent   shapeR   R   R    R   R
   R!   (   R   t   xt   yt   kwargst	   loss_namet   fit_argst   history(    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyR
   s   s     !!c         C@  sy   | p	 i  } i  } t  j | ƒ d } x@ |  j j ƒ  D]/ \ } } | | k r5 | j i | | 6ƒ q5 q5 W| j | ƒ | S(   s@  Filters `sk_params` and return those in `fn`'s arguments.

        # Arguments
            fn : arbitrary function
            override: dictionary, values to override sk_params

        # Returns
            res : dictionary dictionary containing variables
                in both sk_params and fn's arguments.
        i    (   R   R   R   t   itemsR!   (   R   R   t   overrideR"   t   fn_argst   namet   value(    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyR'   ™   s    N(
   R%   t
   __module__t   __doc__R   R   R   R#   R$   R
   R'   (    (    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyR      s   '				&t   KerasClassifierc           B@  s2   e  Z d  Z d „  Z d „  Z d „  Z d „  Z RS(   sA   Implementation of the scikit-learn classifier API for Keras.
    c         K@  s•   t  j | ƒ } t | j ƒ d k r@ t  j | j d ƒ |  _ n' t  j | ƒ |  _ t  j |  j | ƒ } t |  j ƒ |  _ t	 t
 |  ƒ j | | |  S(   st  Constructs a new model with `build_fn` & fit the model to `(x, y)`.

        # Arguments
            x : array-like, shape `(n_samples, n_features)`
                Training samples where n_samples in the number of samples
                and n_features is the number of features.
            y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`
                True labels for X.
            **kwargs: dictionary arguments
                Legal arguments are the arguments of `Sequential.fit`

        # Returns
            history : object
                details about the training history at each epoch.
        i   (   t   npt   arrayR+   R,   t   aranget   classes_t   uniquet   searchsortedt
   n_classes_t   superR:   R
   (   R   R-   R.   R/   (    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyR
   ²   s    c         K@  s5   |  j  t j | ƒ } |  j j | |  } |  j | S(   s  Returns the class predictions for the given test data.

        # Arguments
            x: array-like, shape `(n_samples, n_features)`
                Test samples where n_samples in the number of samples
                and n_features is the number of features.
            **kwargs: dictionary arguments
                Legal arguments are the arguments
                of `Sequential.predict_classes`.

        # Returns
            preds: array-like, shape `(n_samples,)`
                Class predictions.
        (   R'   R   R   R(   R>   (   R   R-   R/   t   classes(    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyR   Ë   s    c         K@  s]   |  j  t j | ƒ } |  j j | |  } | j d d k rY t j d | | g ƒ } n  | S(   sÿ  Returns class probability estimates for the given test data.

        # Arguments
            x: array-like, shape `(n_samples, n_features)`
                Test samples where n_samples in the number of samples
                and n_features is the number of features.
            **kwargs: dictionary arguments
                Legal arguments are the arguments
                of `Sequential.predict_classes`.

        # Returns
            proba: array-like, shape `(n_samples, n_outputs)`
                Class probability estimates.
                In the case of binary classification,
                tp match the scikit-learn API,
                will return an array of shape '(n_samples, 2)'
                (instead of `(n_sample, 1)` as in Keras).
        i   (   R'   R   t   predict_probaR(   R,   R;   t   hstack(   R   R-   R/   t   probs(    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyRD   Þ   s
    c         K@  sú   t  j |  j | ƒ } |  j t j | ƒ } |  j j } t | d ƒ rQ | j	 } n  | d k r t
 | j ƒ d k r t | ƒ } n  |  j j | | |  } t | t ƒ s´ | g } n  x3 t |  j j | ƒ D] \ } } | d k rÊ | SqÊ Wt d ƒ ‚ d S(   s9  Returns the mean accuracy on the given test data and labels.

        # Arguments
            x: array-like, shape `(n_samples, n_features)`
                Test samples where n_samples in the number of samples
                and n_features is the number of features.
            y: array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`
                True labels for x.
            **kwargs: dictionary arguments
                Legal arguments are the arguments of `Sequential.evaluate`.

        # Returns
            score: float
                Mean accuracy of predictions on X wrt. y.

        # Raises
            ValueError: If the underlying model isn't configured to
                compute accuracy. You should pass `metrics=["accuracy"]` to
                the `.compile()` method of the model.
        R%   R&   i   t   accsx   The model is not configured to compute accuracy. You should pass `metrics=["accuracy"]` to the `model.compile()` method.N(   R;   R@   R>   R'   R   R   R(   R)   R*   R%   R+   R,   R   R   t   listt   zipt   metrics_namesR   (   R   R-   R.   R/   R0   t   outputsR6   t   output(    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyt   scoreú   s    !"(   R%   R8   R9   R
   R   RD   RM   (    (    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyR:   ®   s
   			t   KerasRegressorc           B@  s    e  Z d  Z d „  Z d „  Z RS(   s@   Implementation of the scikit-learn regressor API for Keras.
    c         K@  s1   |  j  t j | ƒ } t j |  j j | |  ƒ S(   sß  Returns predictions for the given test data.

        # Arguments
            x: array-like, shape `(n_samples, n_features)`
                Test samples where n_samples in the number of samples
                and n_features is the number of features.
            **kwargs: dictionary arguments
                Legal arguments are the arguments of `Sequential.predict`.

        # Returns
            preds: array-like, shape `(n_samples,)`
                Predictions.
        (   R'   R   R   R;   t   squeezeR(   (   R   R-   R/   (    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyR   '  s    c         K@  sH   |  j  t j | ƒ } |  j j | | |  } t | t ƒ rD | d S| S(   sA  Returns the mean loss on the given test data and labels.

        # Arguments
            x: array-like, shape `(n_samples, n_features)`
                Test samples where n_samples in the number of samples
                and n_features is the number of features.
            y: array-like, shape `(n_samples,)`
                True labels for X.
            **kwargs: dictionary arguments
                Legal arguments are the arguments of `Sequential.evaluate`.

        # Returns
            score: float
                Mean accuracy of predictions on X wrt. y.
        i    (   R'   R   R   R(   R   RH   (   R   R-   R.   R/   R)   (    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyRM   8  s
    (   R%   R8   R9   R   RM   (    (    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyRN   #  s   	(   t
   __future__R    R   R   R   t   numpyR;   t   utils.np_utilsR   t   modelsR   t   objectR   R:   RN   (    (    (    s:   /tmp/pip-build-isqEY4/keras/keras/wrappers/scikit_learn.pyt   <module>   s   ¡u