情感分析及數(shù)據(jù)集
隨著在線社交媒體和評論平臺的快速發(fā)展,大量評論的數(shù)據(jù)被記錄下來。這些數(shù)據(jù)具有支持決策過程的巨大潛力。?情感分析(sentiment analysis)研究人們在文本中 (如產(chǎn)品評論、博客評論和論壇討論等)“隱藏”的情緒。 它在廣泛應(yīng)用于政治(如公眾對政策的情緒分析)、 金融(如市場情緒分析)和營銷(如產(chǎn)品研究和品牌管理)等領(lǐng)域。
由于情感可以被分類為離散的極性或尺度(例如,積極的和消極的),我們可以將情感分析看作一項(xiàng)文本分類任務(wù),它將可變長度的文本序列轉(zhuǎn)換為固定長度的文本類別。在本章中,我們將使用斯坦福大學(xué)的大型電影評論數(shù)據(jù)集(large movie review dataset)進(jìn)行情感分析。它由一個(gè)訓(xùn)練集和一個(gè)測試集組成,其中包含從IMDb下載的25000個(gè)電影評論。在這兩個(gè)數(shù)據(jù)集中,“積極”和“消極”標(biāo)簽的數(shù)量相同,表示不同的情感極性。
import os
from mxnet import np, npx
from d2l import mxnet as d2l
npx.set_np()
讀取數(shù)據(jù)集
首先,下載并提取路徑../data/aclImdb
中的IMDb評論數(shù)據(jù)集。
#@save
d2l.DATA_HUB['aclImdb'] = (
'http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz',
'01ada507287d82875905620988597833ad4e0903')
data_dir = d2l.download_extract('aclImdb', 'aclImdb')
接下來,讀取訓(xùn)練和測試數(shù)據(jù)集。每個(gè)樣本都是一個(gè)評論及其標(biāo)簽:1表示“積極”,0表示“消極”。
#@save
def read_imdb(data_dir, is_train):
"""讀取IMDb評論數(shù)據(jù)集文本序列和標(biāo)簽"""
data, labels = [], []
for label in ('pos', 'neg'):
folder_name = os.path.join(data_dir, 'train' if is_train else 'test',
label)
for file in os.listdir(folder_name):
with open(os.path.join(folder_name, file), 'rb') as f:
review = f.read().decode('utf-8').replace('\n', '')
data.append(review)
labels.append(1 if label == 'pos' else 0)
return data, labels
train_data = read_imdb(data_dir, is_train=True)
print('訓(xùn)練集數(shù)目:', len(train_data[0]))
for x, y in zip(train_data[0][:3], train_data[1][:3]):
print('標(biāo)簽:', y, 'review:', x[0:60])
訓(xùn)練集數(shù)目: 25000 標(biāo)簽: 1 review: Zentropa has much in common with The Third Man, another noir 標(biāo)簽: 1 review: Zentropa is the most original movie I've seen in years. If y 標(biāo)簽: 1 review: Lars Von Trier is never backward in trying out new technique?
預(yù)處理數(shù)據(jù)集
將每個(gè)單詞作為一個(gè)詞元,過濾掉出現(xiàn)不到5次的單詞,我們從訓(xùn)練數(shù)據(jù)集中創(chuàng)建一個(gè)詞表。
train_tokens = d2l.tokenize(train_data[0], token='word')
vocab = d2l.Vocab(train_tokens, min_freq=5, reserved_tokens=['<pad>'])
在詞元化之后,讓我們繪制評論詞元長度的直方圖。
d2l.set_figsize()
d2l.plt.xlabel('# tokens per review')
d2l.plt.ylabel('count')
d2l.plt.hist([len(line) for line in train_tokens], bins=range(0, 1000, 50));
?
正如我們所料,評論的長度各不相同。為了每次處理一小批量這樣的評論,我們通過截?cái)嗪吞畛鋵⒚總€(gè)評論的長度設(shè)置為500。
num_steps = 500 # 序列長度
train_features = np.array([d2l.truncate_pad(
vocab[line], num_steps, vocab['<pad>']) for line in train_tokens])
print(train_features.shape)
(25000, 500) [07:12:31] ../src/storage/storage.cc:196: Using Pooled (Naive) StorageManager for CPU
創(chuàng)建數(shù)據(jù)迭代器
現(xiàn)在我們可以創(chuàng)建數(shù)據(jù)迭代器了。在每次迭代中,都會(huì)返回一小批量樣本。
train_iter = d2l.load_array((train_features, train_data[1]), 64)
for X, y in train_iter:
print('X:', X.shape, ', y:', y.shape)
break
print('小批量數(shù)目:', len(train_iter))
X: (64, 500) , y: (64,)
小批量數(shù)目: 391?文章來源:http://www.zghlxwxcb.cn/news/detail-809952.html
整合代碼
最后,我們將上述步驟封裝到load_data_imdb
函數(shù)中。它返回訓(xùn)練和測試數(shù)據(jù)迭代器以及IMDb評論數(shù)據(jù)集的詞表。文章來源地址http://www.zghlxwxcb.cn/news/detail-809952.html
#@save
def load_data_imdb(batch_size, num_steps=500):
"""返回?cái)?shù)據(jù)迭代器和IMDb評論數(shù)據(jù)集的詞表"""
data_dir = d2l.download_extract('aclImdb', 'aclImdb')
train_data = read_imdb(data_dir, True)
test_data = read_imdb(data_dir, False)
train_tokens = d2l.tokenize(train_data[0], token='word')
test_tokens = d2l.tokenize(test_data[0], token='word')
vocab = d2l.Vocab(train_tokens, min_freq=5)
train_features = np.array([d2l.truncate_pad(
vocab[line], num_steps, vocab['<pad>']) for line in train_tokens])
test_features = np.array([d2l.truncate_pad(
vocab[line], num_steps, vocab['<pad>']) for line in test_tokens])
train_iter = d2l.load_array((train_features, train_data[1]), batch_size)
test_iter = d2l.load_array((test_features, test_data[1]), batch_size,
is_train=False)
return train_iter, test_iter, vocab
到了這里,關(guān)于自然語言處理-情感分析及數(shù)據(jù)集的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!