使用python+sklearn實現概率校準曲線

2021-03-02 機器學習算法與知識圖譜

print(__doc__)
# 作者: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr># Jan Hendrik Metzen <jhm@informatik.uni-bremen.de># 許可證: BSD Style.
import matplotlib.pyplot as plt
from sklearn import datasetsfrom sklearn.naive_bayes import GaussianNBfrom sklearn.svm import LinearSVCfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import (brier_score_loss, precision_score, recall_score, f1_score)from sklearn.calibration import CalibratedClassifierCV, calibration_curvefrom sklearn.model_selection import train_test_split

# 創建分類任務的數據集,其中有很多冗餘的特徵而有很少# 具有信息性的特徵X, y = datasets.make_classification(n_samples=100000, n_features=20, n_informative=2, n_redundant=10, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.99, random_state=42)

def plot_calibration_curve(est, name, fig_index): """Plot calibration curve for est w/o and with calibration. """ # 等滲校準 isotonic = CalibratedClassifierCV(est, cv=2, method='isotonic')
# sigmoid校準 sigmoid = CalibratedClassifierCV(est, cv=2, method='sigmoid')
# 做為基準的沒有校準的邏輯回歸 lr = LogisticRegression(C=1.)
fig = plt.figure(fig_index, figsize=(10, 10)) ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2) ax2 = plt.subplot2grid((3, 1), (2, 0))
ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") for clf, name in [(lr, 'Logistic'), (est, name), (isotonic, name + ' + Isotonic'), (sigmoid, name + ' + Sigmoid')]: clf.fit(X_train, y_train) y_pred = clf.predict(X_test) if hasattr(clf, "predict_proba"): prob_pos = clf.predict_proba(X_test)[:, 1] else: # 使用決策函數 prob_pos = clf.decision_function(X_test) prob_pos = \ (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min())
clf_score = brier_score_loss(y_test, prob_pos, pos_label=y.max()) print("%s:" % name) print("\tBrier: %1.3f" % (clf_score)) print("\tPrecision: %1.3f" % precision_score(y_test, y_pred)) print("\tRecall: %1.3f" % recall_score(y_test, y_pred)) print("\tF1: %1.3f\n" % f1_score(y_test, y_pred))
fraction_of_positives, mean_predicted_value = \ calibration_curve(y_test, prob_pos, n_bins=10)
ax1.plot(mean_predicted_value, fraction_of_positives, "s-", label="%s (%1.3f)" % (name, clf_score))
ax2.hist(prob_pos, range=(0, 1), bins=10, label=name, histtype="step", lw=2)
ax1.set_ylabel("Fraction of positives") ax1.set_ylim([-0.05, 1.05]) ax1.legend(loc="lower right") ax1.set_title('Calibration plots (reliability curve)')
ax2.set_xlabel("Mean predicted value") ax2.set_ylabel("Count") ax2.legend(loc="upper center", ncol=2)
plt.tight_layout()
# 繪製高斯樸素貝葉斯的校準曲線plot_calibration_curve(GaussianNB(), "Naive Bayes", 1)
# 繪製線性支持向量分類器(Linear SVC)的校準曲線plot_calibration_curve(LinearSVC(max_iter=10000), "SVC", 2)
plt.show()

相關焦點

  • 使用python+sklearn實現度量和評分
    scoring=ftwo_scorer, cv=5)第二個用法是使用make_scorer,從一個簡單的python函數構建一個完全自定義的評分對象,該函數可以接收多個參數:您想使用的python函數(下面的示例中的my_custom_loss_func )您的python函數返回分數(greater_is_better=True默認值)還是損失(loss)(greater_is_better
  • 使用python+sklearn實現使用貝葉斯嶺回歸擬合正弦曲線
    本示例使用貝葉斯嶺回歸擬合正弦曲線。
  • 使用python+sklearn實現高斯過程分類(GPC)的概率預測
    本示例描述了不同超參數下RBF核函數的GPC預測概率。
  • 使用python+sklearn實現繪製由VotingClassifier計算的分類概率
    首先,將初始化三個樣本分類器(LogisticRegression,GaussianNB和RandomForestClassifier),並使用權重[1, 1, 5]初始化軟投票(soft-voting)VotingClassifier,這意味著在計算平均概率時,RandomForestClassifier預測概率的計算權重是其他分類器的5倍。
  • Python sklearn模型選擇
    概率校準28.sklearn.cross_decomposition: Cross decomposition 交叉求解29.sklearn.pipeline: Pipeline 管道30.sklearn.preprocessing: Preprocessing and Normalization 預處理和標準化31.sklearn.random_projection
  • 使用python+sklearn實現交叉驗證
    可以使用scoring參數更改此設置:>>> from sklearn import metrics>>> scores = cross_val_score(...也可以通過傳入一個交叉驗證迭代器(cross validation iterator)來使用其他交叉驗證策略,例如:>>> from sklearn.model_selection import ShuffleSplit>>> n_samples = X.shape[0]>>> cv = ShuffleSplit
  • 使用python+sklearn實現成對度量、相關性和核函數
    sklearn.metrics.pairwise子模塊實現了評估樣本集的成對距離或相關性。此模塊包含距離度量和內核。這裡對這兩個問題作了簡要的總結。
  • 使用python+sklearn實現估計器的調參方法
    具體來說,要查找給定估計器的所有參數的名稱和當前值,請使用:估計器(回歸器或分類器,如sklearn.svm.SVC());一些模型允許使用專門的、有效的參數搜索策略,如下所述。scikit-learn中提供了兩種通用的採樣搜索候選值方法:對於給定的值,GridSearchCV 詳盡地考慮所有參數組合,而RandomizedSearchCV 可以從具有指定分布的參數空間中採樣給定數量的候選值。
  • 使用python+sklearn實現繪製VotingClassifier的決策邊界
    繪製小型(toy)數據集中第一個樣本的分類概率,該個概率首先是由三個不同分類器進行預測,然後這些預測結果通過VotingClassifier加權平均得出的。首先,對三個分類器進行初始化(DecisionTreeClassifier, KNeighborsClassifier和SVC),並用權重[2, 1, 2]初始化軟投票(soft-voting)VotingClassifier,這意味著計算平均概率時,DecisionTreeClassifier和SVC的預測概率的計算權重是分類器KNeighborsClassifier的2倍。
  • 使用python+sklearn實現模型複雜性的影響
    matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1.parasite_axes import host_subplotfrom mpl_toolkits.axisartist.axislines import Axesfrom scipy.sparse.csr import csr_matrixfrom sklearn
  • 使用python+sklearn實現Lasso 模型選擇:交叉驗證/ AIC / BIC
    使用Akaike信息標準(AIC),貝葉斯信息標準(BIC)和交叉驗證來選擇Lasso
  • 運用sklearn進行線性判別分析(LDA)代碼實現
    基於sklearn的線性判別分析(LDA)代碼實現一、前言及回顧本文記錄使用sklearn庫實現有監督的數據降維技術——線性判別分析(LDA)。在上一篇LDA線性判別分析原理及python應用(葡萄酒案例分析),我們通過詳細的步驟理解LDA內部邏輯實現原理,能夠更好地掌握線性判別分析的內部機制。
  • 使用python+sklearn實現保序回歸
    注意:單擊此處https://urlify.cn/nE7Zny下載完整的示例代碼,或通過Binder在瀏覽器中運行此示例本文給出了在合成數據上使用保序回歸
  • 使用sklearn輕鬆實現數據縮放
    數據準備的過程主要包括3個步驟:本文會告訴你兩種方法,即如何使用Python的Scikit-Learn庫進行簡單的數據轉換。from sklearn.datasets import load_irisfrom sklearn import preprocessing# 加載數據iris = load_iris()print(iris.data.shape)# 分離原始數據集,分為自變量和因變量X = iris.datay = iris.target#
  • 校準曲線
    校準曲線是表述待測物質濃度與所測量儀器響應值的函數關係,制好校準曲線是取得準確測定結果的基礎。
  • 使用python+sklearn實現Logistic回歸中的L1懲罰與稀疏性
    Mathieu Blondel <mathieu@mblondel.org>#          Andreas Mueller <amueller@ais.uni-bonn.de># 許可證: BSD 3 clauseimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model
  • 使用python+sklearn實現在20newgroups上進行多類稀疏邏輯回歸
    在這裡,我們使用 l1 稀疏(l1 sparsity)將無信息特徵的權重調整為零。如果目標是提取每個班級的強判別詞彙,那麼這是一個很好的方法。如果目標是獲得最佳的預測準確性,則最好改用非稀疏誘導l2懲罰(non sparsity-inducing l2 penalty)。
  • 使用python+sklearn實現噪聲級別估計的高斯過程回歸
    Hendrik Metzen <jhm@informatik.uni-bremen.de>## 許可證: BSD 3 clauseimport numpy as npfrom matplotlib import pyplot as pltfrom matplotlib.colors import LogNormfrom sklearn.gaussian_process
  • 新手福音,機器學習工具Sklearn 中文文檔 0.19版(最新)
    降維sklearn把降維從數據預處理裡面拿了出來,當做是單獨的一塊,裡面包含了PCA、ICA以及一些更為複雜的方法,方便使用。模型選擇對一個問題,會有很多模型方法可以用,但是哪個是好,那個不好,需要根據建模分析的結果判斷,在sklearn中,提供了大量用於計算模型性能和結果的功能,交叉驗證、自動調參、量化預測、學習曲線等分析功能,方便進行模型性能分析。預處理主要針對特徵提取和歸一化處理。
  • 深度學習多種模型評估指標介紹 - 附sklearn實現
    roc曲線橫軸:負正類率FPR代表分類器預測的正類中實際負實例佔所有負實例的比例roc曲線縱軸:真正類率TPR代表分類器預測的正類中實際正實例佔所有正實例的比例例如我們設定一個閾值為0.6,概率大於等於0.6的為正例,小於0.6的為負例。