1.数据准备

跟之前的文本一样,还是原来的数据格式。

sentence,label
游戏太坑,暴率太低,太克金,平民不能玩,negative
让人失望,negative
能解决一下服务器问题?网络正常老掉线,换手机也一样。。。,negative
期待,positive
一星也不想给,这特么简直龟速,炫舞老年版?,negative
衣服不好看游戏内容无特色,界面乱糟糟的,negative
喜欢喜欢,positive
从有了这个手游就一直玩,很喜欢呀,希望更多漂漂衣服,positive
因违反评价条例规定被折叠,negative

2.数据预处理

import time
import jieba
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
import xgboost as xgbdef get_stop_words():filename = "your stop words file path"stop_word_list = []with open(filename, encoding='utf-8') as f:for line in f.readlines():stop_word_list.append(line.strip())return stop_word_listdef processing_sentence(x, stop_words):cut_word = jieba.cut(str(x).strip())words = [word for word in cut_word if word not in stop_words and word != ' ']return ' '.join(words)def data_processing():train_file = "your train file path"df = pd.read_csv(train_file)x_train, x_test, y_train, y_test = train_test_split(df['sentence'], df['label'], test_size=0.1)stop_words = get_stop_words()x_train = x_train.apply(lambda x: processing_sentence(x, stop_words))x_test = x_test.apply(lambda x: processing_sentence(x, stop_words))tf = TfidfVectorizer()x_train = tf.fit_transform(x_train)x_test = tf.transform(x_test)x_train_weight = x_train.toarray()x_test_weight = x_test.toarray()return x_train_weight, x_test_weight, y_train, y_test

文本预处理得到的,仍然是分词以后的tf-idf特征。

3.模型训练

def train_model():x_train_weight, x_test_weight, y_train, y_test = data_processing()start = time.time()print("start time is: ", start)model = xgb.XGBClassifier(max_depth=4, learning_rate=0.1, n_estimators=100,silent=False, objective='binary:logistic')model.fit(x_train_weight, y_train)end = time.time()print("end time is: ", end)print("cost time is: ", (end - start))y_predict = model.predict(x_test_weight)confusion_mat = metrics.confusion_matrix(y_test, y_predict)print('准确率:', metrics.accuracy_score(y_test, y_predict))print("confusion_matrix is: ", confusion_mat)print('分类报告:', metrics.classification_report(y_test, y_predict))

代码训练运行的结果为

start time is:  1649228843.700035
end time is:  1649229253.274875
cost time is:  409.57483983039856
准确率: 0.7524366471734892
confusion_matrix is:  [[137  80][ 47 249]]
分类报告:               precision    recall  f1-score   supportnegative       0.74      0.63      0.68       217positive       0.76      0.84      0.80       296accuracy                           0.75       513macro avg       0.75      0.74      0.74       513
weighted avg       0.75      0.75      0.75       513

4.xgboost参数

xgb的参数还是比较多的,而且在实际使用过程中,调参也是比较重要的一环,下面我们一起看看xgb里面的参数。

xgb自身参数

    booster: stringSpecify which booster to use: gbtree, gblinear or dart.n_jobs : intNumber of parallel threads used to run xgboost.  (replaces ``nthread``)verbosity : intThe degree of verbosity. Valid values are 0 (silent) - 3 (debug).scale_pos_weight : floatBalancing of positive and negative weights.

booster指定树的类型,默认值为gbtree。
scale_pos_weight主要是处理样本不平衡问题,默认值为1。当样本高度不平衡的时候,比如正负样本比为1:100,可以将scale_pos_weight=10,加快模型收敛。

tree参数

    n_estimators : intNumber of trees to fit.max_depth : intMaximum tree depth for base learners.min_child_weight : intMinimum sum of instance weight(hessian) needed in a child.gamma : floatMinimum loss reduction required to make a further partition on a leaf node of the tree.max_delta_step : intMaximum delta step we allow each tree's weight estimation to be.subsample : floatSubsample ratio of the training instance.colsample_bytree : floatSubsample ratio of columns when constructing each tree.

n_estimators:树棵数
max_depth:树最大深度
min_child_weight:每棵树上的叶子节点样本权重和的最小值
gamma:在每棵树上进行进一步分裂所需要的最小损失函数减小值
max_delta_step:每棵树的最大权重
subsample:每棵树训练时每个样本被抽样选择的概率
colsample_bytree:每棵树训练时使用的特征比例

算法通用参数

    learning_rate : floatBoosting learning rate (xgb's "eta")objective : string or callableSpecify the learning task and the corresponding learning objective ora custom objective function to be used (see note below).reg_alpha : float (xgb's alpha)L1 regularization term on weightsreg_lambda : float (xgb's lambda)L2 regularization term on weights

objective包括:
回归任务
reg:linear (默认)
reg:logistic

二分类
binary:logistic 概率
binary:logitraw 类别

多分类
multi:softmax num_class=n 返回类别
multi:softprob num_class=n 返回概率

排序
rank:pairwise

5.参数总结

调整树模型复杂度的参数

n_estimators
max_depth
min_chlid_weight
gamma

增加树随机性的参数

subsample
colsample_bytree
learning_rate
num_round

解决样本不平衡

scale_pos_weight

6.画出特征重要性

将train方法的代码稍作修改,加入刻画特征重要性代码

import matplotlib.pyplot as plt
from xgboost import plot_importancedef train_model():x_train_weight, x_test_weight, y_train, y_test = data_processing()start = time.time()print("start time is: ", start)model = xgb.XGBClassifier(max_depth=4, learning_rate=0.1, n_estimators=50, n_jobs=2,silent=False, objective='binary:logistic')model.fit(x_train_weight, y_train)end = time.time()print("end time is: ", end)print("cost time is: ", (end - start))y_predict = model.predict(x_test_weight)confusion_mat = metrics.confusion_matrix(y_test, y_predict)print('准确率:', metrics.accuracy_score(y_test, y_predict))print("confusion_matrix is: ", confusion_mat)print('分类报告:', metrics.classification_report(y_test, y_predict))fig, ax = plt.subplots(figsize=(15, 15))plot_importance(model,height=0.5,ax=ax,max_num_features=10)plt.show()

最后会输出如下图

上面的图像就将F值排前十的特征进行了可视化。

使用xgboost进行文本分类相关推荐

  1. 文本分类实战--从TFIDF到深度学习(附代码)

    转自:http://blog.csdn.net/liuchonge/article/details/72614524 这几周因为在做竞赛所以没怎么看论文刷题写博客,今天抽时间把竞赛用到的东西总结一下. ...

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

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

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

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

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

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

  5. R语言构建文本分类模型:文本数据预处理、构建词袋模型(bag of words)、构建xgboost文本分类模型、xgboost模型预测推理并使用混淆矩阵评估模型、可视化模型预测的概率分布

    R语言构建文本分类模型:文本数据预处理.构建词袋模型(bag of words).构建xgboost文本分类模型.xgboost模型预测推理并使用混淆矩阵评估模型.可视化模型预测的概率分布 目录

  6. Task01——零基础入门NLP - 新闻文本分类之赛题理解

    本篇目标 首先本篇文章会对赛题进行介绍以及个人对赛题的理解,带大家接触NLP的预处理.模型构建和模型训练等知识点. 赛题介绍 赛题名称:零基础入门NLP - 新闻文本分类 赛题任务:赛题以自然语言处理 ...

  7. python分类流程_文本分类指南:你真的要错过 Python 吗?

    雷锋网按:本文为雷锋字幕组编译的技术博客,原标题 A Comprehensive Guide to Understand and Implement Text Classification in Py ...

  8. 手把手教你在Python中实现文本分类(附代码、数据集)

    作者: Shivam Bansal 翻译:申利彬 校对:丁楠雅 本文约2300字,建议阅读8分钟. 本文将详细介绍文本分类问题并用Python实现这个过程. 引言 文本分类是商业问题中常见的自然语言处 ...

  9. 基于协同训练的半监督文本分类算法

    标签: 半监督学习,文本分类 作者:炼己者 --- 本博客所有内容以学习.研究和分享为主,如需转载,请联系本人,标明作者和出处,并且是非商业用途,谢谢! 如果大家觉得格式看着不舒服,也欢迎大家去看我的 ...

最新文章

  1. [Contest20171109]函数(lipshitz)
  2. 利用dns解析来实现网站的负载均衡
  3. [转载]图的割点、桥与双连通分支
  4. 基于JT/T808 协议的GPS解析分享 C#
  5. .Net Core报“‘GB2312‘ is not a supported encoding name. For information on defining a custom encod”的错误
  6. Scrapy框架的使用之Spider Middleware的用法
  7. PN结是什么?PN结有什么特征?PN结的应用
  8. mysql创建数据库sql语句_创建数据库的SQL语句:mysql数据库
  9. python123第九周测验答案2020_2020知到答案 大数据分析的python基础 最新智慧树满分章节测试答案...
  10. 利用Scrapy爬取豆瓣电影
  11. mysql instead of触发_mysql 触发器
  12. win10系统任务栏不显示最小化窗口的处理步骤
  13. 计算机加域后桌面文件去哪里找,登录域桌面文件丢失
  14. 用别人的githut账号在自己电脑上拉取代码问题
  15. 华三计算机网络笔试题,软考网络工程师试题
  16. 我的架构师之路——书单
  17. Cesium入门(五):加载WMTS瓦片地图服务
  18. H5活动邀请函用这个就可以了
  19. 关于云ERP系统的错误看法
  20. 这3种直觉思维,会让你越来越“穷”!

热门文章

  1. Dijkstra算法总结(C/C++)
  2. gitlab配置自带Nginx实现网段访问限制、gitlab配置访问黑白名单、gitlab访问IP限制
  3. java计算机毕业设计牙科诊所管理系统源码+系统+lw+数据库+调试运行
  4. PCI、PCIX、PCIE、CPCI介绍
  5. python中category是什么类型_如何识别python中的维基百科类别
  6. Unity中利用C#开发泡泡龙游戏
  7. [原创] PS美女转手绘效果
  8. Python | 双均线策略进行交易
  9. 推荐10大协作工具,测试团队必备
  10. 装修费用的一些计算公式