【NLP】在機(jī)器學(xué)習(xí)中開發(fā)情感分析器的5種方法
編譯 | VK
來源 | Towards Data Science

情感分析是一種自然語言處理技術(shù),用于確定給定文本的情感或觀點(diǎn)。情感分析模型可以通過從自然語言中提取意義并將其分配分?jǐn)?shù)來預(yù)測給定的文本數(shù)據(jù)是正的、負(fù)的還是中性的。
開發(fā)或訓(xùn)練情緒分析模型有多種方法,本文中我們將討論5種不同的方法:
定制訓(xùn)練監(jiān)督模型 TextBlob 基于詞典的模型 Bert 基于命名實(shí)體的情感分析器
定制訓(xùn)練監(jiān)督模型:
收集原始標(biāo)記數(shù)據(jù)集進(jìn)行情緒分析。 文本預(yù)處理 文本的數(shù)字編碼 選擇合適的ML算法 調(diào)參與訓(xùn)練ML模型 預(yù)測

TextBlob:
patternalyzer:(默認(rèn))基于模式庫。 NaiveBayesAnalyzer:一個基于電影評論語料庫的NLTK分類器。
安裝:
pip install -U textblob
實(shí)施:
from textblob import TextBlob
from textblob.sentiments import NaiveBayesAnalyzer, PatternAnalyzer
text = 'I liked the movie, the actors performance was too good.'
# NaiveBayesAnalyzer
blob = TextBlob(text, analyzer=NaiveBayesAnalyzer())
print(blob.sentiment)
# PatternAnalyzer
blob = TextBlob(text, analyzer=PatternAnalyzer())
print(blob.sentiment)
基于詞典的模型
輸入文本中的每個積極詞都會增加情感得分,而消極詞則會減少情感得分。 將最后的情緒分?jǐn)?shù)除以該文本中的字?jǐn)?shù),以使分?jǐn)?shù)標(biāo)準(zhǔn)化。
實(shí)施:
import nltk
pos_words = []
neg_words = []
def compute_sentiment_score(text):
sentiment_score = 0
words = nltk.word_tokenize(text)
for word in words:
if word in pos_words:
print('pos:',word)
sentiment_score=sentiment_score+1
if word in neg_words:
print('neg:',word)
sentiment_score=sentiment_score-1
return sentiment_score/len(words)
with open('datapath') as file:
for line in file:
line_attrib = line.split()
word = line_attrib[2].split('=')[1] #2nd column in the file
polarity = line_attrib[-1].split('=')[1] #last column in the file
if polarity =='positive':
pos_words.append(word)
elif polarity=='negative':
neg_words.append(word)
print('Total positive words found: ',len(pos_words))
print('Total negative words found: ',len(neg_words))
text = 'I loved the movie, the actors performance was mindblowing.'
sentiment = compute_sentiment_score(text)
print('The sentiment score of this text is: {:.2f}'.format(sentiment))
BERT:
安裝Transformer庫 加載BERT分類器和標(biāo)記器 創(chuàng)建已處理的數(shù)據(jù)集 配置和訓(xùn)練加載的BERT模型,并對其超參數(shù)進(jìn)行微調(diào) 進(jìn)行情緒分析預(yù)測
實(shí)現(xiàn):
基于命名實(shí)體的情感分析器:
第一步是在文本語料庫中找到所有命名實(shí)體。 在文本上應(yīng)用名稱實(shí)體識別來查找各種實(shí)體,如PERSON、ORG、GPE。 基于命名實(shí)體的情感分析。 以找到包含命名實(shí)體的句子為目標(biāo),只對這些句子逐一進(jìn)行情感分析。
結(jié)論:
參考文獻(xiàn):
往期精彩回顧
本站qq群851320808,加入微信群請掃碼:
評論
圖片
表情
