美团店铺评价语言处理以及文本分类(logistic regression)

美团店铺评价语言处理以及分类(LogisticRegression)

  • 第一篇 数据清洗与分析部分
  • 第二篇 可视化部分,
  • 第三篇 朴素贝叶斯文本分类
  • 本文是该系列的第四篇 主要讨论逻辑回归分类算法的参数以及优化
  • 主要用到的包有jieba,sklearn,pandas,本篇博文主要先用的是词袋模型(bag of words),将文本以数值特征向量的形式来表示(每个文档构建一个特征向量,有很多的0,类似于前文说的category类的one-hot形式,得到的矩阵为稀疏矩阵)
  • 比较朴素贝叶斯方法,逻辑回归两种分类算法
  • 逻辑回归算法的参数细节以及参数调优

导入数据分析常用库

import pandas as pd
import numpy as np
  • 读取文件
df=pd.read_excel("all_data_meituan.xlsx")[["comment","star"]]
df.head()

上一博客中数据预处理,忘记的可以打开此链接复习

```

  • 直接上处理好的特征,如下

朴素贝叶斯作为文本界的快速分类,这次将他作为对比的初始模型,将朴素贝叶斯与逻辑回归进行比较

模型构建

  • 从sklearn 朴素贝叶斯中导入多维贝叶斯
  • 朴素贝叶斯通常用来处理文本分类垃圾短信,速度飞快,效果一般都不会差很多
  • MultinomialNB类可以选择默认参数,如果模型预测能力不符合要求,可以适当调整
from sklearn.naive_bayes import MultinomialNB
nb=MultinomialNB()  
from sklearn.pipeline import make_pipeline # 导入make_pipeline方法
pipe=make_pipeline(vect,nb)
pipe.steps #  查看pipeline的步骤(与pipeline相似)
[('countvectorizer',CountVectorizer(analyzer='word', binary=False, decode_error='strict',dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',lowercase=True, max_df=1.0, max_features=None, min_df=1,ngram_range=(1, 1), preprocessor=None,stop_words=frozenset({'', '范围', '但愿', 'vs', '为', '过去', '集中', '这般', '孰知', '认为', '论', '36', '前后', '每年', '长期以来', 'our', '要不', '使用', '好象', 'such', '不但', '一下', 'how', '召开', '6', '全体', '严格', '除开', 'get', '可好', '毕竟', 'but', '如前所述', '满足', 'your', 'keeps', '只', '大抵', '己', 'concerning', "they're", '再则', '有意的'...'reasonably', '绝对', '咧', '除此以外', '50', '得了', 'seeming', '只是', '背靠背', '弗', 'need', '其', '第二', '再者说'}),strip_accents=None, token_pattern='(?u)\\b[^\\d\\W]\\w+\\b',tokenizer=None, vocabulary=None)),('multinomialnb', MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True))]
pipe.fit(X_train.cut_comment, y_train)
Pipeline(memory=None,steps=[('countvectorizer', CountVectorizer(analyzer='word', binary=False, decode_error='strict',dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',lowercase=True, max_df=1.0, max_features=None, min_df=1,ngram_range=(1, 1), preprocessor=None,stop_words=...e, vocabulary=None)), ('multinomialnb', MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True))])

测试集预测结果

y_pred = pipe.predict(X_test.cut_comment)
# 对测试集进行预测(其中包括了转化以及预测)
# 模型对于测试集的准确率
from sklearn import  metrics
metrics.accuracy_score(y_test,y_pred)
0.82929936305732488

逻辑回归

模型构建

  • 首先使用默认的逻辑回归参数进行预实验
  • 默认参数为 solver = liblinear, max_iter=100,multi_class='ovr',penalty='l2'
  • 为了演示方便,我们没有把make_pipeline 改写为函数,而是单独的调用,使步骤更为清楚
from sklearn.linear_model import LogisticRegression
# lr=LogisticRegression(solver='saga',max_iter=10000)
lr=LogisticRegression()  # 实例化
pipe_lr=make_pipeline(vect,lr)
pipe_lr.steps
[('countvectorizer',CountVectorizer(analyzer='word', binary=False, decode_error='strict',dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',lowercase=True, max_df=1.0, max_features=None, min_df=1,ngram_range=(1, 1), preprocessor=None,stop_words=frozenset({'', 'besides', '中小', '不管怎样', '引起', '它们的', 'take', "c's", 'hopefully', 'no', '就算', '断然', '直到', 'some', '最后一班', '许多', '非独', '嘻', ':', '时', '两者', '惟其', '从优', 'so', 'specified', '50', 'sometimes', '明显', '嗬', '人家', '截至', '开始', '动不动', '大体', '以及', '使', 'own', 'whoever', "wasn't", 'cha...'我是', '/', 'my', '再则', '正常', '49', '关于', '愿意', '其他', '这么', '粗', 'c]', '$', '29', '要求', '第十一', '自后'}),strip_accents=None, token_pattern='(?u)\\b[^\\d\\W]\\w+\\b',tokenizer=None, vocabulary=None)),('logisticregression',LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,penalty='l2', random_state=None, solver='liblinear', tol=0.0001,verbose=0, warm_start=False))]
  • 逻辑回归模型默认参数,对应同样的测试集0.82929936305732488,还是提高了5%,这是在默认的solver情况下,未调整正则化等其余参数

测试集预测结果

pipe_lr.fit(X_train.cut_comment, y_train)
y_pred_lr = pipe_lr.predict(X_test.cut_comment)
metrics.accuracy_score(y_test,y_pred_lr)
0.87261146496815289
  • 现在我们将solver修改为saga,penalty默认是l2,重新进行模型拟合与预测
lr_solver = LogisticRegression(solver='saga')
pipe_lr1=make_pipeline(vect,lr_solver)
pipe_lr1.steps
[('countvectorizer',CountVectorizer(analyzer='word', binary=False, decode_error='strict',dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',lowercase=True, max_df=1.0, max_features=None, min_df=1,ngram_range=(1, 1), preprocessor=None,stop_words=frozenset({'', 'besides', '中小', '不管怎样', '引起', '它们的', 'take', "c's", 'hopefully', 'no', '就算', '断然', '直到', 'some', '最后一班', '许多', '非独', '嘻', ':', '时', '两者', '惟其', '从优', 'so', 'specified', '50', 'sometimes', '明显', '嗬', '人家', '截至', '开始', '动不动', '大体', '以及', '使', 'own', 'whoever', "wasn't", 'cha...'我是', '/', 'my', '再则', '正常', '49', '关于', '愿意', '其他', '这么', '粗', 'c]', '$', '29', '要求', '第十一', '自后'}),strip_accents=None, token_pattern='(?u)\\b[^\\d\\W]\\w+\\b',tokenizer=None, vocabulary=None)),('logisticregression',LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,penalty='l2', random_state=None, solver='saga', tol=0.0001,verbose=0, warm_start=False))]
pipe_lr1.fit(X_train.cut_comment, y_train)
C:\Anaconda3\envs\nlp\lib\site-packages\sklearn\linear_model\sag.py:326: ConvergenceWarning: The max_iter was reached which means the coef_ did not converge"the coef_ did not converge", ConvergenceWarning)Pipeline(memory=None,steps=[('countvectorizer', CountVectorizer(analyzer='word', binary=False, decode_error='strict',dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',lowercase=True, max_df=1.0, max_features=None, min_df=1,ngram_range=(1, 1), preprocessor=None,stop_words=...penalty='l2', random_state=None, solver='saga', tol=0.0001,verbose=0, warm_start=False))])
  • 出现这个提示,说明solver参数在saga(随机平均梯度下降)情况下,系数没有收敛,随机平均梯度需要更大的迭代次数,需要调整最大迭代次数max_iter
# C:\Anaconda3\envs\nlp\lib\site-packages\sklearn\linear_model\sag.py:326: ConvergenceWarning: The max_iter was reached which means the coef_ did not converge
#   "the coef_ did not converge", ConvergenceWarning)
# 出现这个提示,说明solver参数在saga(随机平均梯度下降)情况下,系数没有收敛,随机平均梯度需要更大的迭代次数,需要调整最大迭代次数max_iter
# 这里需要强调一点,这并不是说saga性能不好,saga针对大的数据集收敛速度比其他的优化算法更快。
  • 重新设定了mat_iter之后,进行重新拟合,准确率达到 0.87388535031847137,准确率微弱提升
lr_solver = LogisticRegression(solver='saga',max_iter=10000)
pipe_lr1=make_pipeline(vect,lr_solver)
pipe_lr1.steps
pipe_lr1.fit(X_train.cut_comment, y_train)
Pipeline(memory=None,steps=[('countvectorizer', CountVectorizer(analyzer='word', binary=False, decode_error='strict',dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',lowercase=True, max_df=1.0, max_features=None, min_df=1,ngram_range=(1, 1), preprocessor=None,stop_words=...penalty='l2', random_state=None, solver='saga', tol=0.0001,verbose=0, warm_start=False))])
y_pred_lr1 = pipe_lr1.predict(X_test.cut_comment)
metrics.accuracy_score(y_test,y_pred_lr1)
0.87388535031847137

这里补充一些关于逻辑回归的参数

  • solvers 优化模型

    • 相对与小规模数据liblinear的收敛速度更快,准确率与saga准确率相差无几
    • saga是sag的一种变体,同时支持两种正则化后面需进一步的调整正则化强度以及类别(l1,l2)
    • sklearn官网推荐一般情况下使用saga优化算法,同时支持l1,l2 正则化,而且对于大数据来说收敛速度更快。
    • sag,lbfgs,newton-cg支持l2正则化,对于多维数据收敛速度比较快(特征多),不支持l1正则,(损失函数需要一阶或者二阶连续导数)
    • saga 优化算法更适合在大规模数据集(数据量与特征量)都很大的情况,表现效果会非常好,saga优化算法支持l1正则化,可适用于多维的稀疏矩阵
    • liblinear 使用了开源的liblinear库实现,内部使用了坐标轴下降法来迭代优化损失函数,同时支持(l1,l2),不支持真正的多分类(通过ovr实现的多分类)
    • lbfgs:拟牛顿法的一种,利用损失函数二阶导数矩阵即海森矩阵来迭代优化损失函数。
    • newton-cg:也是牛顿法家族的一种,利用损失函数二阶导数矩阵即海森矩阵来迭代优化损失函数。
  • logitisct regression参数中的C是正则化系数λ的倒数(交叉验证参数Cs,list of floats 或者 int)

  • penalty 正则化选择参数(l1,l2)

  • multi_class 分类方式的选择参数(ovr,mvm)
    • ovr 五种方式都支持,mvm 不支持liblinear
  • class_weith 类型权重参数
    • class_weight={0:0.9,1:0.1} 表示类型0的权重为90%,类型1的权重是10%,如果选择class_weith='balanced',那么就根据训练样本来计算权重,某类的样本越多,则权重越低,样本量越少,则权重越高。
    • 误分类的代价很高,对于正常人与患病者进行分类,将患者划分为正常人的代价很大,我们宁愿将正常人分类为患者,这是还有进行人工干预,但是不愿意将患者漏检,这时我们可以将患者的权重适当提高
    • 第二种情况是 样本高度失衡,比如患者和正常人的比例是1:700,如果不考虑权重,很容易得到一个预测准确率非常高的分类器,但是没有啥意义,这是可以选择balanced参数,分类器会自动根据患者比例进行调整权重。
  • sample_weight 样本权重参数
    • 由于样本不平衡,导致样本不是总体样本的无偏估计,可能导致模型的检出率很低,调节样本权重有两种方式:
    • 在class_weight 使用balance参数,第二种是在fit(X, y, sample_weight=None) 拟合模型的时候,调整sample_weight
  • 迭代次数 max_iter 默认值100,有的优化算法在默认的迭代次数时,损失函数未收敛,需要调整迭代次数

LogisticRegressionCV优化参数

  • LogisticRegressionCV 方法 默认是l2正则化,solver设定为saga
t1=time.time()
from sklearn.linear_model import LogisticRegressionCV
lrvc = LogisticRegressionCV(Cs=[0.0001,0.005,0.001,0.05,0.01,0.1,0.5,1,10],scoring='accuracy',random_state=42,solver='saga',max_iter=10000,penalty='l2')
pipe=make_pipeline(vect,lrvc)
print(pipe.get_params)
pipe.fit(X_train.cut_comment, y_train)
y_pred=pipe.predict(X_test.cut_comment)
print(metrics.accuracy_score(y_test,y_pred))
t2=time.time()
print("time spent l2,saga",t2-t1)
<bound method Pipeline.get_params of Pipeline(memory=None,steps=[('countvectorizer', CountVectorizer(analyzer='word', binary=False, decode_error='strict',dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',lowercase=True, max_df=1.0, max_features=None, min_df=1,ngram_range=(1, 1), preprocessor=None,stop_words=... random_state=42, refit=True,scoring='accuracy', solver='saga', tol=0.0001, verbose=0))])>
0.899363057325
time spent l2,saga 5.017577648162842
  • LogisticRegressionCV 方法 solver设定为saga,l1正则化
t1=time.time()
from sklearn.linear_model import LogisticRegressionCV
lrvc = LogisticRegressionCV(Cs=[0.0001,0.005,0.001,0.05,0.01,0.1,0.5,1,10],scoring='accuracy',random_state=42,solver='saga',max_iter=10000,penalty='l1')
pipe_cvl1=make_pipeline(vect,lrvc)
print(pipe_cvl1.get_params)
pipe_cvl1.fit(X_train.cut_comment, y_train)
y_pred=pipe_cvl1.predict(X_test.cut_comment)
print(metrics.accuracy_score(y_test,y_pred))
t2=time.time()
print("time spent l1,saga",t2-t1)
<bound method Pipeline.get_params of Pipeline(memory=None,steps=[('countvectorizer', CountVectorizer(analyzer='word', binary=False, decode_error='strict',dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',lowercase=True, max_df=1.0, max_features=None, min_df=1,ngram_range=(1, 1), preprocessor=None,stop_words=... random_state=42, refit=True,scoring='accuracy', solver='saga', tol=0.0001, verbose=0))])>
0.915923566879
time spent l1,saga 64.17242479324341
  • l1正则化相比l2正则化,在saga优化器模式下,达到最佳参数所需要的时间增加

  • 同时我们又验证了liblinear与saga在l1正则化的情况下,达到最佳参数需要的时间,差距接近120倍

# LogisticRegressionCV 方法 l1正则化,sovler liblinear,速度比saga快的多,很快就收敛了,准确率没有什么差别,只是不支持真正的多分类(为liblinear 打call)
t3=time.time()
from sklearn.linear_model import LogisticRegressionCV
lrvc = LogisticRegressionCV(Cs=[0.0001,0.005,0.001,0.05,0.01,0.1,0.5,1,10],scoring='accuracy',random_state=42,solver='liblinear',max_iter=10000,penalty='l1')
pipe_cvl1=make_pipeline(vect,lrvc)
print(pipe_cvl1.get_params)
pipe_cvl1.fit(X_train.cut_comment, y_train)
y_pred=pipe_cvl1.predict(X_test.cut_comment)
print("accuracy":metrics.accuracy_score(y_test,y_pred))
t4=time.time()
print("time spent l1 liblinear ",t4-t3)
<bound method Pipeline.get_params of Pipeline(memory=None,steps=[('countvectorizer', CountVectorizer(analyzer='word', binary=False, decode_error='strict',dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',lowercase=True, max_df=1.0, max_features=None, min_df=1,ngram_range=(1, 1), preprocessor=None,stop_words=...om_state=42, refit=True,scoring='accuracy', solver='liblinear', tol=0.0001, verbose=0))])>
"accuracy":0.912101910828
time spent l1 liblinear  0.22439861297607422

后续还会包括其他的一些经典模型的构建以及优化,包括SVM(线性,核函数),decision tree,knn,同时也有集成的算法包括随机森林,bagging,GBDT等算法进行演示

posted on 2018-08-16 14:20 多一点 阅读(...) 评论(...) 编辑 收藏

美团店铺评价语言处理以及文本分类(logistic regression)相关推荐

  1. 美团店铺评价语言处理以及分类(tfidf,SVM,决策树,随机森林,Knn,ensemble)...

    美团店铺评价语言处理以及分类(tfidf,SVM,决策树,随机森林,Knn,ensemble) 第一篇 数据清洗与分析部分 第二篇 可视化部分, 第三篇 朴素贝叶斯文本分类 支持向量机分类 支持向量机 ...

  2. R语言构建xgboost文本分类模型(bag of words):xgb.cv函数交叉验证确定xgboost模型的最优子树个数、交叉验证获取最优子树之后构建最优xgboost模型并评估模型文本分类效能

    R语言构建xgboost文本分类模型(bag of words):xgb.cv函数交叉验证确定xgboost模型的最优子树个数.交叉验证获取最优子树之后构建最优xgboost模型并评估模型文本分类效能 ...

  3. 基于pandas python sklearn 的美团某商家的评论分类(文本分类)

    基于pandas python sklearn 的美团某商家的评论分类(文本分类) 美团店铺评价语言处理以及分类(NLP) 第一篇 数据分析部分 第二篇 可视化部分, 本文是该系列第三篇,文本分类 主 ...

  4. 多元有序logistic回归_医学统计与R语言:多分类logistic回归HosmerLemeshow拟合优度检验...

    微信公众号:医学统计与R语言如果你觉得对你有帮助,欢迎转发 输入1:multinominal logistic regression install.packages("nnet" ...

  5. 二元置信椭圆r语言_医学统计与R语言:多分类logistic回归HosmerLemeshow拟合优度检验...

    微信公众号:医学统计与R语言如果你觉得对你有帮助,欢迎转发 输入1:multinominal logistic regression "nnet") 结果1: test (mult ...

  6. NLP 模型“解语如神”的诀窍:在文本分类模型中注入外部词典

    一. 引言 现实世界的文本表述如恒河沙数,以惊人的速度变换着,人工智能(AI)在快速识别形形色色的文本之前,必须经过充足的训练数据洗礼.然而,面对复杂多变的文本表述,NLP 模型往往无法从有限的训练数 ...

  7. c语言贝叶斯分类,基于朴素贝叶斯分类器的文本分类算法(C语言)

    基于朴素贝叶斯分类器的文本分类算法(C语言) 基于朴素贝叶斯分类器的文本分类算法(C语言).txt两个人吵架,先说对不起的人,并不是认输了,并不是原谅了.他只是比对方更珍惜这份感情.#include ...

  8. R语言构建文本分类模型:文本数据预处理、构建词袋模型(bag of words)、构建xgboost文本分类模型、基于自定义函数构建xgboost文本分类模型

    R语言构建文本分类模型:文本数据预处理.构建词袋模型(bag of words).构建xgboost文本分类模型.基于自定义函数构建xgboost文本分类模型 目录

  9. R语言构建文本分类模型并使用LIME进行模型解释实战:文本数据预处理、构建词袋模型、构建xgboost文本分类模型、基于文本训练数据以及模型构建LIME解释器解释多个测试语料的预测结果并可视化

    R语言构建文本分类模型并使用LIME进行模型解释实战:文本数据预处理.构建词袋模型.构建xgboost文本分类模型.基于文本训练数据以及模型构建LIME解释器解释多个测试语料的预测结果并可视化 目录

最新文章

  1. LeetCode 36 Valid Sudoku(有效数独)(*)
  2. Git:如何从远程源主服务器更新/签出单个文件?
  3. C语言标准数学函数库math.h之常用函数介绍
  4. 写给大家看的机器学习书【Part1】什么是机器学习?机器学到的到底是什么?
  5. HttpContext.Current.Request.Url 地址:获取域名
  6. 基于ZooKeeper实现分布式锁
  7. lecture 4 : More Objective-C
  8. 【数据结构与算法】【算法思想】Dijkstra算法
  9. Java技术学习笔记:C/S 与B/S 区别
  10. 看看80万程序员怎么评论:前端程序员会不会失业?
  11. [译] 绘制路径:Android 中矢量图渲染
  12. 凯斯西储计算机科学,凯斯西储大学电气工程与计算机科学系基本信息详解
  13. JavaScript学习(五十一)—实训题
  14. Oracle 11g数据库基础教程(第2版)-课后习题-第十三章
  15. Vensim学习之Random Normal函数的使用
  16. idea 从svn 下载项目
  17. DVWA-low通关
  18. Linux 系统硬盘MBR转换为GPT格式并扩容
  19. Win10 Build 18237发布:登录屏幕启用毛玻璃特效
  20. 计算机二级有没有年龄,九龄童通过全国计算机二级 创年龄最小纪录(图)_新闻中心_新浪福建_新浪网...

热门文章

  1. 华三模拟器启动设备失败【启动设备MSR36-20_1失败】
  2. 两因素身份验证增强您的Spring Security
  3. Frontiers in Nutrition专刊征稿(IF 6.59, 王进/刘连亮/Zhongbin Deng
  4. 如何查看Android API文档
  5. 地理信息可视化大数据系统分析
  6. 转载 --史上最全数学符号、公式的英文读法,干货满满!
  7. 数据库 之 round函数
  8. DDR2 sodimm + Flash + Triple-Speed Ethernet + IO in nios
  9. 使用lorax 构建定制化操作系统
  10. 电子原理 半波整流与桥式整流Protues仿真电路