99精品伊人亚洲|最近国产中文炮友|九草在线视频支援|AV网站大全最新|美女黄片免费观看|国产精品资源视频|精彩无码视频一区|91大神在线后入|伊人终合在线播放|久草综合久久中文

電子發(fā)燒友App

硬聲App

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

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

3天內(nèi)不再提示
創(chuàng)作
電子發(fā)燒友網(wǎng)>電子資料下載>電子資料>PyTorch教程16.2之情感分析:使用遞歸神經(jīng)網(wǎng)絡

PyTorch教程16.2之情感分析:使用遞歸神經(jīng)網(wǎng)絡

2023-06-05 | pdf | 0.20 MB | 次下載 | 免費

資料介紹

與詞相似度和類比任務一樣,我們也可以將預訓練詞向量應用于情感分析。由于第 16.1 節(jié)中的 IMDb 評論數(shù)據(jù)集 不是很大,使用在大規(guī)模語料庫上預訓練的文本表示可能會減少模型的過度擬合。作為圖 16.2.1所示的具體示例 ,我們將使用預訓練的 GloVe 模型表示每個標記,并將這些標記表示輸入多層雙向 RNN 以獲得文本序列表示,并將其轉(zhuǎn)換為情感分析輸出 Maas,2011。對于相同的下游應用程序,我們稍后會考慮不同的架構(gòu)選擇。

https://file.elecfans.com/web2/M00/A9/CD/poYBAGR9PJyAB1TZAAKGTdnYvUk151.svg

圖 16.2.1本節(jié)將預訓練的 GloVe 提供給基于 RNN 的架構(gòu)進行情緒分析。

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

batch_size = 64
train_iter, test_iter, vocab = d2l.load_data_imdb(batch_size)
from mxnet import gluon, init, np, npx
from mxnet.gluon import nn, rnn
from d2l import mxnet as d2l

npx.set_np()

batch_size = 64
train_iter, test_iter, vocab = d2l.load_data_imdb(batch_size)

16.2.1。用 RNN 表示單個文本

在文本分類任務中,例如情感分析,變長的文本序列將被轉(zhuǎn)換為固定長度的類別。在下面的BiRNN類中,雖然文本序列的每個標記都通過嵌入層 ( self.embedding) 獲得其單獨的預訓練 GloVe 表示,但整個序列由雙向 RNN ( self.encoder) 編碼。更具體地說,雙向 LSTM 在初始和最終時間步的隱藏狀態(tài)(在最后一層)被連接起來作為文本序列的表示。然后通過具有兩個輸出(“正”和“負”)的全連接層 ( self.decoder) 將該單一文本表示轉(zhuǎn)換為輸出類別。

class BiRNN(nn.Module):
  def __init__(self, vocab_size, embed_size, num_hiddens,
         num_layers, **kwargs):
    super(BiRNN, self).__init__(**kwargs)
    self.embedding = nn.Embedding(vocab_size, embed_size)
    # Set `bidirectional` to True to get a bidirectional RNN
    self.encoder = nn.LSTM(embed_size, num_hiddens, num_layers=num_layers,
                bidirectional=True)
    self.decoder = nn.Linear(4 * num_hiddens, 2)

  def forward(self, inputs):
    # The shape of `inputs` is (batch size, no. of time steps). Because
    # LSTM requires its input's first dimension to be the temporal
    # dimension, the input is transposed before obtaining token
    # representations. The output shape is (no. of time steps, batch size,
    # word vector dimension)
    embeddings = self.embedding(inputs.T)
    self.encoder.flatten_parameters()
    # Returns hidden states of the last hidden layer at different time
    # steps. The shape of `outputs` is (no. of time steps, batch size,
    # 2 * no. of hidden units)
    outputs, _ = self.encoder(embeddings)
    # Concatenate the hidden states at the initial and final time steps as
    # the input of the fully connected layer. Its shape is (batch size,
    # 4 * no. of hidden units)
    encoding = torch.cat((outputs[0], outputs[-1]), dim=1)
    outs = self.decoder(encoding)
    return outs
class BiRNN(nn.Block):
  def __init__(self, vocab_size, embed_size, num_hiddens,
         num_layers, **kwargs):
    super(BiRNN, self).__init__(**kwargs)
    self.embedding = nn.Embedding(vocab_size, embed_size)
    # Set `bidirectional` to True to get a bidirectional RNN
    self.encoder = rnn.LSTM(num_hiddens, num_layers=num_layers,
                bidirectional=True, input_size=embed_size)
    self.decoder = nn.Dense(2)

  def forward(self, inputs):
    # The shape of `inputs` is (batch size, no. of time steps). Because
    # LSTM requires its input's first dimension to be the temporal
    # dimension, the input is transposed before obtaining token
    # representations. The output shape is (no. of time steps, batch size,
    # word vector dimension)
    embeddings = self.embedding(inputs.T)
    # Returns hidden states of the last hidden layer at different time
    # steps. The shape of `outputs` is (no. of time steps, batch size,
    # 2 * no. of hidden units)
    outputs = self.encoder(embeddings)
    # Concatenate the hidden states at the initial and final time steps as
    # the input of the fully connected layer. Its shape is (batch size,
    # 4 * no. of hidden units)
    encoding = np.concatenate((outputs[0], outputs[-1]), axis=1)
    outs = self.decoder(encoding)
    return outs

讓我們構(gòu)建一個具有兩個隱藏層的雙向 RNN 來表示用于情感分析的單個文本。

embed_size, num_hiddens, num_layers, devices = 100, 100, 2, d2l.try_all_gpus()
net = BiRNN(len(vocab), embed_size, num_hiddens, num_layers)

def init_weights(module):
  if type(module) == nn.Linear:
    nn.init.xavier_uniform_(module.weight)
  if type(module) == nn.LSTM:
    for param in module._flat_weights_names:
      if "weight" in param:
        nn.init.xavier_uniform_(module._parameters[param])
net.apply(init_weights);
embed_size, num_hiddens, num_layers, devices = 100, 100, 2, d2l.try_all_gpus()
net = BiRNN(len(vocab), embed_size, num_hiddens, num_layers)

net.initialize(init.Xavier(), ctx=devices)

16.2.2。加載預訓練詞向量

embed_size下面我們?yōu)樵~匯表中的標記加載預訓練的 100 維(需要與 一致)GloVe 嵌入。

glove_embedding = d2l.TokenEmbedding('glove.6b.100d')
Downloading ../data/glove.6B.100d.zip from http://d2l-data.s3-accelerate.amazonaws.com/glove.6B.100d.zip...
glove_embedding = d2l.TokenEmbedding('glove.6b.100d')

打印詞匯表中所有標記的向量形狀。

embeds = glove_embedding[vocab.idx_to_token]
embeds.shape
torch.Size([49346, 100])
embeds = glove_embedding[vocab.idx_to_token]
embeds.shape
(49346, 100)

我們使用這些預訓練的詞向量來表示評論中的標記,并且不會在訓練期間更新這些向量。

net.embedding.weight.data.copy_(embeds)
net.embedding.weight.requires_grad = False
net.embedding.weight.set_data(embeds)
net.embedding.collect_params().setattr('grad_req', 'null')

16.2.3。訓練和評估模型

現(xiàn)在我們可以訓練雙向 RNN 進行情感分析。

lr, num_epochs = 0.01, 5
trainer = torch.optim.Adam(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss(reduction="none")
d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)
loss 0.311, train acc 0.872, test acc 0.850
574.5 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]
https://file.elecfans.com/web2/M00/A9/CD/poYBAGR9PJ6AJIk8AAECA4Wy71Y322.svg
lr, num_epochs = 0.01, 5
trainer = gluon.Trainer(net.collect_params(), 'adam', {'learning_rate': lr})
loss = gluon.loss.SoftmaxCrossEntropyLoss()
d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)
loss 0.428, train acc 0.806, test acc 0.791
488.5 examples/sec on [gpu(0), gpu(1)]
https://file.elecfans.com/web2/M00/AA/48/pYYBAGR9PKGAE9v0AAEB8Qpd38M668.svg

我們定義了以下函數(shù)來使用經(jīng)過訓練的模型預測文本序列的情緒net。


下載該資料的人也在下載 下載該資料的人還在閱讀
更多 >

評論

查看更多

下載排行

本周

  1. 1DD3118電路圖紙資料
  2. 0.08 MB   |  1次下載  |  免費
  3. 2AD庫封裝庫安裝教程
  4. 0.49 MB   |  1次下載  |  免費
  5. 3PC6206 300mA低功耗低壓差線性穩(wěn)壓器中文資料
  6. 1.12 MB   |  1次下載  |  免費
  7. 4網(wǎng)絡安全從業(yè)者入門指南
  8. 2.91 MB   |  1次下載  |  免費
  9. 5DS-CS3A P00-CN-V3
  10. 618.05 KB  |  1次下載  |  免費
  11. 6海川SM5701規(guī)格書
  12. 1.48 MB  |  次下載  |  免費
  13. 7H20PR5電磁爐IGBT功率管規(guī)格書
  14. 1.68 MB   |  次下載  |  1 積分
  15. 8IP防護等級說明
  16. 0.08 MB   |  次下載  |  免費

本月

  1. 1貼片三極管上的印字與真實名稱的對照表詳細說明
  2. 0.50 MB   |  103次下載  |  1 積分
  3. 2涂鴉各WiFi模塊原理圖加PCB封裝
  4. 11.75 MB   |  89次下載  |  1 積分
  5. 3錦銳科技CA51F2 SDK開發(fā)包
  6. 24.06 MB   |  43次下載  |  1 積分
  7. 4錦銳CA51F005 SDK開發(fā)包
  8. 19.47 MB   |  19次下載  |  1 積分
  9. 5PCB的EMC設計指南
  10. 2.47 MB   |  16次下載  |  1 積分
  11. 6HC05藍牙原理圖加PCB
  12. 15.76 MB   |  13次下載  |  1 積分
  13. 7802.11_Wireless_Networks
  14. 4.17 MB   |  12次下載  |  免費
  15. 8蘋果iphone 11電路原理圖
  16. 4.98 MB   |  6次下載  |  2 積分

總榜

  1. 1matlab軟件下載入口
  2. 未知  |  935127次下載  |  10 積分
  3. 2開源硬件-PMP21529.1-4 開關(guān)降壓/升壓雙向直流/直流轉(zhuǎn)換器 PCB layout 設計
  4. 1.48MB  |  420064次下載  |  10 積分
  5. 3Altium DXP2002下載入口
  6. 未知  |  233089次下載  |  10 積分
  7. 4電路仿真軟件multisim 10.0免費下載
  8. 340992  |  191390次下載  |  10 積分
  9. 5十天學會AVR單片機與C語言視頻教程 下載
  10. 158M  |  183342次下載  |  10 積分
  11. 6labview8.5下載
  12. 未知  |  81588次下載  |  10 積分
  13. 7Keil工具MDK-Arm免費下載
  14. 0.02 MB  |  73815次下載  |  10 積分
  15. 8LabVIEW 8.6下載
  16. 未知  |  65989次下載  |  10 積分