B
    d!:                 @   s   d 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dl
mZ ddlmZ ddlmZ ddlmZ G d	d
 d
ZedejG dd deZedejG dd deZdS )z9Wrapper for using the Scikit-Learn API with Keras models.    N)losses)
Sequential)has_arg)to_categorical)keras_export)doc_controlsc               @   sD   e Zd ZdZdddZdd Zdd Zd	d
 Zdd ZdddZ	dS )BaseWrappera   Base class for the Keras scikit-learn wrapper.

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

    Args:
        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` 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.
    Nc             K   s   || _ || _| | d S )N)build_fn	sk_paramscheck_params)selfr	   r
    r   M/var/www/html/venv/lib/python3.7/site-packages/keras/wrappers/scikit_learn.py__init__K   s    zBaseWrapper.__init__c             C   s   t jt jt jg}| jdkr(|| j n8t| jtj	sTt| jtj
sT|| jj n|| j x<|D ]4}x.|D ]}t||rpP qpW |dkrft| dqfW dS )zChecks for user typos in `params`.

        Args:
            params: dictionary; the parameters to be checked

        Raises:
            ValueError: if any member of `params` is not a valid argument.
        NZnb_epochz is not a legal parameter)r   fitpredictevaluater	   append__call__
isinstancetypesFunctionType
MethodTyper   
ValueError)r   paramsZlegal_params_fnsZparams_namefnr   r   r   r   P   s"    




zBaseWrapper.check_paramsc             K   s   | j  }|d| ji |S )zGets parameters for this estimator.

        Args:
            **params: ignored (exists for API compatibility).

        Returns:
            Dictionary of parameter names mapped to their values.
        r	   )r
   copyupdater	   )r   r   resr   r   r   
get_paramsq   s    	
zBaseWrapper.get_paramsc             K   s   |  | | j| | S )zSets the parameters of this estimator.

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

        Returns:
            self
        )r   r
   r   )r   r   r   r   r   
set_params~   s    	
zBaseWrapper.set_paramsc             K   s   | j dkr"| jf | | j| _nLt| j tjsXt| j tjsX| j f | | j j| _n| j f | | j | _t	| jj
rt|jdkrt|}t| tj}|| | jj||f|}|S )as  Constructs a new model with `build_fn` & fit the model to `(x, y)`.

        Args:
            x : array-like, shape `(n_samples, n_features)`
                Training samples where `n_samples` is 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.
        N   )r	   r   filter_sk_paramsmodelr   r   r   r   r   Zis_categorical_crossentropylosslenshaper   r   deepcopyr   r   r   )r   xykwargsZfit_argshistoryr   r   r   r      s    

zBaseWrapper.fitc             C   sJ   |pi }i }x.| j  D ] \}}t||r|||i qW || |S )a5  Filters `sk_params` and returns those in `fn`'s arguments.

        Args:
            fn : arbitrary function
            override: dictionary, values to override `sk_params`

        Returns:
            res : dictionary containing variables
                in both `sk_params` and `fn`'s arguments.
        )r
   itemsr   r   )r   r   overrider   namevaluer   r   r   r"      s    

zBaseWrapper.filter_sk_params)N)N)
__name__
__module____qualname____doc__r   r   r   r    r   r"   r   r   r   r   r   "   s   '
!(r   z+keras.wrappers.scikit_learn.KerasClassifierc                   sF   e Zd ZdZd fdd	Z fddZdd Zd	d
 Zdd Z  Z	S )KerasClassifierzImplementation of the scikit-learn classifier API for Keras.

    DEPRECATED. Use [Sci-Keras](https://github.com/adriangb/scikeras) instead.
    See https://www.adriangb.com/scikeras/stable/migration.html
    for help migrating.
    Nc                s$   t jdtdd t j|f| d S )NzKerasClassifier is deprecated, use Sci-Keras (https://github.com/adriangb/scikeras) instead. See https://www.adriangb.com/scikeras/stable/migration.html for help migrating.r!   )
stacklevel)warningswarnDeprecationWarningsuperr   )r   r	   r
   )	__class__r   r   r      s
    zKerasClassifier.__init__c                s   t |}t|jdkr:|jd dkr:t |jd | _nXt|jdkrV|jd dksdt|jdkrt || _t | j|}ntdt	|j t| j| _
t j||f|S )a  Constructs a new model with `build_fn` & fit the model to `(x, y)`.

        Args:
            x : array-like, shape `(n_samples, n_features)`
                Training samples where `n_samples` is 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.

        Raises:
            ValueError: In case of invalid shape for `y` argument.
        r!      zInvalid shape for y: )nparrayr%   r&   Zarangeclasses_uniquesearchsortedr   strZ
n_classes_r9   r   )r   r(   r)   r*   )r:   r   r   r      s    
*zKerasClassifier.fitc             K   sD   | j j|f|}|jd dkr,|jdd}n|dkd}| j| S )a  Returns the class predictions for the given test data.

        Args:
            x: array-like, shape `(n_samples, n_features)`
                Test samples where `n_samples` is 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,)`
                Class predictions.
        r;   )Zaxisg      ?Zint32)r#   r   r&   ZargmaxZastyper>   )r   r(   r*   Zprobaclassesr   r   r   r      s
    zKerasClassifier.predictc             K   s4   | j j|f|}|jd dkr0td| |g}|S )a  Returns class probability estimates for the given test data.

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

        Returns:
            proba: array-like, shape `(n_samples, n_outputs)`
                Class probability estimates.
                In the case of binary classification,
                to match the scikit-learn API,
                will return an array of shape `(n_samples, 2)`
                (instead of `(n_sample, 1)` as in Keras).
        r;   )r#   r   r&   r<   Zhstack)r   r(   r*   Zprobsr   r   r   predict_proba  s    zKerasClassifier.predict_probac             K   s   t | j|}| tj|}| jj}t|dr4|j	}|dkrRt
|jdkrRt|}| jj||f|}t|tst|g}x&t| jj|D ]\}}|dkr|S qW tddS )a;  Returns the mean accuracy on the given test data and labels.

        Args:
            x: array-like, shape `(n_samples, n_features)`
                Test samples where `n_samples` is 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.
        r0   Zcategorical_crossentropyr!   )ZaccuracyacczxThe 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$   hasattrr0   r%   r&   r   r   listzipZmetrics_namesr   )r   r(   r)   r*   Z	loss_nameoutputsr.   outputr   r   r   score+  s    

zKerasClassifier.score)N)
r0   r1   r2   r3   r   r   r   rD   rK   __classcell__r   r   )r:   r   r4      s   r4   z*keras.wrappers.scikit_learn.KerasRegressorc                   s8   e Zd ZdZejd	 fdd	Zdd Zdd Z  Z	S )
KerasRegressorzImplementation of the scikit-learn regressor API for Keras.

    DEPRECATED. Use [Sci-Keras](https://github.com/adriangb/scikeras) instead.
    See https://www.adriangb.com/scikeras/stable/migration.html
    for help migrating.
    Nc                s$   t jdtdd t j|f| d S )NzKerasRegressor is deprecated, use Sci-Keras (https://github.com/adriangb/scikeras) instead. See https://www.adriangb.com/scikeras/stable/migration.html for help migrating.r!   )r5   )r6   r7   r8   r9   r   )r   r	   r
   )r:   r   r   r   `  s
    zKerasRegressor.__init__c             K   s$   |  tj|}t| jj|f|S )a  Returns predictions for the given test data.

        Args:
            x: array-like, shape `(n_samples, n_features)`
                Test samples where `n_samples` is 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<   Zsqueezer#   )r   r(   r*   r   r   r   r   l  s    zKerasRegressor.predictc             K   s:   |  tj|}| jj||f|}t|tr4|d  S | S )aD  Returns the mean loss on the given test data and labels.

        Args:
            x: array-like, shape `(n_samples, n_features)`
                Test samples where `n_samples` is 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`.
        r   )r"   r   r   r#   r   rG   )r   r(   r)   r*   r$   r   r   r   rK   }  s
    

zKerasRegressor.score)N)
r0   r1   r2   r3   r   Zdo_not_doc_inheritabler   r   rK   rL   r   r   )r:   r   rM   V  s
   rM   )r3   r   r   r6   numpyr<   Zkerasr   Zkeras.modelsr   Zkeras.utils.generic_utilsr   Zkeras.utils.np_utilsr   Z tensorflow.python.util.tf_exportr   Ztensorflow.tools.docsr   r   Zdo_not_generate_docsr4   rM   r   r   r   r   <module>   s&    &
 