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

  • 第一篇 数据清洗与分析部分
  • 第二篇 可视化部分,
  • 第三篇 朴素贝叶斯文本分类
  • 支持向量机分类
  • 支持向量机 网格搜索
  • 临近法
  • 决策树
  • 随机森林
  • bagging方法
import pandas as pd
import numpy as np
import  matplotlib.pyplot as  plt
import time
df=pd.read_excel("all_data_meituan.xlsx")[["comment","star"]]
df.head()
comment star
0 还行吧,建议不要排队那个烤鸭和羊肉串,因为烤肉时间本来就不够,排那个要半小时,然后再回来吃烤... 40
1 去过好几次了 东西还是老样子 没增添什么新花样 环境倒是挺不错 离我们这也挺近 味道还可以 ... 40
2 一个字:好!!! #羊肉串# #五花肉# #牛舌# #很好吃# #鸡软骨# #拌菜# #抄河... 50
3 第一次来吃,之前看过好多推荐说这个好吃,真的抱了好大希望,排队的人挺多的,想吃得趁早来啊。还... 20
4 羊肉串真的不太好吃,那种说膻不膻说臭不臭的味。烤鸭还行,大虾没少吃,也就到那吃大虾了,吃完了... 30
df.shape
(17400, 2)
df['sentiment']=df['star'].apply(lambda x:1 if x>30 else 0)
df=df.drop_duplicates() ## 去掉重复的评论
df=df.dropna()
X=pd.concat([df[['comment']],df[['comment']],df[['comment']]])
y=pd.concat([df.sentiment,df.sentiment,df.sentiment])
X.columns=['comment']
X.reset_index
X.shape
(3138, 1)
import jieba
def chinese_word_cut(mytext):return " ".join(jieba.cut(mytext))
X['cut_comment']=X["comment"].apply(chinese_word_cut)
X['cut_comment'].head()
Building prefix dict from the default dictionary ...
Loading model from cache C:\Users\FRED-H~1\AppData\Local\Temp\jieba.cache
Loading model cost 0.651 seconds.
Prefix dict has been built succesfully.0    还行 吧 , 建议 不要 排队 那个 烤鸭 和 羊肉串 , 因为 烤肉 时间 本来 就 不够...
1    去过 好 几次 了   东西 还是 老 样子   没 增添 什么 新花样   环境 倒 是 ...
2    一个 字 : 好 ! ! !   # 羊肉串 #   # 五花肉 #   # 牛舌 #   ...
3    第一次 来 吃 , 之前 看过 好多 推荐 说 这个 好吃 , 真的 抱 了 好 大 希望 ...
4    羊肉串 真的 不太 好吃 , 那种 说 膻 不 膻 说 臭 不 臭 的 味 。 烤鸭 还 行...
Name: cut_comment, dtype: object
from sklearn.model_selection import  train_test_split
X_train,X_test,y_train,y_test= train_test_split(X,y,random_state=42,test_size=0.25)
def get_custom_stopwords(stop_words_file):with open(stop_words_file,encoding="utf-8") as f:custom_stopwords_list=[i.strip() for i in f.readlines()]return custom_stopwords_list
stop_words_file = "stopwords.txt"
stopwords = get_custom_stopwords(stop_words_file)
stopwords[-10:]
['100', '01', '02', '03', '04', '05', '06', '07', '08', '09']
from sklearn.feature_extraction.text import  CountVectorizer
vect=CountVectorizer()
vect
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=None,strip_accents=None, token_pattern='(?u)\\b\\w\\w+\\b',tokenizer=None, vocabulary=None)
vect.fit_transform(X_train["cut_comment"])
<2353x1965 sparse matrix of type '<class 'numpy.int64'>'with 20491 stored elements in Compressed Sparse Row format>
vect.fit_transform(X_train["cut_comment"]).toarray().shape
(2353, 1965)
# pd.DataFrame(vect.fit_transform(X_train["cut_comment"]).toarray(),columns=vect.get_feature_names()).iloc[:10,:22]
# print(vect.get_feature_names())
# #  数据维数1956,不算很大(未使用停用词)
vect = CountVectorizer(token_pattern=u'(?u)\\b[^\\d\\W]\\w+\\b',stop_words=frozenset(stopwords)) # 去除停用词
pd.DataFrame(vect.fit_transform(X_train['cut_comment']).toarray(), columns=vect.get_feature_names()).head()
# 1691 columns,去掉以数字为特征值的列,减少了三列编程1691
# max_df = 0.8 # 在超过这一比例的文档中出现的关键词(过于平凡),去除掉。
# min_df = 3 # 在低于这一数量的文档中出现的关键词(过于独特),去除掉。
amazing happy ktv pm2 一万个 一个多 一个月 一串 一人 一件 ... 麻烦 麻酱 黄喉 黄桃 黄花鱼 黄金 黑乎乎 黑椒 黑胡椒 齐全
0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
4 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0

5 rows × 1691 columns

from sklearn.pipeline import make_pipeline
from sklearn.svm import SVC
from sklearn import  metrics
svc_cl=SVC()
pipe=make_pipeline(vect,svc_cl)
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=...,max_iter=-1, probability=False, random_state=None, shrinking=True,tol=0.001, verbose=False))])
y_pred = pipe.predict(X_test.cut_comment)
metrics.accuracy_score(y_test,y_pred)
0.6318471337579618
metrics.confusion_matrix(y_test,y_pred)
array([[  0, 289],[  0, 496]], dtype=int64)

支持向量机分类

from sklearn.svm import SVC
svc_cl=SVC() # 实例化
pipe=make_pipeline(vect,svc_cl)
pipe.fit(X_train.cut_comment, y_train)
y_pred = pipe.predict(X_test.cut_comment)
metrics.accuracy_score(y_test,y_pred)
0.6318471337579618

支持向量机 网格搜索

from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
from sklearn.pipeline import  Pipeline
# svc=SVC(random_state=1)
from sklearn.linear_model import SGDClassifier
from sklearn.feature_extraction.text import TfidfTransformer
tfidf=TfidfTransformer()
# ('tfidf',
#                       TfidfTransformer()),
#                      ('clf',
#                       SGDClassifier(max_iter=1000)),
# svc=SGDClassifier(max_iter=1000)
svc=SVC()
# pipe=make_pipeline(vect,SVC)
pipe_svc=Pipeline([("scl",vect),('tfidf',tfidf),("clf",svc)])
para_range=[0.0001,0.001,0.01,0.1,1.0,10,100,1000]
para_grid=[{'clf__C':para_range,'clf__kernel':['linear']},{'clf__gamma':para_range,'clf__kernel':['rbf']}
]
gs=GridSearchCV(estimator=pipe_svc,param_grid=para_grid,cv=10,n_jobs=-1)
gs.fit(X_train.cut_comment,y_train)
GridSearchCV(cv=10, error_score='raise',estimator=Pipeline(memory=None,steps=[('scl', 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({'...,max_iter=-1, probability=False, random_state=None, shrinking=True,tol=0.001, verbose=False))]),fit_params=None, iid=True, n_jobs=-1,param_grid=[{'clf__C': [0.0001, 0.001, 0.01, 0.1, 1.0, 10, 100, 1000], 'clf__kernel': ['linear']}, {'clf__gamma': [0.0001, 0.001, 0.01, 0.1, 1.0, 10, 100, 1000], 'clf__kernel': ['rbf']}],pre_dispatch='2*n_jobs', refit=True, return_train_score='warn',scoring=None, verbose=0)
gs.best_estimator_.fit(X_train.cut_comment,y_train)
Pipeline(memory=None,steps=[('scl', 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({'...,max_iter=-1, probability=False, random_state=None, shrinking=True,tol=0.001, verbose=False))])
y_pred = gs.best_estimator_.predict(X_test.cut_comment)
metrics.accuracy_score(y_test,y_pred)
0.9503184713375796

临近法

from sklearn.neighbors import  KNeighborsClassifier
knn=KNeighborsClassifier(n_neighbors=5,p=2,metric='minkowski')
pipe=make_pipeline(vect,knn)
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=...owski',metric_params=None, n_jobs=1, n_neighbors=5, p=2,weights='uniform'))])
y_pred = pipe.predict(X_test.cut_comment)
metrics.accuracy_score(y_test,y_pred)
0.7070063694267515
metrics.confusion_matrix(y_test,y_pred)
array([[ 87, 202],[ 28, 468]], dtype=int64)

决策树

from sklearn.tree import DecisionTreeClassifier
tree=DecisionTreeClassifier(criterion='entropy',random_state=1)
pipe=make_pipeline(vect,tree)
pipe.fit(X_train.cut_comment, y_train)
y_pred = pipe.predict(X_test.cut_comment)
metrics.accuracy_score(y_test,y_pred)
0.9388535031847134
metrics.confusion_matrix(y_test,y_pred)
array([[256,  33],[ 15, 481]], dtype=int64)

随机森林


from sklearn.ensemble import RandomForestClassifier
forest=RandomForestClassifier(criterion='entropy',random_state=1,n_jobs=2)
pipe=make_pipeline(vect,forest)
pipe.fit(X_train.cut_comment, y_train)
y_pred = pipe.predict(X_test.cut_comment)
metrics.accuracy_score(y_test,y_pred)
# 加上tfidf反而准确率96.5降低至95.0,
0.9656050955414013
metrics.confusion_matrix(y_test,y_pred)
array([[265,  24],[  3, 493]], dtype=int64)

bagging方法

from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
tree=DecisionTreeClassifier(criterion='entropy',random_state=1)
bag=BaggingClassifier(base_estimator=tree,n_estimators=10,max_samples=1.0,max_features=1.0,bootstrap=True,bootstrap_features=False,n_jobs=1,random_state=1)
pipe=make_pipeline(vect,tfidf,bag)
pipe.fit(X_train.cut_comment, y_train)
y_pred = pipe.predict(X_test.cut_comment)
metrics.accuracy_score(y_test,y_pred)  #  没用转化td-idf 93.2%, 加上转化步骤,准确率提升到95.5
0.9554140127388535
metrics.confusion_matrix(y_test,y_pred)
array([[260,  29],[  6, 490]], dtype=int64)

posted on 2018-09-20 00:04 多一点 阅读(...) 评论(...) 编辑 收藏

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

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

    美团店铺评价语言处理以及文本分类(logistic regression) 美团店铺评价语言处理以及分类(LogisticRegression) 第一篇 数据清洗与分析部分 第二篇 可视化部分, 第三 ...

  2. python与算法社区_【Python算法】分类与预测——Python随机森林

    [Python算法]分类与预测--Python随机森林 1.随机森林定义 随机森林是一种多功能的机器学习算法,能够执行回归和分类的任务.同时,它也是一种数据降维手段,在处理缺失值.异常值以及其他数据探 ...

  3. 【RF分类】基于matlab随机森林算法数据分类【含Matlab源码 2048期】

    ⛄一.获取代码方式 获取代码方式1: 完整代码已上传我的资源:[RF分类]基于matlab随机森林算法数据分类[含Matlab源码 2048期] 获取代码方式2: 付费专栏Matlab智能算法神经网络 ...

  4. 分类树/装袋法/随机森林算法的R语言实现

    原文首发于简书于[2018.06.12] 本文是我自己动手用R语言写的实现分类树的代码,以及在此基础上写的袋装法(bagging)和随机森林(random forest)的算法实现.全文的结构是: 分 ...

  5. 【华为云技术分享】【Python算法】分类与预测——Python随机森林

    1.随机森林定义 随机森林是一种多功能的机器学习算法,能够执行回归和分类的任务.同时,它也是一种数据降维手段,在处理缺失值.异常值以及其他数据探索等方面,取得了不错的成效.另外,它还担任了集成学习中的 ...

  6. 基于6种监督学习(逻辑回归+决策树+随机森林+SVM+朴素贝叶斯+神经网络)的毒蘑菇分类

    公众号:尤而小屋 作者:Peter 编辑:Peter 大家好,我是Peter~ 本文是kaggle案例分享的第3篇,赛题的名称是:Mushroom Classification,Safe to eat ...

  7. 机器学习实战之分类算法(K-近邻/朴素贝叶斯/决策树/随机森林)

    机器学习分类算法 1. 机器学习算法简介 1.1 按照学习方式分类 1.2 区别 1.3 关于监督学习中的分类与回归区别 1.4 机器学习开发流程 2. 数据集介绍与划分 2.1 sklearn数据集 ...

  8. 基于逻辑回归/决策树/随机森林/多层感知分类器/xgboost/朴素贝叶斯分类的资讯多分类性能对比

    在上一篇(https://blog.csdn.net/baymax_007/article/details/82748544)中,利用逻辑回归实现资讯多分类.本文在之前基础上,又引入决策树.随机森林. ...

  9. sklearn决策树/随机森林多分类绘制ROC和PR曲线

    有篇讲解原理的博文/论文(可看可不看):<为什么Decision Tree可以绘制出ROC曲线?> 一.数据,并要先one-hot多分类标签 from sklearn.preprocess ...

最新文章

  1. 【设计模式】享元模式
  2. 智能医疗战场 人工智能如何赋能健康智能终端?
  3. 屏蔽浏览器退格键页面后退
  4. Java黑皮书课后题第5章:*5.1(统计正数和负数的个数然后计算这些数的平均值)编写程序,读入未指定个数的整数,判断读入的正数有多少个、负数有多少个,然后计算输入值的总和和平均值(不记0,浮点表示)
  5. oracle cusor 定义
  6. Linux 基础I/O :文件描述符,重定向,文件系统,软链接和硬链接,动态库和静态库
  7. 实战课堂:一则CPU 100%的故障分析处理知识和警示
  8. DelayQueue1.8源码
  9. linux ftp win nt,Java中apache包中FTPClient读取win NT上的FTP服务器文件失败
  10. vue改页面顶部浏览器标题栏图标、名称和地址栏详细教程
  11. 7450清零_联想M7450F打印机加粉清零方法
  12. ①万字《详解canvas api画图》小白前端入门教程(建议收藏)
  13. 【必做1】结对编程—词频统计
  14. 淘宝店铺如何装修呢?
  15. 2022山东老博会,山东养老展,中国国际养老服务业展9月举办
  16. matlab 方差计算
  17. python进行词频统计_如何利用Python进行文本词频统计
  18. CCS导入项目后中文是乱码
  19. mongodb文档操作1
  20. 上随体导数的一些理解

热门文章

  1. 无线打印机服务器属性,为什么我的打印机能在打印机
  2. 【论文】解读AM-GCN: Adaptive Multi-channel Graph Convolutional
  3. js 编写一个程序实现统计一串字符串中的英文小写字母个数!
  4. excel服务器条形码不显示,excel怎么制作条形码教程 excel条形码显示不出怎么办...
  5. 把计算机知识列表合为一列,怎么把相同表格的数据合并
  6. 晶体管共发射极应用电路
  7. HTTP 错误 404.5 - Not Found
  8. 团队合作开发的两种文档工具
  9. firefoxos :add ipdl
  10. android 记录打印文件