#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. 多媒体开发之分场图像和交错图像interlacing---一个破解版的迅雷云点播网站

    [-] 目录 编辑描述 编辑去交错方法 编辑去交错源自电影的影像 编辑去交错交错式影像 编辑单一场去交错intra-field deinterlacing 编辑场间去交错inter-field dei ...

  2. 书籍:Building Secure PHP Apps

    Building Secure PHP Apps https://leanpub.com/buildingsecurephpapps

  3. maven+springmvc错误 JAX-RS (REST Web Services) 2.0 can not be installed

    项目problem提示错误 JAX-RS (REST Web Services) 2.0 can not be installed : One or more constraints have not ...

  4. uva 610(tarjan的应用)

    题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=23727 思路:首先是Tarjan找桥,对于桥,只能是双向边,而对于 ...

  5. hdu 2821(dfs)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2821 思路:一开始的时候没注意到,必须从map[i][j]==0的位置开始,然后就是dfs了,回溯的时 ...

  6. PHP后台代码解决跨域问题

      在前端里面,解决跨域的时候总显得那么的恶心,什么jsonp啊,ajax啊,CORS啊什么的,总觉得是在钻空子进行跨域,其实在PHP文件里面只需要加一段代码就可以跨域了,前端你该怎么写还是怎么写,p ...

  7. 重写equals()方法也要重写hashcode()方法

    如果我们对equals方法进行了重写,建议一定要对hashCode方法重写,以保证相同的对象返回相同的hash值,不同的对象返回不同的hash值.

  8. excel如何将一个工作薄中的工作表生成独立的工作薄

    excel如何将一个工作薄中的工作表生成独立的工作薄  '用vba代码 Sub 另存所有工作表为工作簿() Dim sht As Worksheet Application.ScreenUpdatin ...

  9. LeetCode 笔记系列15 Set Matrix Zeroes [稍微有一点hack]

    题目:Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Fol ...

  10. 第一个MapReduce的例子

    第一个MapReduce的例子 Hadoop Guide的第一个MapReduce的例子是处理气象数据的(数据来源ncdc),终于跑通了.总结一下步骤,安装hadoop不在本文中介绍 1 数据预处理 ...