<jupyter_start><jupyter_text>Visualizations with Display ObjectsThis Notebooks is adapted from [*Visualizations with Display Objects*](https://scikit-learn.org/stable/auto_examples/miscellaneous/plot_display_object_visualization.htmlsphx-glr-auto-examples-miscellaneous-plot-display-object-visualization-py).In this example, we will construct display objects, `ConfusionMatrixDisplay`, `RocCurveDisplay`, and`PrecisionRecallDisplay` directly from their respective metrics. This is an alternative to using their corresponding plot functions when a model's predictions are already computed or expensive to compute. Note that this is advanced usage, and in general we recommend using their respective plot functions.  Load DataFor this example, we load a [blood transfusion service center data set from OpenML](https://www.openml.org/d/1464). This is a binary classification problem where the target is whether an individual donated blood.<jupyter_code>import numpy as np
from sklearn.datasets import fetch_openml

X, y = fetch_openml(data_id=1464, return_X_y=True)
y = y.astype(np.int8)<jupyter_output><empty_output><jupyter_text>Data Samples<jupyter_code>import pandas as pd

df = pd.DataFrame(X, columns=["V1", "V2", "V3", "V4"])
df.insert(4, "Class", y)
df.head()<jupyter_output><empty_output><jupyter_text>V1 = months since last donation V2 = total number of donations V3 = total blood donated in cc V4 = months since first donation Class = donated in March 2007 (yes = 2, no = 1)<jupyter_code>df.describe()
df.Class.value_counts()<jupyter_output><empty_output><jupyter_text>1 = did NOT donate blood in March 2007 2 = donated blood in March 2007  Train ModelSplit data into a train and test dataset and fit a logistic regression.<jupyter_code>from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics

X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=1)

clf = make_pipeline(
    StandardScaler(),
    LogisticRegression(
        C=1.0,
        penalty="l2",
        multi_class="auto",
        random_state=0,
        class_weight=None,
        solver="lbfgs",
        max_iter=100,
        l1_ratio=None,
    ),
)
clf.fit(X_train, y_train)
print("Test accuracy: %f" % clf.score(X_test, y_test))<jupyter_output>Test accuracy: 0.770053<jupyter_text>Predict ClassesUse the fitted model to make predictions using the test examples.<jupyter_code>y_pred = clf.predict(X_test)

print("Predicted classes:\n%s\n" % pd.DataFrame(y_pred).value_counts())
print("Actual classes:\n%s" % pd.DataFrame(y_test).value_counts())<jupyter_output>Predicted classes:
1    177
2     10
dtype: int64

Actual classes:
1    142
2     45
dtype: int64<jupyter_text>Create `ConfusionMatrixDisplay`Compute the confustion matrix and plot it with `ConfusionMatrixDisplay`<jupyter_code>cm = metrics.confusion_matrix(y_test, y_pred)
_ = metrics.ConfusionMatrixDisplay(cm, display_labels=[1,2]).plot()

print("Precision: %f" % metrics.precision_score(y_test, y_pred, pos_label=2))
print("Recall: %f" % metrics.recall_score(y_test, y_pred, pos_label=2))<jupyter_output>Precision: 0.600000
Recall: 0.133333<jupyter_text>Create `RocCurveDisplay`The roc curve requires either the probabilities or the non-thresholded decision values from the estimator. Since the logistic regression provides a decision function, we will use it to plot the roc curve.<jupyter_code>y_score = clf.decision_function(X_test)
fpr, tpr, _ = metrics.roc_curve(y_test, y_score, pos_label=2)
roc_display = metrics.RocCurveDisplay(fpr=fpr, tpr=tpr).plot()
print("Area under the curve: %f" % metrics.auc(fpr, tpr))<jupyter_output>Area under the curve: 0.778013<jupyter_text>Create `PrecisionRecallDisplay`Similarly, the precision recall curve can be plotted using `y_score` from the prevision sections.<jupyter_code>prec, recall, _ = metrics.precision_recall_curve(y_test, y_score, pos_label=2)
pr_display = metrics.PrecisionRecallDisplay(prec, recall).plot()
print("Average precision: %f" % metrics.average_precision_score(y_test, y_score))<jupyter_output>Average precision: 0.618756
{'fraction_non_alphanumeric': 0.095711916607439, 'fraction_numerical': 0.024164889836531627, 'mean_word_length': 6.317157712305026, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 28, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '654420', 'license': 'Apache-2.0', 'n_tokens_mistral': 1451, 'n_tokens_neox': 1350, 'n_words': 365, 'path': 'examples/notebooks/plot_display_object_visualization.ipynb', 'repo_name': 'hkennyv/guildai', 'size': '4221'}