数据来自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的更多相关文章

  1. 机器学习二 逻辑回归作业、逻辑回归(Logistic Regression)

    机器学习二 逻辑回归作业   作业在这,http://speech.ee.ntu.edu.tw/~tlkagk/courses/ML_2016/Lecture/hw2.pdf 是区分spam的. 57 ...

  2. 通俗地说逻辑回归【Logistic regression】算法(二)sklearn逻辑回归实战

    前情提要: 通俗地说逻辑回归[Logistic regression]算法(一) 逻辑回归模型原理介绍 上一篇主要介绍了逻辑回归中,相对理论化的知识,这次主要是对上篇做一点点补充,以及介绍sklear ...

  3. 100天搞定机器学习|Day8 逻辑回归的数学原理

    机器学习100天|Day1数据预处理 100天搞定机器学习|Day2简单线性回归分析 100天搞定机器学习|Day3多元线性回归 100天搞定机器学习|Day4-6 逻辑回归 100天搞定机器学习|D ...

  4. 100天搞定机器学习|Day4-6 逻辑回归

    逻辑回归avik-jain介绍的不是特别详细,下面再唠叨一遍这个算法. 1.模型 在分类问题中,比如判断邮件是否为垃圾邮件,判断肿瘤是否为阳性,目标变量是离散的,只有两种取值,通常会编码为0和1.假设 ...

  5. 机器学习之分类器性能指标之ROC曲线、AUC值

    分类器性能指标之ROC曲线.AUC值 一 roc曲线 1.roc曲线:接收者操作特征(receiveroperating characteristic),roc曲线上每个点反映着对同一信号刺激的感受性 ...

  6. [机器学习]-分类问题常用评价指标、混淆矩阵及ROC曲线绘制方法

    分类问题 分类问题是人工智能领域中最常见的一类问题之一,掌握合适的评价指标,对模型进行恰当的评价,是至关重要的. 同样地,分割问题是像素级别的分类,除了mAcc.mIoU之外,也可以采用分类问题的一些 ...

  7. 【机器学习】逻辑回归(Logistic Regression)

    注:最近开始学习<人工智能>选修课,老师提纲挈领的介绍了一番,听完课只了解了个大概,剩下的细节只能自己继续摸索. 从本质上讲:机器学习就是一个模型对外界的刺激(训练样本)做出反应,趋利避害 ...

  8. 机器学习 (三) 逻辑回归 Logistic Regression

    文章内容均来自斯坦福大学的Andrew Ng教授讲解的Machine Learning课程,本文是针对该课程的个人学习笔记,如有疏漏,请以原课程所讲述内容为准.感谢博主Rachel Zhang 的个人 ...

  9. 机器学习:逻辑回归(OvR 与 OvO)

    一.基础理解 问题:逻辑回归算法是用回归的方式解决分类的问题,而且只可以解决二分类问题: 方案:可以通过改造,使得逻辑回归算法可以解决多分类问题: 改造方法: OvR(One vs Rest),一对剩 ...

随机推荐

  1. I2C总线、设备、驱动

    I2C总线.设备.驱动 框架 I2C驱动框架可分为3个部分,分别是:I2C核心层.I2C总线驱动层(适配器层)以及I2C设备驱动层: I2C核心层 提供了统一的I2C操作函数,主要有两套函数smbus ...

  2. c++初步认识

    经过漫长的C学习终于踏入C++的知识库当中了,还是保持以前的习惯会一步步通过写博客的形式来记录点滴学习记录,这种学习方式是相当慢的,但是对我来说是最踏实的,不浮躁,一步一个脚印.C++是一门啥语言呢, ...

  3. 可能是最全面的 Python 字符串拼接总结

    来源: 枫恋寒 链接: https://segmentfault.com/a/119000001.png"font-size: 12px;"> 在 Python 中字符串连接 ...

  4. Android-File读写+SharedPreferences的存取地址

    写了两个demo,一个是使用SharedPreferences将数据存储在应用文件中并读取,另一个是使用Context的openFileOutput和openFileInput将数据存储在应用文件中并 ...

  5. HDU-3341-Lost's revenge(AC自动机, DP, 压缩)

    链接: https://vjudge.net/problem/HDU-3341 题意: Lost and AekdyCoin are friends. They always play "n ...

  6. AttributeError: 'int' object has no attribute 'upper'

    因为安装的openpyxl版本是2.3.4,而代码是: sheet.cell(rownumber, 1).value = data['id']参数不对,应该是: sheet.cell(None, ro ...

  7. 001_linux基础命令

    开局日常吹牛一小时,今天更新的是linux的基础命令.现在是2018/5/30,晴,心情挺好的. 回归正题,linux基础命令只是一些初学者常用的命令,如果其他更多高级的命令等我学我再发上来,因为这个 ...

  8. csp-s模拟测试77+78(lrd day1&2)

    RP-=inf....... 一场考试把rp败光...由于本次考试本人在考试中乱说自己AK导致rp--,本人当选为机房倒数第二没素质 不过AK一次还挺开心的... 达哥出的题还是比较简单的. T1:考 ...

  9. laotech老师唠科mac 深入浅出MAC OS X

    laotech老师唠科mac 深入浅出MAC OS X http://study.163.com/plan/planLearn.htm?id=1637004#/learn/resVideo?lesso ...

  10. 【Python】使用Beautiful Soup等三种方式定制Jmeter测试脚本

    背景介绍 我们在做性能调优时,时常需要根据实际压测的情况,调整线程组的参数,比如循环次数,线程数,所有线程启动的时间等. 如果是在一台Linux机器上,就免不了在本机打开图形页面修改,然后最后传递到压 ...