#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. MapReduce 中的两表 join 几种方案简介

    转自:http://my.oschina.net/leejun2005/blog/95186 MapSideJoin例子:http://my.oschina.net/leejun2005/blog/1 ...

  2. Windows 安装、重装MySQL时,报错:could not start the service mysql

    原因: 卸载mysql时并没有完全删除相关文件和服务,需要手动清除. 解决方法: 首先,在管理工具->服务里面将MySQL的服务给停止(有的是没有安装成功,有这个服务,但是已经停止了的). 然后 ...

  3. Javascript特效代码大全(420个)(转)

    转载自:Javascript特效代码大全(420个) 收集资料,以便使用+面试+学习  ├ Cookie脚本 ├ 随访问次数变提示 ├ 集成Cookies ├ 使窗口仅弹出一次 ├ 签名提示程序 ├ ...

  4. 手机游戏运营主要的指标是什么? 7天活跃, 14天活跃 ARPU ?如何提升游戏 app 的虚拟道具的收入?

    数据采集越细,手段越丰富,所获得的数据也就更加详实,虽然手机游戏没有网游那么复杂,但也需要数据化运营,而且是必要的,是优化游戏收入的关键,大家最主要关心的是下面三类数据的指标 1. 用户数量首先,在移 ...

  5. MyBitis(iBitis)系列随笔之三:简单实现CRUD

    Mybitis(iBitis)实现对对象增删改查操作要借助<select/>查询,<insert/>增加,<update/>更新,<delete/>删除 ...

  6. Mock利器:PowerMock

    powerMock不仅支持接口mock,final类.静态类.静态方法.私有方法都支持mock,还是很强大的: 1.gradle引用: myonlycompile('org.powermock:pow ...

  7. iOS 功能代码 上传到 远程 码云私有库

    推送代码到远程私有库 创建私有库(注意:仓库名称LYDKit必须和本地仓库对应的名称一样) 复制远程仓库的地址,打开终端,cd到对应的本地库路径下面 >>> cd /Users/cx ...

  8. boost::archive::text_oarchive

    Serialization的中文解释是“串行化” .“序列化”或者“持久化” ,就是将内存中的对象保存到磁盘中,等到程序再次运行的时候再读取磁盘中的文件恢复原来的对象.下面来看一个简单的例子: #in ...

  9. datatables如何把列设置成hidden隐藏域?

    官网:https://datatables.net/reference/option/设置: visible: false如下: <!DOCTYPE html><html>&l ...

  10. JDK的图文安装教程

    JDK的安装 什么是JDK? JDK就是Java开发工具包,即Java Development Kit.就是做Java开发所需要的最基本的工具.包括Java编译器(把人使用的Java语言变成JVM能运 ...