본문 바로가기

NPL with ML

감성 분석 (Sentiment Analysis) - 지도학습 기반

반응형

감성 분석에 있어 지도 학습은 학습 데이터와 타깃 레이블 값을 기반으로 감성 분석 학습을 수행한 뒤 이를 기반으로 다른 데이터의 감성 분석을 예측하는 방법으로 일반적인 텍스트 기반의 분류와 거의 동일합니다.

 

실습데이타는 이곳에서 다운로드합니다. [링크] labeledTrainData.tsv 이 화일을 다운로드하면 됩니다.

 

1. 화일 다운로드 후 불필요한 내용을 정리하기 위한 string 정리를 합니다.

import pandas as pd
import re

review_df = pd.read_csv('C:\\Users\\HANA\\PycharmProjects\\HANATOUR\\NLP\\TEXT_Example\\labeledTrainData.tsv', header=0, sep="\t", quoting=3)

print(review_df.head())
# print(review_df['review'][0])

#불필요한 내용 정리 하기에서 위와 아래는 동일한 내용
review_df['review'] = review_df['review'].str.replace('<br />', ' ')
review_df['review'] = review_df['review'].apply(lambda x : re.sub("[^a-zA-Z]"," ", x))

아래와 같은 내용으로 데이터가 존재합니다. id, sentiment, review feature입니다.

         id  sentiment                                             review
0  "5814_8"          1  "With all this stuff going down at the moment ...
1  "2381_9"          1  "\"The Classic War of the Worlds\" by Timothy ...
2  "7759_3"          0  "The film starts with a manager (Nicholas Bell...
3  "3630_4"          0  "It must be assumed that those who praised thi...
4  "9495_8"          1  "Superbly trashy and wondrously unpretentious ...

 

2. train_test_split를 위해 데이타 정리 

from sklearn.model_selection import train_test_split

class_df = review_df['sentiment']
print(class_df)

feature_df = review_df.drop(['id','sentiment'], axis=1, inplace=False)
print(feature_df)

X_train, X_test, y_train, y_test = train_test_split(feature_df, class_df, test_size=0.3, random_state=156)
print(X_train.shape, X_test.shape)

 

3. Review 텍스트를 피처 벡터화한 후에 ML분류 알고리즘을 적용합니다. PIpline 객체를 이용해 두 가지를 한 번에 시행합니다. 먼저 CountVectorizer를 이용하여 예측 성능을 측정합니다. Classfier는 LogisticRegression을 이용합니다. 예측 성능 평가는 이진 분류 평가를 위해 테스트 데이터 세트의 정확도와 ROC-AUC를 측정합니다.

from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, roc_auc_score

pipline = Pipeline([
    ('cnt_vect', CountVectorizer(stop_words='english', ngram_range=(1,2))),
    ('lt_clf', LogisticRegression(C=10))])
    
#Pipline 객체를 이용해 fit(), prefit()로 학습/예측 수행, predict_proba()는 roc_auc때문에 수행
pipline.fit(X_train['review'], y_train)
pred = pipline.predict(X_test['review'])
pred_prods = pipline.predict_proba(X_test['review'])[:, 1]
print(accuracy_score(y_test, pred), roc_auc_score(y_test, pred_prods))

 

0.886 0.9502703875483725

 

동일한 방법으로 TF-IDF벡터화를 이용해 예측합니다. 결과를 보면 TF-IDF방법이 좀 더 예측 성능이 좋습니다.

#스톱 워드는 English, Filtering, ngram은 (1,2)로 설정해 TfidfVectorizer 수행
#LogisticRegression의 C는 10으로 설정
pipline = Pipeline([
    ('tfidf_vect', TfidfVectorizer(stop_words='english', ngram_range=(1,2))),
    ('lt_clf', LogisticRegression(C=10))])

pipline.fit(X_train['review'], y_train)
pred = pipline.predict(X_test['review'])
pred_prods = pipline.predict_proba(X_test['review'])[:, 1]
print(accuracy_score(y_test, pred), roc_auc_score(y_test, pred_prods))

 

0.8936 0.959799823582973

 

반응형