#encoding:utf-8
import pandas as pd
import numpy as np
from sklearn import datasets,linear_model
from sklearn.metrics import roc_curve,auc
import pylab as pl
from matplotlib.pyplot import plot def confusionMatrix(predicted,actual,threshold):
if len(predicted)!=len(actual):return -1
tp = 0.0
fp = 0.0
tn = 0.0
fn = 0.0
for i in range(len(actual)):
if actual[i]>0.5:
if predicted[i]>threshold:
tp += 1.0
else:
fn += 1.0
else:
if predicted[i]<threshold:
tn += 1.0
else:
fp += 1.0
rtn = [fp,fn,fp,tn]
return rtn
#获取数据
rockdata = open('sonar.all-data')
xList = []
labels = []
#将标签转换成数值,M转换成1.0,R转换为0.0
for line in rockdata:
row = line.strip().split(",")
if(row[-1] =='M'):
labels.append(1.0)
else:
labels.append(0.0)
row.pop()
floatRow = [float(num) for num in row]
xList.append(floatRow)
print labels
#获取数据的行数,通过对3的求余,将数据划分为2个子集,1/3的测试集,2/3的训练集
indices = range(len(xList))
xListTest = [xList[i] for i in indices if i%3==0]
xListTrain = [xList[i] for i in indices if i%3!=0]
labelsTest = [labels[i] for i in indices if i%3==0]
labelsTrain = [labels[i] for i in indices if i%3!=0]
#将列表转换成数组
xTrain = np.array(xListTrain)
yTrain = np.array(labelsTrain)
xTest = np.array(xListTest)
yTest = np.array(labelsTest)
#预测模型
rocksVMinesModel = linear_model.LinearRegression()
#训练数据
rocksVMinesModel.fit(xTrain,yTrain)
# 预测训练数据
trainingPredictions = rocksVMinesModel.predict(xTrain)
print ("---------",trainingPredictions[0:5],trainingPredictions[-6:-1])
#生成训练数据的混淆矩阵
confusionMatTrain = confusionMatrix(trainingPredictions,yTrain,0.5)
print confusionMatTrain
#预测测试数据
testPredictions = rocksVMinesModel.predict(xTest)
#生成测试数据的混淆矩阵
confusionTest = confusionMatrix(testPredictions,yTest,0.5)
print confusionTest
#通过roc_curve函数计算fpt,tpr,并计算roc_auc,AUC越高代表越好
fpr,tpr,thresholds = roc_curve(yTrain,trainingPredictions)
roc_auc = auc(fpr,tpr)
print roc_auc
#生成训练集上的ROC曲线
#plot roc curve
pl.clf()#清楚图形,初始化图形的时候需要
pl.plot(fpr,tpr,label='ROC curve (area=%0.2f)' %roc_auc)#画ROC曲线
pl.plot([0,1],[0,1],'k-')#生成对角线
pl.xlim([0.0,1.0])#X轴范围
pl.ylim([0.0,1.0])#Y轴范围
pl.xlabel('False Positive Rate')#X轴标签显示
pl.ylabel('True Positive Rate')#Y轴标签显示
pl.title('In sample ROC rocks versus mines')#标题
pl.legend(loc="lower left")#图例位置
pl.show() #生成测试集上的ROC曲线
fpr,tpr,thresholds = roc_curve(yTest,testPredictions)
roc_auc = auc(fpr,tpr)
print roc_auc
#plot roc curve
pl.clf()
pl.plot(fpr,tpr,label='ROC curve (area=%0.2f)' %roc_auc)
pl.plot([0,1],[0,1],'k-')
pl.xlim([0.0,1.0])
pl.ylim([0.0,1.0])
pl.xlabel('False Positive Rate')
pl.ylabel('True Positive Rate')
pl.title('In sample ROC rocks versus mines')
pl.legend(loc="lower right")
pl.show() 训练集上的ROC曲线

测试集上的ROC曲线

												

python 随机分类的更多相关文章

  1. Python随机生成验证码的两种方法

    Python随机生成验证码的方法有很多,今天给大家列举两种,大家也可以在这个基础上进行改造,设计出适合自己的验证码方法方法一:利用range Python随机生成验证码的方法有很多,今天给大家列举两种 ...

  2. 用python随机生成数据,再插入到postgresql中

    用python随机生成学生姓名,三科成绩和班级数据,再插入到postgresql中. 模块用psycopg2 random import random import psycopg2 fname=[' ...

  3. python 文本分类

    python 文本分类 pyhton 机器学习 待续...

  4. 13、Selenium+python+API分类总结

    Selenium+python+API分类总结 http://selenium-python.readthedocs.org/index.html 分类 方法 方法描述 客户端操作 __init__( ...

  5. python随机生成个人信息

    python随机生成个人信息 #!/usr/bin/env python3 # -*- coding:utf-8 -*- import sys import random class Personal ...

  6. 【机器学习实验】学习Python来分类现实世界的数据

    引入 一个机器能够依据照片来辨别鲜花的品种吗?在机器学习角度,这事实上是一个分类问题.即机器依据不同品种鲜花的数据进行学习.使其能够对未标记的測试图片数据进行分类. 这一小节.我们还是从scikit- ...

  7. python入门-分类和回归各种初级算法

    引自:http://www.cnblogs.com/taichu/p/5251332.html ########################### #说明: # 撰写本文的原因是,笔者在研究博文“ ...

  8. python + sklearn ︱分类效果评估——acc、recall、F1、ROC、回归、距离

    之前提到过聚类之后,聚类质量的评价: 聚类︱python实现 六大 分群质量评估指标(兰德系数.互信息.轮廓系数) R语言相关分类效果评估: R语言︱分类器的性能表现评价(混淆矩阵,准确率,召回率,F ...

  9. python 多分类任务中按照类别分层采样

    在机器学习多分类任务中有时候需要针对类别进行分层采样,比如说类别不均衡的数据,这时候随机采样会造成训练集.验证集.测试集中不同类别的数据比例不一样,这是会在一定程度上影响分类器的性能的,这时候就需要进 ...

随机推荐

  1. Servlet开发-----基础及MVC设计模式

    一.Servlet介绍   Servlet本身只是普通的Java类,只有当容器为他创建了ServletConfig和ServletContext时才成为了一个Servlet:   Servlet简单的 ...

  2. 一个简单的AJAX示例(转)

    转载自:http://www.cnblogs.com/rubylouvre/archive/2013/01/08/2851051.html,为了防备面试,备份一份吧!! 虽然现在有了框架,许多AJAX ...

  3. 如何在ChemDraw中输入℃温度符号

    化学反应常常对于温度是有一定要求的,所以用ChemDraw化学绘图工具在绘制化学反应的时候常常会用到℃温度符号.但是一些才接触ChemDraw的用户朋友不知道怎么输入℃.针对这种情况本教程来给大家分享 ...

  4. angular使用codemirror ui-codemirror在模态框或者tab中没有缩进,内容也会在点击之后才显示的问题

    <textarea ui-codemirror="{ mode: 'javascript', lineNumbers: true, theme: 'solarized dark', l ...

  5. Visual Studio Code调试node.js:无法在PATH上找到运行时的node

    首先,环境变量Path中加入nodejs的路径: 验证nodejs是否已经加入环境变量: 接着,重新启动Visual Studio Code, 试一下,是不是好了~   附录:Visual Studi ...

  6. python+selenium之简单介绍继承

    python+selenium之简单介绍继承 一.此例简单的介绍一下继承 1.面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过继承机制.继承完全可以理解成类之间的类型和子类型 ...

  7. 1-2、superset国际化

    最近由于工作需要研究开源可视化项目superset,由于其国际化做不怎么好,故而记录下国际化的过程,本篇本着『授人以鱼不如授人以渔』的原则,只叙述国际化的过程及方法,不提供直接的国际化文件. 为了方便 ...

  8. M451 PWM对照数据手册分析

    PWM_T Struct Reference Control Register » Pulse Width Modulation Controller(PWM)   typedef struct { ...

  9. deviceready has not fired after 5 seconds

    deviceready has not fired after 5 seconds 建议用手机连上电脑,用真机进行调试:

  10. [LintCode] 最多有多少个点在一条直线上

    /** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(i ...