對影評數據進行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))