美团店铺评价语言处理以及分类(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类可以选择默认参数,如果模型预测能力不符合要求,可以适当调整
```python
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:Anaconda3envs
lplibsite-packagessklearnlinear_modelsag.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:Anaconda3envs
lplibsite-packagessklearnlinear_modelsag.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