实战
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def plot_ks(y_test, y_score, positive_flag):
y_test.index = np.arange(len(y_test))
target_data = pd.DataFrame({'y_test':y_test, 'y_score':y_score})
target_data.sort_values(by = 'y_score', ascending = False, inplace = True)
cuts = np.arange(0.1,1,0.1)
index = len(target_data.y_score)*cuts
scores = np.array(target_data.y_score)[index.astype('int')]
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)
Sensitivity.append(positive_recall/positive)
Specificity.append(negative_recall/negative)
plot_data = pd.DataFrame({'cuts':cuts,'y1':1-np.array(Specificity),'y2':np.array(Sensitivity),
'ks':np.array(Sensitivity)-(1-np.array(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()
virtual_data = pd.read_excel(r'virtual_data.xlsx')
plot_ks(y_test = virtual_data.Class, y_score = virtual_data.Score,positive_flag = 'P')