How to plot ROC curve in Python

后端 未结 11 2250
臣服心动
臣服心动 2020-11-29 16:15

I am trying to plot a ROC curve to evaluate the accuracy of a prediction model I developed in Python using logistic regression packages. I have computed the true positive ra

11条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 16:21

    Based on multiple comments from stackoverflow, scikit-learn documentation and some other, I made a python package to plot ROC curve (and other metric) in a really simple way.

    To install package : pip install plot-metric (more info at the end of post)

    To plot a ROC Curve (example come from the documentation) :

    Binary classification

    Let's load a simple dataset and make a train & test set :

    from sklearn.datasets import make_classification
    from sklearn.model_selection import train_test_split
    X, y = make_classification(n_samples=1000, n_classes=2, weights=[1,1], random_state=1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=2)
    

    Train a classifier and predict test set :

    from sklearn.ensemble import RandomForestClassifier
    clf = RandomForestClassifier(n_estimators=50, random_state=23)
    model = clf.fit(X_train, y_train)
    
    # Use predict_proba to predict probability of the class
    y_pred = clf.predict_proba(X_test)[:,1]
    

    You can now use plot_metric to plot ROC Curve :

    from plot_metric.functions import BinaryClassification
    # Visualisation with plot_metric
    bc = BinaryClassification(y_test, y_pred, labels=["Class 1", "Class 2"])
    
    # Figures
    plt.figure(figsize=(5,5))
    bc.plot_roc_curve()
    plt.show()
    

    Result :

    You can find more example of on the github and documentation of the package:

    • Github : https://github.com/yohann84L/plot_metric
    • Documentation : https://plot-metric.readthedocs.io/en/latest/

提交回复
热议问题