a
    Sic:                     @   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   W/var/www/html/django/DPS/env/lib/python3.9/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u r(|| j n8t| jtj	sTt| jtj
sT|| jj n|| j |D ]2}|D ]}t||rl qdql|dkrdtd|qdd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.
        Nnb_epochz{} is not a legal parameter)r   fitpredictevaluater	   append__call__
isinstancetypesFunctionType
MethodTyper   
ValueErrorformat)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u r&| jf i | | j| _nTt| j tjs`t| j tjs`| j f i | | j j| _n| j f i | | j | _t	| jj
rt|jdkrt|}t| tj}|| | jj||fi |}|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   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   sF   |pi }i }| j  D ] \}}t||r|||i q|| |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i | 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   	__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i |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*   arangeclasses_uniquesearchsortedr   strZ
n_classes_r?   r   )r   r,   r-   r.   r@   r   r   r      s    
*zKerasClassifier.fitc                 K   sH   | j j|fi |}|jd dkr0|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.
        rB   )axisg      ?int32)r&   r   r*   argmaxastyperF   )r   r,   r.   probaclassesr   r   r   r      s
    zKerasClassifier.predictc                 K   s8   | j j|fi |}|jd dkr4t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).
        rB   )r&   r   r*   rC   hstack)r   r,   r.   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i |}t|tsx|g}t| jj|D ]\}}|dv r|  S qt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.
        r4   categorical_crossentropyr$   )accuracyacczxThe model is not configured to compute accuracy. You should pass `metrics=["accuracy"]` to the `model.compile()` method.N)rC   rH   rF   r%   r   r   r&   r(   hasattrr4   r)   r*   r   r   listzipmetrics_namesr   )r   r,   r-   r.   	loss_nameoutputsr2   outputr   r   r   score+  s     


zKerasClassifier.score)N)
r4   r5   r6   r7   r   r   r   rS   r^   __classcell__r   r   r@   r   r8      s   r8   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i | 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$   r9   r;   r   r@   r   r   r   `  s    zKerasRegressor.__init__c                 K   s(   |  tj|}t| jj|fi |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   rC   squeezer&   )r   r,   r.   r   r   r   r   l  s    zKerasRegressor.predictc                 K   s>   |  tj|}| jj||fi |}t|tr8|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   rX   )r   r,   r-   r.   r(   r   r   r   r^   }  s
    

zKerasRegressor.score)N)
r4   r5   r6   r7   r   do_not_doc_inheritabler   r   r^   r_   r   r   r@   r   r`   V  s
   r`   )r7   r   r   r<   numpyrC   kerasr   Zkeras.modelsr   keras.utils.generic_utilsr   keras.utils.np_utilsr    tensorflow.python.util.tf_exportr   tensorflow.tools.docsr   r   do_not_generate_docsr8   r`   r   r   r   r   <module>   s&    & 