生活随笔
收集整理的這篇文章主要介紹了
二十、文本情感分类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 文本情感傾向性分析
1.1 情感分析的概念
- 簡單的說,我們可以將情感分析(sentiment classification)任務定義為一個分類問題,即指定一個文本輸入,機器通過對文本進行分析、處理、歸納和推理后自動輸出結論,如下圖所示:
1.2 情感分析的任務
- 通常情況下,人們把情感分析任務看成一個三分類問題。
- 正向: 表示正面積極的情感,如高興,幸福,驚喜,期待等。
- 負向: 表示負面消極的情感,如難過,傷心,憤怒,驚恐等。
- 其他: 其他類型的情感。
1.3 情感分析的作用
- 利用機器自動分析這些情感傾向,不但有助于幫助企業了解消費者對其產品的感受,為產品改進提供依據;同時還有助于企業分析商業伙伴們的態度,以便更好地進行商業決策
2. 情感分析的數據預處理
2.1 數據集介紹
- IMDB電影評論數據,地址:http://ai.stanford.edu/~amaas/data/sentiment/,這是一份包含了5萬條流行電影的評論數據,其中訓練集25000條,測試集25000條。
2.2 思路分析
- 根據上述的樣本,需要使用pytorch完成模型,實現對評論情感進行預測。首先可以把上述問題定義為分類問題,情感評分分為1-10,10個類別。那么根據之前的經驗,我們的大致流程如下:準備數據集、模型構建、模型訓練、模型評估。
2.3 代碼實現
def tokenize(text
):fileters
= ['!', '"', '#', '$', '%', '&', '\(', '\)', '\*', '\+', ',', '-', '\.', '/', ':', ';', '<', '=', '>','\?', '@', '\[', '\\', '\]', '^', '_', '`', '\{', '\|', '\}', '~', '\t', '\n', '\x97', '\x96', '”', '“', ]text
= re
.sub
("<.*?>", " ", text
, flags
=re
.S
)text
= re
.sub
("|".join
(fileters
), " ", text
, flags
=re
.S
)return [i
.strip
() for i
in text
.split
()]
class ImdbDataset(Dataset
):def __init__(self
, mode
):super(ImdbDataset
, self
).__init__
()if mode
== "train":text_path
= [os
.path
.join
(data_base_path
, i
) for i
in ["train/neg", "train/pos"]]else:text_path
= [os
.path
.join
(data_base_path
, i
) for i
in ["test/neg", "test/pos"]]self
.total_file_path_list
= []for i
in text_path
:self
.total_file_path_list
.extend
([os
.path
.join
(i
, j
) for j
in os
.listdir
(i
)])def __getitem__(self
, idx
):cur_path
= self
.total_file_path_list
[idx
]cur_filename
= os
.path
.basename
(cur_path
)label
= int(cur_filename
.split
("_")[-1].split
(".")[0]) - 1 text
= tokenize
(open(cur_path
).read
().strip
()) return label
, text
def __len__(self
):return len(self
.total_file_path_list
)
dataset
= ImdbDataset
(mode
="train")def collate_fn(batch
):content
,label
= list(zip(*batch
))return content
,labeldataloader
= DataLoader
(dataset
=dataset
, batch_size
=10, shuffle
=True,collate_fn
=collate_fn
)
count
= 0
for idx
, (label
, text
) in enumerate(dataloader
):print("idx:", idx
)print("table:", label
)print("text:", text
)count
+= 1if count
== 1:break
總結
以上是生活随笔為你收集整理的二十、文本情感分类的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。