【问题标题】:Scikit Learn - How to plot probabilitiesScikit Learn - 如何绘制概率
【发布时间】:2018-01-24 16:23:20
【问题描述】:

我想绘制模型的预测概率。

plt.scatter(y_test, prediction[:,0])
plt.xlabel("True Values")
plt.ylabel("Predictions")
plt.show()

但是,我得到了类似上面的图表。哪种有意义,但我想更好地可视化概率分布。有没有一种方法可以让我的实际类为 0 或 1 并且预测介于 0 和 1 之间。

【问题讨论】:

    标签: python matplotlib scikit-learn


    【解决方案1】:

    您可以根据真实值拆分值,然后绘制两个类的值的两个直方图,例如使用以下内容(至少如果您有一个 numpy 数组 arr_truearr_pred 这应该可以工作):

    arr_true_0_indices = (y_test == 0.0)
    arr_true_1_indices = (y_test == 1.0)
    
    arr_pred_0 = prediction[arr_true_0_indices]
    arr_pred_1 = prediction[arr_true_1_indices]
    
    plt.hist(arr_pred_0, bins=40, label='True class 0', normed=True, histtype='step')
    plt.hist(arr_pred_1, bins=40, label='True class 1', normed=True, histtype='step')
    plt.xlabel('Network output')
    plt.ylabel('Arbitrary units / probability')
    plt.legend(loc='best')
    plt.show()
    

    这应该是这样的:

    【讨论】:

      【解决方案2】:

      预测概率可用于可视化模型性能。真正的标签可以用颜色来表示。

      试试这个例子:

      from sklearn.datasets import make_classification
      import matplotlib.pyplot as plt
      
      X, y = make_classification(n_samples=1000, n_features=4,
                                 n_informative=2, n_redundant=0,
                                 random_state=1, shuffle=False)
      from sklearn.linear_model import LogisticRegression
      
      lr=LogisticRegression(random_state=0, solver='lbfgs', max_iter=10)
      lr.fit(X, y)
      
      prediction=lr.predict_proba(X)[:,1]
      
      plt.figure(figsize=(15,7))
      plt.hist(prediction[y==0], bins=50, label='Negatives')
      plt.hist(prediction[y==1], bins=50, label='Positives', alpha=0.7, color='r')
      plt.xlabel('Probability of being Positive Class', fontsize=25)
      plt.ylabel('Number of records in each bucket', fontsize=25)
      plt.legend(fontsize=15)
      plt.tick_params(axis='both', labelsize=25, pad=5)
      plt.show() 
      

      【讨论】:

      • 是否有 pyplot 设置可以堆叠两个历史类别而不是叠加?
      猜你喜欢
      • 2015-12-01
      • 2015-09-02
      • 2016-01-18
      • 2012-08-23
      • 2015-10-25
      • 2014-06-29
      • 2015-08-20
      • 2014-04-27
      • 2017-09-11
      相关资源
      最近更新 更多