Team Ai
Apppublic

sklearn-docs/multilabel_classification

sourceHugging Facemitupdated 3y agoView on Hugging Face
1likes
app.py117 linesDownload Raw Back to root
1import numpy as np2import gradio as gr3import matplotlib.pyplot as plt4 5from sklearn.datasets import make_multilabel_classification6from sklearn.multiclass import OneVsRestClassifier7from sklearn.svm import SVC8from sklearn.decomposition import PCA9from sklearn.cross_decomposition import CCA10from matplotlib import cm11 12plt.switch_backend('agg')13 14 15def plot_hyperplane(clf, min_x, max_x, linestyle, linecolor, label):16    """17    This function is used to plot the hyperplane obtained from the classifier.18 19    :param clf: the classifier model20    :param min_x: the minimum value of X21    :param max_x: the maximum value of x22    :param linestyle: the style of line one needs in the plot.23    :param label: the label for the hyperplane24    """25 26    w = clf.coef_[0]27    a = -w[0] / w[1]28    xx = np.linspace(min_x - 5, max_x + 5)29    yy = a * xx - (clf.intercept_[0]) / w[1]30    plt.plot(xx, yy, linestyle, color=linecolor, linewidth=2.5, label=label)31 32 33 34def multilabel_classification(n_samples:int, n_classes: int, n_labels: int, allow_unlabeled: bool, decompostion: str) -> "plt.Figure":35    """36    This function is used to perform multilabel classification.37 38    :param n_samples: the number of samples.39    :param n_classes: the number of classes for the classification problem.40    :param n_labels: the average number of labels per instance.41    :param allow_unlabeled: if set to True some instances might not belong to any class.42    :param decompostion: the type of decomposition algorithm to use.43 44    :returns: a matplotlib figure.45    """46 47    X, Y = make_multilabel_classification(48    n_samples=n_samples,49    n_classes=n_classes, n_labels=n_labels, allow_unlabeled=allow_unlabeled, random_state=42)50 51    if decomposition == "PCA":52        X = PCA(n_components=2).fit_transform(X)53 54    else:55        X = CCA(n_components=2).fit(X, Y).transform(X)56 57    min_x = np.min(X[:, 0])58    max_x = np.max(X[:, 0])59 60 61    min_y = np.min(X[:, 1])62    max_y = np.max(X[:, 1])63 64    model = OneVsRestClassifier(SVC(kernel="linear"))65    model.fit(X, Y)66 67    fig, ax = plt.subplots(1, 1, figsize=(24, 15))68 69    ax.scatter(X[:, 0], X[:, 1], s=40, c="gray", edgecolors=(0, 0, 0))70    # colors = cm.rainbow(np.linspace(0, 1, n_classes))71    colors = cm.get_cmap('tab10', 10)(np.linspace(0, 1, 10))72 73    for nc in range(n_classes):74        cl = np.where(Y[:, nc])75        ax.scatter(X[cl, 0], X[cl, 1], s=np.random.random_integers(20, 200), 76                   edgecolors=colors[nc], facecolors="none", linewidths=2, label=f"Class {nc+1}")77        78        plot_hyperplane(model.estimators_[nc], min_x, max_x, "--", colors[nc], f"Boundary for class {nc+1}")79        ax.set_xticks(())80        ax.set_yticks(())81 82        ax.set_xlim(min_x - .5 * max_x, max_x + .5 * max_x)83        ax.set_ylim(min_y - .5 * max_y, max_y + .5 * max_y)84 85    ax.legend()86        87 88    return fig89 90 91 92 93with gr.Blocks() as demo:94 95    gr.Markdown(""" 96    97    # Multilabel Classification98 99    This space is an implementation of the scikit-learn document [Multilabel Classification](https://scikit-learn.org/stable/auto_examples/miscellaneous/plot_multilabel.html#sphx-glr-auto-examples-miscellaneous-plot-multilabel-py).100    The objective of this space is to simulate a multi-label document classification problem, where the data is generated randomly. 101    102    """)103 104    n_samples = gr.Slider(100, 10_000, label="n_samples", info="the number of samples")105    n_classes = gr.Slider(2, 10, label="n_classes", info="the number of classes that data should have.", step=1)106    n_labels = gr.Slider(1, 10, label="n_labels", info="the average number of labels per instance", step=1)107    allow_unlabeled = gr.Checkbox(True, label="allow_unlabeled", info="If set to True some instances might not belong to any class.")108    decomposition = gr.Dropdown(['PCA', 'CCA'], label="decomposition", info="the type of decomposition algorithm to use.")109    110    output = gr.Plot(label="Plot")111 112    compute_btn = gr.Button("Compute")113    compute_btn.click(fn=multilabel_classification, inputs=[n_samples, n_classes, n_labels, allow_unlabeled, decomposition],114                      outputs=output, api_name="multilabel")115 116 117demo.launch()