python ks曲線 python之KS曲線

2021-10-11 12:53:38 字數 1907 閱讀 7315

# 自定義繪製ks曲線的函式

def plot_ks(y_test, y_score, positive_flag):

# 對y_test,y_score重新設定索引

y_test.index = np.arange(len(y_test))

#y_score.index = np.arange(len(y_score))

# 構建目標資料集

target_data = pd.dataframe()

# 按y_score降序排列

target_data.sort_values(by = 『y_score』, ascending = false, inplace = true)

# 自定義分位點

cuts = np.arange(0.1,1,0.1)

# 計算各分位點對應的score值

index = len(target_data.y_score)*cuts

scores = target_data.y_score.iloc[index.astype(『int』)]

# 根據不同的score值,計算sensitivity和specificity

sensitivity =

specificity =

for score in scores:

# 正例覆蓋樣本數量與實際正例樣本量

positive_recall = target_data.loc[(target_data.y_test == positive_flag) & (target_data.y_score>score),:].shape[0]

positive = sum(target_data.y_test == positive_flag)

# 負例覆蓋樣本數量與實際負例樣本量

negative_recall = target_data.loc[(target_data.y_test != positive_flag) & (target_data.y_score<=score),:].shape[0]

negative = sum(target_data.y_test != positive_flag)

# 構建繪圖資料

plot_data = pd.dataframe()

# 尋找sensitivity和1-specificity之差的最大值索引

max_ks_index = np.argmax(plot_data.ks)

plt.plot([0]+cuts.tolist()+[1], [0]+plot_data.y1.tolist()+[1], label = 『1-specificity』)

plt.plot([0]+cuts.tolist()+[1], [0]+plot_data.y2.tolist()+[1], label = 『sensitivity』)

# 新增參考線

plt.vlines(plot_data.cuts[max_ks_index], ymin = plot_data.y1[max_ks_index],

ymax = plot_data.y2[max_ks_index], linestyles = 『–『)

# 新增文字資訊

plt.text(x = plot_data.cuts[max_ks_index]+0.01,

y = plot_data.y1[max_ks_index]+plot_data.ks[max_ks_index]/2,

s = 『ks= %.2f』 %plot_data.ks[max_ks_index])

# 顯示圖例

plt.legend()

# 顯示圖形

plt.show()

# 呼叫自定義函式,繪製k-s曲線

plot_ks(y_test = y_test, y_score = y_score, positive_flag = 1)

ROC曲線 PR曲線

在 的結果分析中,roc和pr曲線是經常用到的兩個有力的展示圖。1.roc曲線 roc曲線 receiver operating characteristic 是一種對於靈敏度進行描述的功能影象。roc曲線可以通過描述真陽性率 tpr 和假陽性率 fpr 來實現。由於是通過比較兩個操作特徵 tpr和...

Python KS檢驗以及其餘非引數檢驗的實現

4 其餘的非引數檢驗 5 參考 定義 檢驗乙個分布f x 與理論分布g x 比如正態分佈 是否一致,或兩個觀測值分布是否有顯著差異的檢驗方法 根據定義,ks檢驗可以分為兩大類 對應的原假設和備擇假設分別為 第一種 h0 指定數列服從特定分布 h1 指定數列不服從特定分布 第二種 h0 兩個數列分布一...

P R曲線和ROC曲線

混淆矩陣又稱錯誤矩陣,指每個類別下,模型 結果的類別和數量在乙個矩陣中展示出來。真實標籤 為正 為負 真實為正 tpfn 真實為負 fptn 又稱為 tpr true positive rate 或者 敏感度sensitivity 通俗理解 真實為正的樣本中識別為正的佔比。t pr tpt p fn...