scikit-learn机器学习(二)逻辑回归进行二分类(垃圾邮件分类),二分类性能指标,画ROC曲线,计算acc,recall,presicion,f1
数据来自UCI机器学习仓库中的垃圾信息数据集
数据可从http://archive.ics.uci.edu/ml/datasets/sms+spam+collection下载
转成csv载入数据
import matplotlib
matplotlib.rcParams['font.sans-serif']=[u'simHei']
matplotlib.rcParams['axes.unicode_minus']=False
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model.logistic import LogisticRegression
from sklearn.model_selection import train_test_split,cross_val_score df = pd.read_csv('data/SMSSpamCollection.csv',header=None)
print(df.head) print("垃圾邮件个数:%s" % df[df[0]=='spam'][0].count())
print("正常邮件个数:%s" % df[df[0]=='ham'][0].count())

垃圾邮件个数:747
正常邮件个数:4825
创建TfidfVectorizer实例,将训练文本和测试文本都进行转换
X = df[1].values
y = df[0].values
X_train_raw,X_test_raw,y_train,y_test=train_test_split(X,y)
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(X_train_raw)
X_test = vectorizer.transform(X_test_raw)
建立逻辑回归模型训练和预测
LR = LogisticRegression()
LR.fit(X_train,y_train)
predictions = LR.predict(X_test)
for i,prediction in enumerate(predictions[:5]):
print("预测为 %s ,信件为 %s" % (prediction,X_test_raw[i]))
预测为 ham ,信件为 Send to someone else :-)
预测为 ham ,信件为 Easy ah?sen got selected means its good..
预测为 ham ,信件为 Sorry da. I gone mad so many pending works what to do.
预测为 ham ,信件为 What not under standing.
预测为 spam ,信件为 SIX chances to win CASH! From 100 to 20,000 pounds txt> CSH11 and send to 87575. Cost 150p/day, 6days, 16+ TsandCs apply Reply HL 4 info
二元分类性能指标:混淆矩阵
# In[2]二元分类分类指标
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
# predictions 与 y_test
confusion_matrix = confusion_matrix(y_test,predictions)
print(confusion_matrix)
plt.matshow(confusion_matrix)
plt.title("混淆矩阵")
plt.colorbar()
plt.ylabel("真实值")
plt.xlabel("预测值")
plt.show()

[[1217 1]
[ 52 123]]
准确率,召回率,精准率,F1值
# In[3] 给出 precision recall f1-score support
from sklearn.metrics import classification_report
print(classification_report(y_test,predictions)) from sklearn.metrics import roc_curve,auc
# 准确率
scores = cross_val_score(LR,X_train,y_train,cv=5)
print("准确率为: ",scores)
print("平均准确率为: ",np.mean(scores)) # 有时必须要将标签转为数值
from sklearn.preprocessing import LabelEncoder
class_le = LabelEncoder()
y_train_n = class_le.fit_transform(y_train)
y_test_n = class_le.fit_transform(y_test) # 精准率
precision = cross_val_score(LR,X_train,y_train_n,cv=5,scoring='precision')
print("平均精准率为: ",np.mean(precision))
# 召回率
recall = cross_val_score(LR,X_train,y_train_n,cv=5,scoring='recall')
print("平均召回率为: ",np.mean(recall))
# F1值
f1 = cross_val_score(LR,X_train,y_train_n,cv=5,scoring='f1')
print("平均F1值为: ",np.mean(f1))
准确率为: [0.96654719 0.95459976 0.95449102 0.9508982 0.96047904]
平均准确率为: 0.9574030433756144
平均精准率为: 0.9906631114805584
平均召回率为: 0.6956979405034325
平均F1值为: 0.8162874707978786
画出ROC曲线,AUC为ROC曲线以下部分的面积
# In[4] ROC曲线 y_test_n为数值
predictions_pro = LR.predict_proba(X_test)
false_positive_rate, recall, thresholds = roc_curve(y_test_n,predictions_pro[:,1])
roc_auc = auc(false_positive_rate, recall)
plt.title("受试者操作特征曲线(ROC)")
plt.plot(false_positive_rate, recall, 'b', label='AUC = % 0.2f' % roc_auc)
plt.legend(loc='lower right')
plt.plot([0,1],[0,1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.xlabel('假阳性率')
plt.ylabel('召回率')
plt.show()

所有代码:
# -*- coding: utf-8 -*-
import matplotlib
matplotlib.rcParams['font.sans-serif']=[u'simHei']
matplotlib.rcParams['axes.unicode_minus']=False
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model.logistic import LogisticRegression
from sklearn.model_selection import train_test_split,cross_val_score df = pd.read_csv('data/SMSSpamCollection.csv',header=None)
print(df.head) print("垃圾邮件个数:%s" % df[df[0]=='spam'][0].count())
print("正常邮件个数:%s" % df[df[0]=='ham'][0].count()) # In[1]
X = df[1].values
y = df[0].values
X_train_raw,X_test_raw,y_train,y_test=train_test_split(X,y)
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(X_train_raw)
X_test = vectorizer.transform(X_test_raw) LR = LogisticRegression()
LR.fit(X_train,y_train)
predictions = LR.predict(X_test)
for i,prediction in enumerate(predictions[:5]):
print("预测为 %s ,信件为 %s" % (prediction,X_test_raw[i])) # In[2]二元分类分类指标
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
# predictions 与 y_test
confusion_matrix = confusion_matrix(y_test,predictions)
print(confusion_matrix)
plt.matshow(confusion_matrix)
plt.title("混淆矩阵")
plt.colorbar()
plt.ylabel("真实值")
plt.xlabel("预测值")
plt.show() # In[3] 给出 precision recall f1-score support
from sklearn.metrics import classification_report
print(classification_report(y_test,predictions)) from sklearn.metrics import roc_curve,auc
# 准确率
scores = cross_val_score(LR,X_train,y_train,cv=5)
print("准确率为: ",scores)
print("平均准确率为: ",np.mean(scores)) # 必须要将标签转为数值
from sklearn.preprocessing import LabelEncoder
class_le = LabelEncoder()
y_train_n = class_le.fit_transform(y_train)
y_test_n = class_le.fit_transform(y_test) # 精准率
precision = cross_val_score(LR,X_train,y_train_n,cv=5,scoring='precision')
print("平均精准率为: ",np.mean(precision))
# 召回率
recall = cross_val_score(LR,X_train,y_train_n,cv=5,scoring='recall')
print("平均召回率为: ",np.mean(recall))
# F1值
f1 = cross_val_score(LR,X_train,y_train_n,cv=5,scoring='f1')
print("平均F1值为: ",np.mean(f1)) # In[4] ROC曲线 y_test_n为数值
predictions_pro = LR.predict_proba(X_test)
false_positive_rate, recall, thresholds = roc_curve(y_test_n,predictions_pro[:,1])
roc_auc = auc(false_positive_rate, recall)
plt.title("受试者操作特征曲线(ROC)")
plt.plot(false_positive_rate, recall, 'b', label='AUC = % 0.2f' % roc_auc)
plt.legend(loc='lower right')
plt.plot([0,1],[0,1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.xlabel('假阳性率')
plt.ylabel('召回率')
plt.show()
scikit-learn机器学习(二)逻辑回归进行二分类(垃圾邮件分类),二分类性能指标,画ROC曲线,计算acc,recall,presicion,f1的更多相关文章
- 机器学习二 逻辑回归作业、逻辑回归(Logistic Regression)
机器学习二 逻辑回归作业 作业在这,http://speech.ee.ntu.edu.tw/~tlkagk/courses/ML_2016/Lecture/hw2.pdf 是区分spam的. 57 ...
- 通俗地说逻辑回归【Logistic regression】算法(二)sklearn逻辑回归实战
前情提要: 通俗地说逻辑回归[Logistic regression]算法(一) 逻辑回归模型原理介绍 上一篇主要介绍了逻辑回归中,相对理论化的知识,这次主要是对上篇做一点点补充,以及介绍sklear ...
- 100天搞定机器学习|Day8 逻辑回归的数学原理
机器学习100天|Day1数据预处理 100天搞定机器学习|Day2简单线性回归分析 100天搞定机器学习|Day3多元线性回归 100天搞定机器学习|Day4-6 逻辑回归 100天搞定机器学习|D ...
- 100天搞定机器学习|Day4-6 逻辑回归
逻辑回归avik-jain介绍的不是特别详细,下面再唠叨一遍这个算法. 1.模型 在分类问题中,比如判断邮件是否为垃圾邮件,判断肿瘤是否为阳性,目标变量是离散的,只有两种取值,通常会编码为0和1.假设 ...
- 机器学习之分类器性能指标之ROC曲线、AUC值
分类器性能指标之ROC曲线.AUC值 一 roc曲线 1.roc曲线:接收者操作特征(receiveroperating characteristic),roc曲线上每个点反映着对同一信号刺激的感受性 ...
- [机器学习]-分类问题常用评价指标、混淆矩阵及ROC曲线绘制方法
分类问题 分类问题是人工智能领域中最常见的一类问题之一,掌握合适的评价指标,对模型进行恰当的评价,是至关重要的. 同样地,分割问题是像素级别的分类,除了mAcc.mIoU之外,也可以采用分类问题的一些 ...
- 【机器学习】逻辑回归(Logistic Regression)
注:最近开始学习<人工智能>选修课,老师提纲挈领的介绍了一番,听完课只了解了个大概,剩下的细节只能自己继续摸索. 从本质上讲:机器学习就是一个模型对外界的刺激(训练样本)做出反应,趋利避害 ...
- 机器学习 (三) 逻辑回归 Logistic Regression
文章内容均来自斯坦福大学的Andrew Ng教授讲解的Machine Learning课程,本文是针对该课程的个人学习笔记,如有疏漏,请以原课程所讲述内容为准.感谢博主Rachel Zhang 的个人 ...
- 机器学习:逻辑回归(OvR 与 OvO)
一.基础理解 问题:逻辑回归算法是用回归的方式解决分类的问题,而且只可以解决二分类问题: 方案:可以通过改造,使得逻辑回归算法可以解决多分类问题: 改造方法: OvR(One vs Rest),一对剩 ...
随机推荐
- 解决Centos /boot过小无法更新内核
Centos7默认安装时,/boot目录设置只有150M左右,这样编译几个版本的内核/boot空间就不够用了.报错大致如下: Disk Requirements: At least 3MB more ...
- Git学习笔记08-远程仓库
因为想在家里和公司都能用到一套代码,所以选择上传到github,记录一下使用经验. 需要安装git,和注册github 以下操作是第一次将自己的代码上传到GitHub上 1)创建github项目 1. ...
- c语言学习、工作相关必备的常用网站
1.https://zh.cppreference.com/,c.c++参考手册, 2.http://www.cplusplus.com/,在线查看c.c++函数的定义及用法 3.http://c-f ...
- JavaScript里的递增"++"和递减"--"
递增"++",表示在原来的数值上+1 tips:比如a=1,那么++a或者a++都等于2. 递减"--",表示再原来的数值上-1,前置/后置递减计算过程同递增 ...
- [Flutter] Stack Layout
Normally if you place three the same size icons in a stack, they will stands on top of each other, t ...
- 更改ejs模板引擎的后缀为html
安装 EJS 在项目目录右键->Open Command Prompt Here 输入 npm install ejs 打开app.js //app.set('view engine', 'ja ...
- box-orient
box-orient 语法: box-orient:horizontal | vertical | inline-axis | block-axis 默认值:horizontal 适用于:伸缩盒容器大 ...
- java新建excel文件导出(HSSFWorkbook)
public ActionForward exportExcel(ActionMapping mapping, ActionForm form, HttpServletRequest request, ...
- 参数类型 (@Controller层)
@RequestMapping(path = "/listPage")@SuppressWarnings("unchecked")@BussinessLog(v ...
- Spring Boot and Rabbit MQ 异常的时候消息的状态
我们有一个处理消息的方法. 在处理消息的时候出现了异常,那出现异常后这个消息会怎么处理呢. 根据我们的实际情况的观察,如果出现了异常. 但是你没有捕获或者处理异常,这个消息会一直存在,并且你的系统会持 ...