python之KS曲线

Python012

python之KS曲线,第1张

# 自定义绘制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_test':y_test, 'y_score':y_score})

    # 按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)

        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))})

    # 寻找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)

matplotlib 是Python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图。而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中。

它的文档相当完备,并且 Gallery页面 中有上百幅缩略图,打开之后都有源程序。因此如果你需要绘制某种类型的图,只需要在这个页面中浏览/复制/粘贴一下,基本上都能搞定。

在Linux下比较著名的数据图工具还有gnuplot,这个是免费的,Python有一个包可以调用gnuplot,但是语法比较不习惯,而且画图质量不高。

而 Matplotlib则比较强:Matlab的语法、python语言、latex的画图质量(还可以使用内嵌的latex引擎绘制的数学公式)。

快速绘图

matplotlib的pyplot子库提供了和matlab类似的绘图API,方便用户快速绘制2D图表。例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

#

coding=gbk

'''

Created

on Jul 12,2014

python

科学计算学习:numpy快速处理数据测试

@author:

皮皮

'''

importstring

importmatplotlib.pyplot

as plt

importnumpy

as np

if__name__

== '__main__':

file

= open(E:machine_learningdatasetshousing_datahousing_data_ages.txt, 'r')

linesList

= file.readlines()

#

print(linesList)

linesList

= [line.strip().split(,) forline

in linesList]

file.close()

print(linesList:)

print(linesList)

#

years = [string.atof(x[0])forx

in linesList]

years

= [x[0]forx

in linesList]

print(years)

price

= [x[1]forx

in linesList]

print(price)

plt.plot(years,

price, 'b*')#,label=$cos(x^2)$)

plt.plot(years,

price, 'r')

plt.xlabel(years(+2000))

plt.ylabel(housing

average price(*2000yuan))

plt.ylim(0,15)

plt.title('line_regression

&gradient decrease')

plt.legend()

plt.show()