情感分析代码(阅读+书写+注释)

对影评数据进行NLP情感分类(二分类的问题)

kaggle竞赛试题地址:https://www.kaggle.com/c/word2vec-nlp-tutorial/
数据集地址:链接:https://pan.baidu.com/s/1eR27IG5LmSBULJHtYGQi2Q 提取码:gh70
复制这段内容后打开百度网盘手机App,操作更方便哦
注意事项-首先要对影评数据做一些预处理

  • 去掉html标签
  • 移除标点
  • 切分成词
  • 去除停用词
  • 重新组成新的句子

1- 第一步导入实验过程中所需要的包

import os
import re
import numpy as np
import pandas as pd

#解析网页
from bs4 import BeautifulSoup


from sklearn.feature_extraction.text import  CountVectorizer
from sklearn.ensemble import  RandomForestClassifier
#校验
from sklearn.metrics import confusion_matrix

import nltk
#nltk.download()

from nltk.corpus import stopwords

2-利用pandas读入训练数据

datafile="./labeledTrainData.tsv"
#以\t做切分
df = pd.read_csv(datafile,sep="\t",escapechar="\\")
print("Number of reviews:{}".format(len(df)))

3-提取表格中的第一条语句

raw_example=df["review"][0]

4-将语句中的html标签进行去除

# #BeautifulSoup(raw_example,"html.parser").get_text()用来对网页内容进行处理并且提取文字内容
example=BeautifulSoup(raw_example,"html.parser").get_text()

5-使用正则表达式去除标点符号

example_letters = re.sub(r"[^a-zA-Z]"," ",example)

6-进行大小写的统一

words=example_letters.lower().split()

7-去除停用词

words_notstop=[ w for w in words if w not in stopwords.words("english")]

所有的影评都要运用上面的处理所以将上面的几步处理写入到一个函数当中

eng_stopwords=set(stopwords.words("english"))

def clean_text(text):
    text=BeautifulSoup(text,"html_parser").get_text()
    text=re.sub(r"[a-zA-Z]"," ",text)
    words=text.lower().split()
    words=[ w for w in words if w not in eng_stopwords]
    #','.join('abc')-----'a,b,c'
    return " ".join(words)

调用函数对数据进行清洗

clean_text(raw_example)

将清洗数据添加到表格中,并且要对所有的影评进行清洗

#DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)
#对表格中的每一个review运用clean_text函数
df["clean_review"]=df.review.apply(clean_text)

使用bag of words特征

#CountVectorizer是属于常见的特征数值计算类,是一个文本特征提取方法
#CountVectorizer会将文本中的词语转换为词频矩阵,它通过fit_transform函数计算各个词语出现的次数
# max_features个作为关键词集
# CountVectorizer是通过fit_transform函数将文本中的词语转换为词频矩阵\toarray()可看到词频矩阵的结果
vectorizer=CountVectorizer(max_features=5000)
# 对df表格中的clean_review(清洗后的数据)使用CountVectorizer向量化
train_data_features=vectorizer.fit_transform(df.clean_review).toarray()

训练分类器

##训练分类器

forest = RandomForestClassifier(n_estimators=100)
forest=forest.fit(train_data_features,df.sentiment)

在训练集上验证

#在训练集上做predict验证效果
confusion_matrix(df.sentiment,forest.predict(train_data_features))

我们如果要对测试数据集进行测试时,要将测试数据集中的影评采用相同的数据清洗

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章