o
    xi-                     @   s   d Z ddlmZ ddlZddlmZ ddlZddlZddl	m
Z
mZ ddlmZ eded	 	
			
dddZ						dddZ						
dddZ	d ddZ	d!ddZd"ddZd#ddZdS )$z?Define plots for classification models built with scikit-learn.    )simplefilterN)naive_bayes)	calculateutils   )sharedignore)actioncategoryF
Classifierc                 C   s   t d|	 d t| tjst| |
 t d |r't| || t d t||| t d tj	| ||||d t d t
||| t d t| tjs^t| |||	 t d	 t||| t d
 t||| t d dS )ag  Generate all sklearn classifier plots supported by W&B.

    The following plots are generated:
        feature importances, confusion matrix, summary metrics,
        class proportions, calibration curve, roc curve, precision-recall curve.

    Should only be called with a fitted classifier (otherwise an error is thrown).

    Args:
        model: (classifier) Takes in a fitted classifier.
        X_train: (arr) Training set features.
        y_train: (arr) Training set labels.
        X_test: (arr) Test set features.
        y_test: (arr) Test set labels.
        y_pred: (arr) Test set predictions by the model passed.
        y_probas: (arr) Test set predicted probabilities by the model passed.
        labels: (list) Named labels for target variable (y). Makes plots easier to
                        read by replacing target values with corresponding index.
                        For example if `labels=['dog', 'cat', 'owl']` all 0s are
                        replaced by dog, 1s by cat.
        is_binary: (bool) Is the model passed a binary classifier? Defaults to False
        model_name: (str) Model name. Defaults to 'Classifier'
        feature_names: (list) Names for features. Makes plots easier to read by
                                replacing feature indexes with corresponding names.
        log_learning_curve: (bool) Whether or not to log the learning curve.
                                    Defaults to False.

    Returns:
        None: To see plots, go to your W&B run page then expand the 'media' tab
            under 'auto visualizations'.

    Example:
    ```python
    wandb.sklearn.plot_classifier(
        model,
        X_train,
        X_test,
        y_train,
        y_test,
        y_pred,
        y_probas,
        ["cat", "dog"],
        False,
        "RandomForest",
        ["barks", "drools", "plays_fetch", "breed"],
    )
    ```
    z

Plotting .zLogged feature importances.zLogged learning curve.zLogged confusion matrix.)XyX_testy_testzLogged summary metrics.zLogged class proportions.zLogged calibration curve.zLogged roc curve.zLogged precision-recall curve.N)wandbtermlog
isinstancer   MultinomialNBfeature_importancesr   learning_curveconfusion_matrixsummary_metricsclass_proportionscalibration_curverocprecision_recall)modelX_trainr   y_trainr   y_predy_probaslabels	is_binary
model_namefeature_nameslog_learning_curve r'   ]/home/ubuntu/.local/lib/python3.10/site-packages/wandb/integration/sklearn/plot/classifier.py
classifier   s(   >







r)   Tc                 C   s$   t j| |||}t d|i dS )a  Log the receiver-operating characteristic curve.

    Args:
        y_true: (arr) Test set labels.
        y_probas: (arr) Test set predicted probabilities.
        labels: (list) Named labels for target variable (y). Makes plots easier to
                       read by replacing target values with corresponding index.
                       For example if `labels=['dog', 'cat', 'owl']` all 0s are
                       replaced by dog, 1s by cat.

    Returns:
        None: To see plots, go to your W&B run page then expand the 'media' tab
              under 'auto visualizations'.

    Example:
    ```python
    wandb.sklearn.plot_roc(y_true, y_probas, labels)
    ```
    r   N)r   plot	roc_curvelog)y_truer!   r"   
plot_micro
plot_macroclasses_to_plot	roc_chartr'   r'   r(   r   n   s   r   c           	      C   sf   t | } t |}tj| |d}tj| |d}|r/|r1t| |||||}td|i dS dS dS )a  Log a confusion matrix to W&B.

    Confusion matrices depict the pattern of misclassifications by a model.

    Args:
        y_true: (arr) Test set labels.
        y_probas: (arr) Test set predicted probabilities.
        labels: (list) Named labels for target variable (y). Makes plots easier to
                       read by replacing target values with corresponding index.
                       For example if `labels=['dog', 'cat', 'owl']` all 0s are
                       replaced by dog, 1s by cat.

    Returns:
        None: To see plots, go to your W&B run page then expand the 'media' tab
              under 'auto visualizations'.

    Example:
    ```python
    wandb.sklearn.plot_confusion_matrix(y_true, y_probas, labels)
    ```
    )r-   r    r   N)	npasarrayr   test_missing
test_typesr   r   r   r,   )	r-   r    r"   true_labelspred_labels	normalizenot_missingcorrect_typesconfusion_matrix_chartr'   r'   r(   r      s   

	r   c                 C   s$   t j| |||}t d|i dS )a[  Log a precision-recall curve to W&B.

    Precision-recall curves depict the tradeoff between positive predictive value (precision)
    and true positive rate (recall) as the threshold of a classifier is shifted.

    Args:
        y_true: (arr) Test set labels.
        y_probas: (arr) Test set predicted probabilities.
        labels: (list) Named labels for target variable (y). Makes plots easier to
                       read by replacing target values with corresponding index.
                       For example if `labels=['dog', 'cat', 'owl']` all 0s are
                       replaced by dog, 1s by cat.

    Returns:
        None: To see plots, go to your W&B run page then expand the 'media' tab
              under 'auto visualizations'.

    Example:
    ```python
    wandb.sklearn.plot_precision_recall(y_true, y_probas, labels)
    ```
    r   N)r   r*   pr_curver,   )r-   r!   r"   r.   r0   precision_recall_chartr'   r'   r(   r      s   r   Feature Importance2   c                 C   sX   t j| d}t j| d}t | }|r&|r(|r*t| |}td|i dS dS dS dS )a  Log a plot depicting the relative importance of each feature for a classifier's decisions.

    Should only be called with a fitted classifier (otherwise an error is thrown).
    Only works with classifiers that have a feature_importances_ attribute, like trees.

    Args:
        model: (clf) Takes in a fitted classifier.
        feature_names: (list) Names for features. Makes plots easier to read by
                              replacing feature indexes with corresponding names.

    Returns:
        None: To see plots, go to your W&B run page then expand the 'media' tab
              under 'auto visualizations'.

    Example:
    ```python
    wandb.sklearn.plot_feature_importances(model, ["width", "height", "length"])
    ```
    )r   r   N)r   r4   r5   test_fittedr   r   r   r,   )r   r%   titlemax_num_featuresr9   r:   model_fittedfeature_importance_chartr'   r'   r(   r      s   
r   c                 C   sb   t j| |d}t j| |d}|r-|r/t| t|} }t| ||}td|i dS dS dS )a  Plot the distribution of target classes in training and test sets.

    Useful for detecting imbalanced classes.

    Args:
        y_train: (arr) Training set labels.
        y_test: (arr) Test set labels.
        labels: (list) Named labels for target variable (y). Makes plots easier to
                       read by replacing target values with corresponding index.
                       For example if `labels=['dog', 'cat', 'owl']` all 0s are
                       replaced by dog, 1s by cat.

    Returns:
        None: To see plots, go to your W&B run page then expand the 'media' tab
              under 'auto visualizations'.

    Example:
    ```python
    wandb.sklearn.plot_class_proportions(y_train, y_test, ["dog", "cat", "owl"])
    ```
    )r   r   r   N)	r   r4   r5   r2   arrayr   r   r   r,   )r   r   r"   r9   r:   class_proportions_chartr'   r'   r(   r      s   r   c                 C   s   t j| ||d}t j| ||d}t | }|rH|rJ|rLt|}|jjdks0|dk|dkB  s7t	
d dS t| |||}t	d|i dS dS dS dS )a  Log a plot depicting how well-calibrated the predicted probabilities of a classifier are.

    Also suggests how to calibrate an uncalibrated classifier. Compares estimated predicted
    probabilities by a baseline logistic regression model, the model passed as
    an argument, and by both its isotonic calibration and sigmoid calibrations.
    The closer the calibration curves are to a diagonal the better.
    A sine wave like curve represents an overfitted classifier, while a cosine
    wave like curve represents an underfitted classifier.
    By training isotonic and sigmoid calibrations of the model and comparing
    their curves we can figure out whether the model is over or underfitting and
    if so which calibration (sigmoid or isotonic) might help fix this.
    For more details, see https://scikit-learn.org/stable/auto_examples/calibration/plot_calibration_curve.html.

    Should only be called with a fitted classifier (otherwise an error is thrown).

    Please note this function fits variations of the model on the training set when called.

    Args:
        clf: (clf) Takes in a fitted classifier.
        X: (arr) Training set features.
        y: (arr) Training set labels.
        model_name: (str) Model name. Defaults to 'Classifier'

    Returns:
        None: To see plots, go to your W&B run page then expand the 'media' tab
              under 'auto visualizations'.

    Example:
    ```python
    wandb.sklearn.plot_calibration_curve(clf, X, y, "RandomForestClassifier")
    ```
    )clfr   r   Ur   r   zThis function only supports binary classification at the moment and therefore expects labels to be binary. Skipping calibration curve.Nr   )r   r4   r5   r@   r2   r3   dtypecharallr   termwarnr   calibration_curvesr,   )rG   r   r   clf_namer9   r:   	is_fittedcalibration_curve_chartr'   r'   r(   r     s   !

 r   )Fr   NF)NNNTTN)NNNNNF)NNNTN)NNr>   r?   )NNN)NNNr   )__doc__warningsr   numpyr2   sklearnr   r   
wandb.plotwandb.integration.sklearnr   r    r   FutureWarningr)   r   r   r   r   r   r   r'   r'   r'   r(   <module>   sD    
]
 
1
!

