深度學習--RNN基礎

林每天都要努力發表於2023-04-25

深度學習--RNN基礎

​ RNN(Recurrent Neutral Network,迴圈神經網路),主要應用於自然語言處理NLP。

RNN表示方法

1.編碼

因為Pytorch中沒有String型別資料,需要引入序列表示法(sequence representation)對文字進行表示。

​ 表示方法:[seq_len:一句話的單詞數,feature_len:每個單詞的表示方法]

文字資訊的表達方式:

  1. one-hot:多少個單詞就有多少位編碼。缺點:非常稀疏(sparse),維度太高,缺乏語意相關性(semantic similarity)
  2. word2vec
import torch
import torch.nn as nn

word_to_ix = {"hello":0,"world":1}

embeds = nn.Embedding(2,5)  #2行5列  一共有2個單詞,用5位的feature來表示
lookup_tensor = torch.tensor([word_to_ix["hello"]],dtype=torch.long)
hello_embed = embeds(lookup_tensor)
print(hello_embed)
#tensor([[-0.2169,  0.3653,  0.7812, -0.8420, -0.2815]],
#       grad_fn=<EmbeddingBackward0>)


word_to_ix = {"hello":0,"world":1}

embeds = nn.Embedding(2,5)  #2行5列  一共有2個單詞,用5位的feature來表示
lookup_tensor = torch.tensor([word_to_ix["hello"]],dtype=torch.long)
hello_embed = embeds(lookup_tensor)
print(hello_embed)
#tensor([[-0.2169,  0.3653,  0.7812, -0.8420, -0.2815]],
#       grad_fn=<EmbeddingBackward0>)
  1. glove
from torchnlp.word_to_vector import GloVe
vectors = GloVe()
vector["hello"]

2. batch

兩種引入方式:[word num, b, word vec] 或者 [b, word num, word vec ] 第一種常用

RNN原理

naive version

對每一個單詞進行 x@w1+b1 操作,每個單詞都有不同的引數

Weight sharing

共享引數,用同一個w和b

Consistent memory 持續記憶

每一個單詞運算表示:x @ wxh +h @ whh

增加了一個h單元,相當於一個memory單元。

總結:

RNN的網路為yt = why*ht

ht=啟用函式(Whh* ht-1+Wxh *xt) 常用的為tanh

模型的反向傳播:BPTT(back propagation through time)

RNN層的使用方法

run = nn.RNN(100,10)  #word vec 單詞的表示位數, memory 記憶節點

run._parameters.keys()
#odict_keys(['weight_ih_l0', 'weight_hh_l0', 'bias_ih_l0', 'bias_hh_l0'])

run.weight_hh_l0.shape, run.weight_ih_l0.shape
#(torch.Size([10, 10]), torch.Size([10, 100]))

run.bias_hh_l0.shape, run.bias_ih_l0.shape
#(torch.Size([10]), torch.Size([10]))

1.nn.RNN

nn.RNN(input_size:單詞的表示方法維度,hidden_size:記憶的維度:,num_layers:預設是1)

前向傳播,一步到位 out, ht = forward(x, h0)

​ x:[一句話單詞數,batch幾句話,表示的維度]

​ h0/ht:[層數,batch,記憶(引數)的維度]

​ out:[一句話單詞數,batch,引數的維度]

import torch
import torch.nn as nn

run = nn.RNN(input_size=100, hidden_size=20, num_layers=1)
print(run)
#RNN(100, 20)

x = torch.randn(10,3,100)
h = torch.zeros(1,3,20)
out,h1 = run(x,h)
print(out.shape,h1.shape)
#torch.Size([10, 3, 20]) torch.Size([1, 3, 20])

2. nn.RNNCell:只完成一個計算

nn.RNNCell(input_size:單詞的表示方法維度,hidden_size:記憶的維度:,num_layers:預設是1)

前向傳播:ht=rnncell(xt,ht_1)

​ xt:[batch,word維度]

​ ht_1/ht:[層數,batch,引數的維度]

#RNNCell
x = torch.randn(10,3,100)
cell = nn.RNNCell(100,20)
h1 = torch.zeros(3,20)
#人為控制一句話的單詞數
for xt in x:
    print(xt)
    h1 = cell(xt,h1)
print(h1.shape)
#torch.Size([3, 20])

相關文章