Detecting Insults in Social Commentary 数据分析报告(python)
文章目录
- Detecting Insults in Social Commentary 数据分析报告
- 报告摘要
- 一、问题描述
- 二、数据加载
- 三、文本数据处理
- 3.1 数据清洗
- 3.2 停止词处理
- 3.3 文本词干化处理
- 3.4 计算词频矩阵
- 四、模型构建与评估
- 4.1 划分训练集和测试集数据
- 4.2 利用逻辑斯蒂模型建模
- 4.3 利用L1正则化建模
Detecting Insults in Social Commentary 数据分析报告
报告摘要
- 目标:本分析旨在利用文本数据判断一个评论是否为侮辱性评论。
- 方法:对评论数据进行数据清洗、停止词处理、词干化基础上,构建词频矩阵,利用逻辑斯蒂回归和L1正则化的逻辑回归对评论是否为侮辱性评论进行判断。
- 结论:对测试集数据进行测试后,发现模型具有一定的判断效果。
目录
- 问题描述
- 数据加载
- 文本数据处理
- 数据清洗
- 停止词处理
- 文本词干化处理
- 计算词频矩阵
- 模型构建与评估
- 划分训练集和测试集
- 利用逻辑斯蒂模型建模
- L1正则化建模
一、问题描述
本问题旨在判断一个评论是否为侮辱性评论。每个样本由一句/一段评论构成,判断每个评论是否为针对个人的侮辱性评论。
变量名 | 含义 |
---|---|
Insult | 评论是否为侮辱性评论 |
Date | 评论时间 |
Comment | 评论内容 |
二、数据加载
# 加载所需的python库
import statsmodels.api as sm
import statsmodels.formula.api as smf
import statsmodels.graphics.api as smg
import patsy
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
from scipy import stats
import seaborn as sns
#载入train数据集
traindata = pd.read_csv("D:/学习/数据挖掘与机器学习/homework week3/train.csv")
train = traindata
# 查看前五条数据
train.head()
Insult | Date | Comment | |
---|---|---|---|
0 | 1 | 20120618192155Z | "You fuck your dad." |
1 | 0 | 20120528192215Z | "i really don't understand your point.\xa0 It ... |
2 | 0 | NaN | "A\\xc2\\xa0majority of Canadians can and has ... |
3 | 0 | NaN | "listen if you dont wanna get married to a man... |
4 | 0 | 20120619094753Z | "C\xe1c b\u1ea1n xu\u1ed1ng \u0111\u01b0\u1edd... |
# 训练集中共有3947条数据,其中Insult和Comment没有缺失值,Date有718条缺失。
train.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3947 entries, 0 to 3946
Data columns (total 3 columns):
Insult 3947 non-null int64
Date 3229 non-null object
Comment 3947 non-null object
dtypes: int64(1), object(2)
memory usage: 123.3+ KB
三、文本数据处理
3.1 数据清洗
# 构建数据清洗函数、去掉标点等符号
import re
def preprocessor(text):text = re.sub('<[^>]*>', '', text)emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text)text = re.sub('[\W]+', ' ', text.lower()) + \' '.join(emoticons).replace('-', '')return text
# 利用构建的函数进行数据清洗
train.Comment = train.Comment.apply(preprocessor)
train.Comment[1]
' i really don t understand your point xa0 it seems that you are mixing apples and oranges '
3.2 停止词处理
# 载入停止词库
import nltk
nltk.download('stopwords')
[nltk_data] Downloading package stopwords to
[nltk_data] C:\Users\yunlai\AppData\Roaming\nltk_data...
[nltk_data] Package stopwords is already up-to-date!True
# 去掉停止词
from nltk.corpus import stopwords
stop = stopwords.words('english')
[w for w in train.Comment if w not in stop]
train.Comment.head()
0 you fuck your dad
1 i really don t understand your point xa0 it s...
2 a xc2 xa0majority of canadians can and has be...
3 listen if you dont wanna get married to a man...
4 c xe1c b u1ea1n xu u1ed1ng u0111 u01b0 u1eddn...
Name: Comment, dtype: object
3.3 文本词干化处理
from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()
def tokenizer_porter(text):return [porter.stem(word) for word in text.split()]
# 词干化
train.Comment = train.Comment.apply(tokenizer_porter)
train.Comment[0]
['you', 'fuck', 'your', 'dad']
# 编写函数、将词干化后的词连接
def join_data(text):text = ' '.join(text)return text
train.Comment = train.Comment.apply(join_data)
train.Comment[1]
'i realli don t understand your point xa0 it seem that you are mix appl and orang'
3.4 计算词频矩阵
from sklearn.feature_extraction.text import TfidfTransformer
tfidf = TfidfTransformer(use_idf=True, norm='l2', smooth_idf=True)
from sklearn.feature_extraction.text import CountVectorizer
count = CountVectorizer()
# 计算每个词的词频矩阵
comment = tfidf.fit_transform(count.fit_transform(train.Comment)).toarray()
comment =DataFrame(comment)
# 将计算结果合并到数据集中
train = pd.merge(train,comment,left_index = True, right_index = True)
四、模型构建与评估
4.1 划分训练集和测试集数据
data = train
del data["Date"]
del data["Comment"]
data.head()
Insult | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | ... | 12691 | 12692 | 12693 | 12694 | 12695 | 12696 | 12697 | 12698 | 12699 | 12700 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 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 × 12702 columns
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, roc_curve,roc_auc_score,classification_report
from sklearn.cross_validation import cross_val_score
from sklearn.cross_validation import train_test_split
train_y = data.Insult
train_x = data
del train_x["Insult"]
train_x['intercept'] = 1.0
train_x.head()
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ... | 12692 | 12693 | 12694 | 12695 | 12696 | 12697 | 12698 | 12699 | 12700 | intercept | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
5 rows × 12702 columns
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(train_x, train_y, test_size=0.3, random_state=0)
4.2 利用逻辑斯蒂模型建模
# 考虑到样本数据量较少,构建随机森林等模型效果可能不好,故构建逻辑斯蒂模型
clf = LogisticRegression()
clf.fit(X_train,y_train)
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)
# 利用模型进行预测
clf.predict(X_test)
array([0, 0, 0, ..., 0, 0, 1], dtype=int64)
preds = clf.predict(X_test)
# 计算混淆矩阵
confusion_matrix(y_test,preds)
array([[840, 22],[197, 126]])
# 计算roc_auc得分
pre = clf.predict_proba(X_test)
roc_auc_score(y_test,pre[:,1])
0.89364858166981531
# 画出roc曲线
fpr,tpr,thresholds = roc_curve(y_test,pre[:,1])
fig,ax = plt.subplots(figsize=(8,5))
plt.plot(fpr,tpr)
ax.set_title("Roc of Logistic Regression")
<matplotlib.text.Text at 0xdb08018278>
4.3 利用L1正则化建模
# 参数调整,C=2
lrtrain = LogisticRegression(penalty='l1', C=2)
lrtrain.fit(X_train,y_train)
LogisticRegression(C=2, class_weight=None, dual=False, fit_intercept=True,intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,penalty='l1', random_state=None, solver='liblinear', tol=0.0001,verbose=0, warm_start=False)
# 利用模型预测,构建混淆矩阵
preds2 = lrtrain.predict(X_test)
confusion_matrix(y_test,preds2)
array([[809, 53],[146, 177]])
# 计算roc_auc得分
pre2 = lrtrain.predict_proba(X_test)
roc_auc_score(y_test,pre2[:,1])
0.8920287616817395
# 画出roc曲线
fpr,tpr,thresholds = roc_curve(y_test,pre2[:,1])
fig,ax = plt.subplots(figsize=(8,5))
plt.plot(fpr,tpr)
ax.set_title("Roc of Logistic Regression L1")
<matplotlib.text.Text at 0xdb03a28160>
逻辑斯蒂模型和L1正则化的逻辑斯蒂模型roc_auc 得分分别为0.87和0.89,说明模型具有一定效果。
Detecting Insults in Social Commentary 数据分析报告(python)相关推荐
- python 豆瓣评论数据分析_Python爬虫实战案例:豆瓣影评大数据分析报告之网页分析...
个人希望,通过这个完整的爬虫案例(预计总共4篇短文),能够让爬虫小白学会怎么做爬虫的开发,所以在高手们看来,会有很多浅显的废话,如果觉得啰嗦,可以跳过一些内容~ 上一篇文章给大家简单介绍了Python ...
- python数据分析并生成报告_pandas_profiling :教你一行代码生成数据分析报告
分析报告全貌 什么是探索性数据分析 熟悉pandas的童鞋估计都知道pandas的describe()和info()函数,用来查看数据的整体情况,比如平均值.标准差之类,就是所谓的探索性数据分析-ED ...
- python数据分析报告主题_【原创】python主题LDA建模和t-SNE可视化数据分析报告论文(代码数据)...
python 主题 LDA 建模和 t - SNE 可视化 数据分析报告
- Titantic乘客生还预测数据分析报告—基于python实现
Titantic乘客生还预测数据分析报告-基于python实现 1. 问题提出 2. 数据描述 3. 特征独立分析 4. 数据处理 5. 模型评估 1. 问题提出 Titantic数据集是Kaggle ...
- 如何使用Python生成数据分析报告
逛知乎的时候看到这样一个提问,Python自动化办公能做那些有趣或者有用的事情? 看了一下这个提问,我想这可能是很多职场人面临的困惑,想把Python用到工作中来提升效率,却不知如何下手?Python ...
- Python办公自动化|一键生成数据分析报告
前两天逛知乎的时候看到这样一个提问,Python自动化办公能做那些有趣或者有用的事情? 看了一下这个提问,我想这可能是很多职场人面临的困惑,想把Python用到工作中来提升效率,却不知如何下手?Pyt ...
- python商业数据分析报告范文_python自动化撰写数据分析报告
在工作中经常要出具各种报告,我们可以根据报告周期来设置定时任务自动生成数据分析报告.首先要确定报告模板,给模板中的每一个变动值赋予一个参数:然后根据业务需求再python中定义每个变动值的计算方式:最 ...
- 用Python自动生成数据分析报告
公众号后台回复"图书",了解更多号主新书内容 作者:林骥 来源:林骥 很多时候,我们需要做一些重复性的工作,比如说,每个月制作类似的数据分析报告,整个框架是基本固定的,此时,我们可 ...
- 用Python自动生成数据分析报告!
来源:林骥 你好,我是林骥. 很多时候,我们需要做一些重复性的工作,比如说,每个月制作类似的数据分析报告,整个框架是基本固定的,此时,我们可以采用 Python 来自动生成数据分析报告,把更多的时间和 ...
最新文章
- C++调用Python文件,TensorFlow和PyTorch构建的深度学习模型,无法使用GPU的情况分析。
- 快讯 | 第二届数据标准化及治理大会成功举办,清华力量助推中国数据标准化建设
- NYOJ 267 郁闷的C小加(二)
- .net 事件委托 java_仿net事件委托的java事件模型实现(转csdn)
- qt 中文转十六进制_QT中16进制字符串转汉字
- C语言开发笔记(八)static
- 第四章信息系统安全基础考试要点及真题分布
- 06_Jedis完成MySQL的条件查询案例
- 微信为什么没有公众号导航
- 年报掘金:机构增仓路线图曝光(2010-03-06转载)
- PRD之道:4个撰写PRD的关键思路
- 前端每日实战:91# 视频演示如何用纯 CSS 创作一个行驶中的火车 loader
- PLC凸轮指令编程应用(SMART PLC凸轮FC)
- 通过分析周榜前100名专家的博客文章 手把手教你写出爆款文章
- Android studio 打包项目,抛出异常keystore was tampered with,or password was incorrect!
- android sepolicy 最新小结
- 解决pprint安装不上 | pprint_一个漂亮的打印机
- 继承 inherit
- 2020 年 11 月编程语言排行榜
- git可视化工具gitg和SmartGit
热门文章
- 前端面试题 —— 飞机加油问题
- 动态加载烘培贴图与Terrain转mesh
- 码教授|信息流的那点事:为什么信息流如此流行
- 涉密计算机与涉密网络管理制度,长沙理工大学网络涉密保密管理制度
- 办公室服务器文件管理制度,办公室文件管理制度
- 笔记本更换网络连接,MAC地址改变!
- 怎么用VLOOKUP来匹配excel表里面的数据
- 【Godot游戏开发案例《FlappyBird》小练习 】
- 计算机在无纸化办公系统中应用属于,0506非计算机专业和计算机专业基础部分会考练习题.doc...
- H264/AVC Hypothetical Reference Decoder(HRD)