o
    ={c!:                     @   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   ;lib/python3.10/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 nt| jtj	s*t| jtj
s*|| jj n|| j |D ]}|D ]	}t||r? nq6|dkrKt| dq2d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   s0   


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di | | j| _n*t| j tjs0t| j tjs0| j di | | j j| _n| j di | | j | _t	| jj
rOt|jdkrOt|}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
   r   filter_sk_paramsmodelr   r   r   r   r   Zis_categorical_crossentropylosslenshaper   r   Z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_paramsr	   )
__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                    (   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 | _n,t|jdkr+|jd dks2t|jdkr@t || _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: )npZarrayr'   r(   Z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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astyperB   )r   r)   r+   ZprobaZclassesr   r   r   r      s
   
zKerasClassifier.predictc                 K   s8   | j j|fi |}|jd dkrt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(   rA   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r|j	}|dkr)t
|jdkr)t|}| jj||fi |}t|ts<|g}t| jj|D ]\}}|dv rO|  S qCtd)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.
        r1   Zcategorical_crossentropyr#   )ZaccuracyZacczxThe model is not configured to compute accuracy. You should pass `metrics=["accuracy"]` to the `model.compile()` method.)rA   rD   rB   r$   r   r   r%   r&   hasattrr1   r'   r(   r   r   listzipZmetrics_namesr   )r   r)   r*   r+   Z	loss_nameZoutputsr/   outputr   r   r   score+  s"   

zKerasClassifier.scorer	   )
r1   r2   r3   r4   r   r   r   rG   rL   __classcell__r   r   r>   r   r5      s    r5   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                    r6   )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#   r7   r9   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   rA   Zsqueezer%   )r   r)   r+   r   r   r   r   l  s   zKerasRegressor.predictc                 K   s>   |  tj|}| jj||fi |}t|tr|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   rI   )r   r)   r*   r+   r&   r   r   r   rL   }  s
   

zKerasRegressor.scorer	   )
r1   r2   r3   r4   r   Zdo_not_doc_inheritabler   r   rL   rM   r   r   r>   r   rN   V  s    rN   )r4   r   r   r:   ZnumpyrA   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_docsr5   rN   r   r   r   r   <module>   s(    & 