o
    Ne!:  ã                   @   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   úKD:\Projects\ConvertPro\env\Lib\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 )zÓChecks 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 )zÍGets 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 )z­Sets 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   Ú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 )ÚKerasClassifierzéImplementation 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 )Nz¬KerasClassifier 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: )ÚnpÚ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.
        éÿÿÿÿrA   )Zaxisg      à?Zint32)r%   r   r(   ZargmaxZastyperD   )r   r*   r,   ZprobaÚ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).
        rA   )r%   r   r(   rB   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.
        r2   Zcategorical_crossentropyr#   )ZaccuracyÚacczxThe model is not configured to compute accuracy. You should pass `metrics=["accuracy"]` to the `model.compile()` method.)rB   rF   rD   r$   r   r   r%   r&   Úhasattrr2   r'   r(   r   r   ÚlistÚzipZmetrics_namesr   )r   r*   r+   r,   Z	loss_nameZoutputsr0   Úoutputr   r   r   Úscore+  s"   

ÿÿzKerasClassifier.scorer	   )
r2   r3   r4   r5   r   r   r   rJ   rP   Ú__classcell__r   r   r?   r   r6   Ç   s    r6   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 )
ÚKerasRegressorzèImplementation 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                    r7   )Nz«KerasRegressor is deprecated, use Sci-Keras (https://github.com/adriangb/scikeras) instead. See https://www.adriangb.com/scikeras/stable/migration.html for help migrating.r#   r8   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   rB   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   rM   )r   r*   r+   r,   r&   r   r   r   rP   }  s
   

zKerasRegressor.scorer	   )
r2   r3   r4   r5   r   Zdo_not_doc_inheritabler   r   rP   rQ   r   r   r?   r   rR   V  s    rR   )r5   r   r   r;   ÚnumpyrB   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_docsr6   rR   r   r   r   r   Ú<module>   s(    & 