
    ~Wh!:                     <   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
          Z ed          ej         G d de                                  Z ed          ej         G 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                   :    e Zd ZdZd	dZd Zd Zd Zd Z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                 L    || _         || _        |                     |           d S N)build_fn	sk_paramscheck_params)selfr   r   s      a/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/keras/wrappers/scikit_learn.py__init__zBaseWrapper.__init__K   s*     ")$$$$$    c                    t           j        t           j        t           j        g}| j        |                    | j                   nxt          | j        t          j	                  s?t          | j        t          j
                  s |                    | j        j                   n|                    | j                   |D ]1}|D ]}t          ||          r n|dk    rt          | d          2d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)r   paramslegal_params_fnsparams_namefns        r   r   zBaseWrapper.check_paramsP   s    N

 = ##DM2222M5-
 
 	3T]E,<==	3 ##DM$:;;;;##DM222! 	 	K&  2{++ E *,,$&AAA  	 	r   c                 p    | 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    ress      r   
get_paramszBaseWrapper.get_paramsq   s5     n!!##

J.///
r   c                 d    |                      |           | 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    s     r   
set_paramszBaseWrapper.set_params~   s3     	&!!!f%%%r   c                    | j         + | j        di |                     | j                  | _        nt	          | j         t
          j                  sOt	          | j         t
          j                  s0 | j         di |                     | j         j                  | _        n* | j         di |                     | j                   | _        t          j	        | j        j
                  r't          |j                  dk    rt          |          }t          j        |                     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kwargsfit_argshistorys         r   r   zBaseWrapper.fit   s\     = &NN)>)>t})M)MNNDJJM5-
 
 	OT]E,<==	O '  ''(>?? DJJ 'NN)>)>t})M)MNNDJ .tz??	"AG!!q!!A=!6!6z~!F!FGG $*.A2222r   c                     |pi }i }| j                                         D ],\  }}t          ||          r|                    ||i           -|                    |           |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values         r   r.   zBaseWrapper.filter_sk_params   ss     >r>//11 	* 	*KD%r4   *

D%=)))

8
r   r   )
__name__
__module____qualname____doc__r   r   r(   r*   r   r.   r-   r   r   r
   r
   "   s        & &P% % % %
  B    & & &P     r   r
   z+keras.wrappers.scikit_learn.KerasClassifierc                   @     e Zd ZdZd fd	Z fdZd Zd Zd Z x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    t          j        dt          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   r   r   	__class__s      r   r   zKerasClassifier.__init__   sP    " 	
 	
 	
 	
 	//Y/////r   c                 b   t          j        |          }t          |j                  dk    r6|j        d         dk    r%t          j        |j        d                   | _        nt          |j                  dk    r|j        d         dk    st          |j                  dk    r4t          j        |          | _        t          j        | j        |          }n$t          dt          |j                  z             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arrayr2   r3   arangeclasses_uniquesearchsortedr   str
n_classes_rL   r   )r   r5   r6   r7   rN   s       r   r   zKerasClassifier.fit   s    & HQKKqw<<1aIagaj11DMM!'llaAGAJ!OOAG8I8IIaLLDMq11AA4s17||CDDDdm,,uww{1a**6***r   c                      | j         j        |fi |}|j        d         dk    r|                    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.
        rP   )axisg      ?int32)r/   r   r3   argmaxastyperT   )r   r5   r7   probaclassess        r   r   zKerasClassifier.predict   sj     #
"1////;r?Qlll++GGs{**733G}W%%r   c                      | j         j        |fi |}|j        d         dk    rt          j        d|z
  |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).
        rP   )r/   r   r3   rQ   hstack)r   r5   r7   probss       r   predict_probazKerasClassifier.predict_proba  sP    & #
"1//// ;q>QIq5y%011Er   c                    t          j        | 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 r|c S t#          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.
        r?   categorical_crossentropyr,   )accuracyacczxThe model is not configured to compute accuracy. You should pass `metrics=["accuracy"]` to the `model.compile()` method.)rQ   rV   rT   r.   r   r   r/   r1   hasattrr?   r2   r3   r   r   listzipmetrics_namesr   )r   r5   r6   r7   	loss_nameoutputsr=   outputs           r   scorezKerasClassifier.score+  s   * ODM1--&&z':FCCJO	9j)) 	+!*I222s17||q7H7Hq!!A%$*%a55f55'4(( 	 iG
 8'BB 	 	LD&*** +,
 
 	
r   r   )
r?   r@   rA   rB   r   r   r   rd   rp   __classcell__rN   s   @r   rD   rD      s         	0 	0 	0 	0 	0 	0+ + + + +<& & &,  6(
 (
 (
 (
 (
 (
 (
r   rD   z*keras.wrappers.scikit_learn.KerasRegressorc                   J     e Zd ZdZej        d fd	            Zd Zd Z x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                 t    t          j        dt          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,   rF   rH   rM   s      r   r   zKerasRegressor.__init__`  sP    " 	
 	
 	
 	
 	//Y/////r   c                     |                      t          j        |          }t          j         | 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   rQ   squeezer/   )r   r5   r7   s      r   r   zKerasRegressor.predictl  sD     &&z'96BBz,$*,Q99&99:::r   c                     |                      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   rj   )r   r5   r6   r7   r1   s        r   rp   zKerasRegressor.score}  s^      &&z':FCC"tz"1a22622dD!! 	G8Our   r   )
r?   r@   rA   rB   r   do_not_doc_inheritabler   r   rp   rq   rr   s   @r   rt   rt   V  su          (	0 	0 	0 	0 	0 )(	0; ; ;"      r   rt   )rB   r%   r   rI   numpyrQ   kerasr   keras.modelsr   keras.utils.generic_utilsr   keras.utils.np_utilsr    tensorflow.python.util.tf_exportr   tensorflow.tools.docsr   r
   do_not_generate_docsrD   rt   r-   r   r   <module>r      s   @ ?              # # # # # # - - - - - - / / / / / / : 9 9 9 9 9 . . . . . .b b b b b b b bJ ;<<"J
 J
 J
 J
 J
k J
 J
 #" =<J
Z :;;"9 9 9 9 9[ 9 9 #" <;9 9 9r   