0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

PyTorch教程-16.1. 情緒分析和數(shù)據(jù)集

jf_pJlTbmA9 ? 來源:PyTorch ? 作者:PyTorch ? 2023-06-05 15:44 ? 次閱讀

隨著在線社交媒體和評論平臺的激增,大量的意見數(shù)據(jù)被記錄下來,具有支持決策過程的巨大潛力。情感分析研究人們在其生成的文本中的情感,例如產(chǎn)品評論、博客評論和論壇討論。它在政治(例如,公眾對政策的情緒分析)、金融(例如,市場情緒分析)和市場營銷(例如,產(chǎn)品研究和品牌管理)等領(lǐng)域有著廣泛的應(yīng)用。

由于情緒可以被分類為離散的極性或尺度(例如,積極和消極),我們可以將情緒分析視為文本分類任務(wù),它將可變長度的文本序列轉(zhuǎn)換為固定長度的文本類別。在本章中,我們將使用斯坦福的大型電影評論數(shù)據(jù)集進(jìn)行情感分析。它由一個訓(xùn)練集和一個測試集組成,其中包含從 IMDb 下載的 25000 條電影評論。在這兩個數(shù)據(jù)集中,“正面”和“負(fù)面”標(biāo)簽的數(shù)量相等,表明不同的情緒極性。

import os
import torch
from torch import nn
from d2l import torch as d2l

import os
from mxnet import np, npx
from d2l import mxnet as d2l

npx.set_np()

16.1.1。讀取數(shù)據(jù)集

首先,在路徑中下載并解壓這個 IMDb 評論數(shù)據(jù)集 ../data/aclImdb。

#@save
d2l.DATA_HUB['aclImdb'] = (d2l.DATA_URL + 'aclImdb_v1.tar.gz',
             '01ada507287d82875905620988597833ad4e0903')

data_dir = d2l.download_extract('aclImdb', 'aclImdb')

Downloading ../data/aclImdb_v1.tar.gz from http://d2l-data.s3-accelerate.amazonaws.com/aclImdb_v1.tar.gz...

#@save
d2l.DATA_HUB['aclImdb'] = (d2l.DATA_URL + 'aclImdb_v1.tar.gz',
             '01ada507287d82875905620988597833ad4e0903')

data_dir = d2l.download_extract('aclImdb', 'aclImdb')

Downloading ../data/aclImdb_v1.tar.gz from http://d2l-data.s3-accelerate.amazonaws.com/aclImdb_v1.tar.gz...

接下來,閱讀訓(xùn)練和測試數(shù)據(jù)集。每個示例都是評論及其標(biāo)簽:1 表示“正面”,0 表示“負(fù)面”。

#@save
def read_imdb(data_dir, is_train):
  """Read the IMDb review dataset text sequences and labels."""
  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('# trainings:', len(train_data[0]))
for x, y in zip(train_data[0][:3], train_data[1][:3]):
  print('label:', y, 'review:', x[:60])

# trainings: 25000
label: 1 review: Henry Hathaway was daring, as well as enthusiastic, for his
label: 1 review: An unassuming, subtle and lean film, "The Man in the White S
label: 1 review: Eddie Murphy really made me laugh my ass off on this HBO sta

#@save
def read_imdb(data_dir, is_train):
  """Read the IMDb review dataset text sequences and labels."""
  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('# trainings:', len(train_data[0]))
for x, y in zip(train_data[0][:3], train_data[1][:3]):
  print('label:', y, 'review:', x[:60])

# trainings: 25000
label: 1 review: Henry Hathaway was daring, as well as enthusiastic, for his
label: 1 review: An unassuming, subtle and lean film, "The Man in the White S
label: 1 review: Eddie Murphy really made me laugh my ass off on this HBO sta

16.1.2。預(yù)處理數(shù)據(jù)集

將每個單詞視為一個標(biāo)記并過濾掉出現(xiàn)次數(shù)少于 5 次的單詞,我們從訓(xùn)練數(shù)據(jù)集中創(chuàng)建了一個詞匯表。

train_tokens = d2l.tokenize(train_data[0], token='word')
vocab = d2l.Vocab(train_tokens, min_freq=5, reserved_tokens=[''])

train_tokens = d2l.tokenize(train_data[0], token='word')
vocab = d2l.Vocab(train_tokens, min_freq=5, reserved_tokens=[''])

標(biāo)記化后,讓我們繪制以標(biāo)記為單位的評論長度直方圖。

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));

pYYBAGR9PJGAVpMAAADxspcG71s604.svg

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));

pYYBAGR9PJGAVpMAAADxspcG71s604.svg

正如我們所料,評論的長度各不相同。為了每次處理一小批此類評論,我們將每個評論的長度設(shè)置為 500,并進(jìn)行截斷和填充,這類似于第 10.5 節(jié)中機器翻譯數(shù)據(jù)集的預(yù)處理 步驟。

num_steps = 500 # sequence length
train_features = torch.tensor([d2l.truncate_pad(
  vocab[line], num_steps, vocab['']) for line in train_tokens])
print(train_features.shape)

torch.Size([25000, 500])

num_steps = 500 # sequence length
train_features = np.array([d2l.truncate_pad(
  vocab[line], num_steps, vocab['']) for line in train_tokens])
print(train_features.shape)

(25000, 500)

16.1.3。創(chuàng)建數(shù)據(jù)迭代器

現(xiàn)在我們可以創(chuàng)建數(shù)據(jù)迭代器。在每次迭代中,返回一小批示例。

train_iter = d2l.load_array((train_features, torch.tensor(train_data[1])), 64)

for X, y in train_iter:
  print('X:', X.shape, ', y:', y.shape)
  break
print('# batches:', len(train_iter))

X: torch.Size([64, 500]) , y: torch.Size([64])
# batches: 391

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('# batches:', len(train_iter))

X: (64, 500) , y: (64,)
# batches: 391

16.1.4。把它們放在一起

最后,我們將上述步驟包裝到函數(shù)中l(wèi)oad_data_imdb。它返回訓(xùn)練和測試數(shù)據(jù)迭代器以及 IMDb 評論數(shù)據(jù)集的詞匯表。

#@save
def load_data_imdb(batch_size, num_steps=500):
  """Return data iterators and the vocabulary of the IMDb review dataset."""
  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 = torch.tensor([d2l.truncate_pad(
    vocab[line], num_steps, vocab['']) for line in train_tokens])
  test_features = torch.tensor([d2l.truncate_pad(
    vocab[line], num_steps, vocab['']) for line in test_tokens])
  train_iter = d2l.load_array((train_features, torch.tensor(train_data[1])),
                batch_size)
  test_iter = d2l.load_array((test_features, torch.tensor(test_data[1])),
                batch_size,
                is_train=False)
  return train_iter, test_iter, vocab

#@save
def load_data_imdb(batch_size, num_steps=500):
  """Return data iterators and the vocabulary of the IMDb review dataset."""
  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['']) for line in train_tokens])
  test_features = np.array([d2l.truncate_pad(
    vocab[line], num_steps, vocab['']) 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

16.1.5。概括

情感分析研究人們在其生成的文本中的情感,這被認(rèn)為是將變長文本序列轉(zhuǎn)換為固定長度文本類別的文本分類問題。

預(yù)處理后,我們可以將斯坦福的大型電影評論數(shù)據(jù)集(IMDb 評論數(shù)據(jù)集)加載到帶有詞匯表的數(shù)據(jù)迭代器中。

16.1.6。練習(xí)

我們可以修改本節(jié)中的哪些超參數(shù)來加速訓(xùn)練情緒分析模型?

你能實現(xiàn)一個函數(shù)來將亞馬遜評論的數(shù)據(jù)集加載到數(shù)據(jù)迭代器和標(biāo)簽中以進(jìn)行情感分析嗎?

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • 數(shù)據(jù)集
    +關(guān)注

    關(guān)注

    4

    文章

    1197

    瀏覽量

    24537
  • pytorch
    +關(guān)注

    關(guān)注

    2

    文章

    794

    瀏覽量

    13009
收藏 人收藏

    評論

    相關(guān)推薦

    高階API構(gòu)建模型和數(shù)據(jù)使用

    了TensorFlow2.0Beta版本,同pytorch一樣支持動態(tài)執(zhí)行(TensorFlow2.0默認(rèn)eager模式,無需啟動會話執(zhí)行計算圖),同時刪除了雜亂低階API,使用高階API簡單地構(gòu)建復(fù)雜神經(jīng)網(wǎng)絡(luò)模型,本文主要分享用高階API構(gòu)建模型和數(shù)據(jù)
    發(fā)表于 11-04 07:49

    在機智云上創(chuàng)建項目和數(shù)據(jù)

    一、基于STM32+ESP8266+機智云的物聯(lián)網(wǎng)demo1、在機智云上創(chuàng)建項目和數(shù)據(jù)2、WIFI模塊燒寫固件3、移植到MCU上①、在STM32上移植②、在IMX6ULL上移植1、在機智云上創(chuàng)建
    發(fā)表于 08-03 07:45

    Rough和數(shù)據(jù)挖掘應(yīng)用于案件綜合分析

    在檢察機關(guān)中,對大量同類案件進(jìn)行綜合分析并挖掘出有益知識,這對有效預(yù)防同類案件的發(fā)生具有重要的現(xiàn)實意義。簡要介紹了Rough 理論和數(shù)據(jù)挖掘的基本概念和相關(guān)技術(shù);
    發(fā)表于 01-15 14:26 ?8次下載

    基于PLSA模型的群體情緒演進(jìn)分析

    針對群體情緒演進(jìn)分析中話題內(nèi)容挖掘及其對應(yīng)群體情緒分析兩個層面的難題,提出了一種基于概率潛在語義分析(PLSA)模型的群體
    發(fā)表于 12-30 17:16 ?0次下載
    基于PLSA模型的群體<b class='flag-5'>情緒</b>演進(jìn)<b class='flag-5'>分析</b>

    利用Python和PyTorch處理面向?qū)ο蟮?b class='flag-5'>數(shù)據(jù)

    本篇是利用 Python 和 PyTorch 處理面向?qū)ο蟮?b class='flag-5'>數(shù)據(jù)系列博客的第 2 篇。 如需閱讀第 1 篇:原始數(shù)據(jù)和數(shù)據(jù)
    的頭像 發(fā)表于 08-25 15:30 ?2892次閱讀

    利用 Python 和 PyTorch 處理面向?qū)ο蟮?b class='flag-5'>數(shù)據(jù)(2)) :創(chuàng)建數(shù)據(jù)對象

    本篇是利用 Python 和 PyTorch 處理面向?qū)ο蟮?b class='flag-5'>數(shù)據(jù)系列博客的第 2 篇。我們在第 1 部分中已定義 MyDataset 類,現(xiàn)在,讓我們來例化 MyDataset 對象,此可迭代對象是與原始
    的頭像 發(fā)表于 08-02 17:35 ?831次閱讀
    利用 Python 和 <b class='flag-5'>PyTorch</b> 處理面向?qū)ο蟮?b class='flag-5'>數(shù)據(jù)</b><b class='flag-5'>集</b>(2)) :創(chuàng)建<b class='flag-5'>數(shù)據(jù)</b><b class='flag-5'>集</b>對象

    PyTorch教程4.2之圖像分類數(shù)據(jù)

    電子發(fā)燒友網(wǎng)站提供《PyTorch教程4.2之圖像分類數(shù)據(jù).pdf》資料免費下載
    發(fā)表于 06-05 15:41 ?0次下載
    <b class='flag-5'>PyTorch</b>教程4.2之圖像分類<b class='flag-5'>數(shù)據(jù)</b><b class='flag-5'>集</b>

    PyTorch教程10.5之機器翻譯和數(shù)據(jù)

    電子發(fā)燒友網(wǎng)站提供《PyTorch教程10.5之機器翻譯和數(shù)據(jù).pdf》資料免費下載
    發(fā)表于 06-05 15:14 ?0次下載
    <b class='flag-5'>PyTorch</b>教程10.5之機器翻譯<b class='flag-5'>和數(shù)據(jù)</b><b class='flag-5'>集</b>

    PyTorch教程14.6之對象檢測數(shù)據(jù)

    電子發(fā)燒友網(wǎng)站提供《PyTorch教程14.6之對象檢測數(shù)據(jù).pdf》資料免費下載
    發(fā)表于 06-05 11:23 ?0次下載
    <b class='flag-5'>PyTorch</b>教程14.6之對象檢測<b class='flag-5'>數(shù)據(jù)</b><b class='flag-5'>集</b>

    PyTorch教程14.9之語義分割和數(shù)據(jù)

    電子發(fā)燒友網(wǎng)站提供《PyTorch教程14.9之語義分割和數(shù)據(jù).pdf》資料免費下載
    發(fā)表于 06-05 11:10 ?0次下載
    <b class='flag-5'>PyTorch</b>教程14.9之語義分割<b class='flag-5'>和數(shù)據(jù)</b><b class='flag-5'>集</b>

    PyTorch教程15.9之預(yù)訓(xùn)練BERT的數(shù)據(jù)

    電子發(fā)燒友網(wǎng)站提供《PyTorch教程15.9之預(yù)訓(xùn)練BERT的數(shù)據(jù).pdf》資料免費下載
    發(fā)表于 06-05 11:06 ?0次下載
    <b class='flag-5'>PyTorch</b>教程15.9之預(yù)訓(xùn)練BERT的<b class='flag-5'>數(shù)據(jù)</b><b class='flag-5'>集</b>

    PyTorch教程16.1情緒分析和數(shù)據(jù)

    電子發(fā)燒友網(wǎng)站提供《PyTorch教程16.1情緒分析和數(shù)據(jù).pdf》資料免費下載
    發(fā)表于 06-05 10:54 ?0次下載
    <b class='flag-5'>PyTorch</b>教程<b class='flag-5'>16.1</b>之<b class='flag-5'>情緒</b><b class='flag-5'>分析</b><b class='flag-5'>和數(shù)據(jù)</b><b class='flag-5'>集</b>

    PyTorch教程16.4之自然語言推理和數(shù)據(jù)

    電子發(fā)燒友網(wǎng)站提供《PyTorch教程16.4之自然語言推理和數(shù)據(jù).pdf》資料免費下載
    發(fā)表于 06-05 10:57 ?0次下載
    <b class='flag-5'>PyTorch</b>教程16.4之自然語言推理<b class='flag-5'>和數(shù)據(jù)</b><b class='flag-5'>集</b>

    PyTorch教程-16.4。自然語言推理和數(shù)據(jù)

    16.4。自然語言推理和數(shù)據(jù)? Colab [火炬]在 Colab 中打開筆記本 Colab [mxnet] Open the notebook in Colab Colab [jax
    的頭像 發(fā)表于 06-05 15:44 ?443次閱讀

    PyTorch如何訓(xùn)練自己的數(shù)據(jù)

    PyTorch是一個廣泛使用的深度學(xué)習(xí)框架,它以其靈活性、易用性和強大的動態(tài)圖特性而聞名。在訓(xùn)練深度學(xué)習(xí)模型時,數(shù)據(jù)是不可或缺的組成部分。然而,很多時候,我們可能需要使用自己的數(shù)據(jù)
    的頭像 發(fā)表于 07-02 14:09 ?527次閱讀