RNN的介紹


一、狀態和模型

在CNN網絡中的訓練樣本的數據為IID數據(獨立同分布數據),所解決的問題也是分類問題或者回歸問題或者是特征表達問題。但更多的數據是不滿足IID的,如語言翻譯,自動文本生成。它們是一個序列問題,包括時間序列和空間序列。這時就要用到RNN網絡,RNN的結構圖如下所示:

 序列樣本一般分為:一對多(生成圖片描述),多對一(視頻解說,文本歸類),多對多(語言翻譯)。RNN不僅能夠處理序列輸入,也能夠得到序列輸出,這里的序列指的是向量的序列。RNN學習來的是一個程序,也可以說是一個狀態機,不是一個函數

二、序列預測

1.下面以序列預測為例,介紹RNN網絡。下面來描述這個問題。

(1)輸入的是時間變化向量序列 x t-2 , x t-1 , x t , x t+1 , x t+2

(2)在t時刻通過模型來估計

(3)問題:對內部狀態和長時間范圍的場景難以建模和觀察

(4)解決方案:引入內部隱含狀態變量

 

2.序列預測模型

它與CNN網絡的區別可以這樣理解,它不僅需要本次的x作為輸入,還要把前一次隱藏層作為輸入,綜合得出輸出y

輸入離散列序列:     

在時間t的更新計算;

 

預測計算:  

 對於上圖的各層參數說明如下:

            

    

在整個計算過程中,W保持不變,h0在0 時刻初始化。當h0不同時,網絡生成的東西也就不相同了,它就像一個種子。序列生成時,本次的輸出yt會作為下一次的輸入,這樣源源不斷的進行下去。

三、RNN的訓練

            

它做前向運算,相同的W要運算多次,多步之前的輸入x會影響當前的輸出,在后向運算過程中,同樣W也不被乘多次。計算loss時,要把每一步的損失都加起來。

1.BPTT算法

(1)RNN前向運算

(2)計算w的偏導,需要把所有time step加起來

(3)計算梯度需要用到如下鏈式規則

如上實在的dyt/dhk是沒有計算公式的,下面來看看怎么計算這個式子

梳理一下我們的問題和已知,

計算目標:

已知:

 

因此:

2.BPTT算法的梯度消失(vanishing)和梯度爆炸(exploding)現象分析

這里的消失和CNN等網絡的梯度消失的原因是不一樣的,CNN是因為隱藏層過多導致的梯度消失,而此處的消失是因為step過多造成的,如果隱層多更會加劇這種現象。

已知:

根據||XY||≤||X|| ||Y||知道:

其中beta代表上限,因此:

3.解決方案。

(1)clipping:不讓梯度那么大,通過公式將它控制在一定的范圍

(2)將tanh函數換為relu函數

但事實上直接用這種全連接形式的RNN是很少見的,很多人都在用LSTM

4.LSTM

它的h層對下一個step有兩個輸入,除了h t-1外,多了一個c

(1)forget / input unit

ft指的是對前一次的h要忘記多少,it為輸入單元,表示本次要對c更新多少。

(2) update cell

 

因為ft最后是一個sigmoid函數,最后輸出值大多為接近0或者1,也就是長短期記憶ct為-1到1的范圍,所以它不止是累加,還是可能讓其減小

(3)output

綜上所述,LSTM的結構與公式是

(4)LSTM的訓練

不需要記憶復雜的BPTT公式,利用時序展開,構造層次關系,可以開發復雜的BPTT算法,同時LSTM具有定抑制梯度vinishing/exploding的特性。

(5)使用LSTM

將多個LSTM組合成層,網絡中有多層,復雜的結構能夠處理更大范圍的動態性。

四、RNN的應用

1.learning to execute

 

序列數據的復雜性

(1)序列中相關距離可能很長

(2)需要有記憶功能

(3)代碼中又有分支

(4)多種任務

 

如何訓練

(1)樣本的順序:先易后難VS難易交替

(2)樣本的類型:循環代碼VS解析代碼

2.字符語言模型:字符序列輸入,預測下一個字符(https://github.com/karpathy/char-rnn)

文本生成:在通過大量的樣本訓練好預測模型之后,我們可以利用這個模型來生產我們需要的文本

下面給出實現的代碼;

"""
Minimal character-level Vanilla RNN model. Written by Andrej Karpathy (@karpathy)
BSD License
"""
import numpy as np
 
# data I/O
data = open('input.txt', 'r').read() # should be simple plain text file
chars = list(set(data))
data_size, vocab_size = len(data), len(chars)
print 'data has %d characters, %d unique.' % (data_size, vocab_size)
char_to_ix = { ch:i for i,ch in enumerate(chars) }
ix_to_char = { i:ch for i,ch in enumerate(chars) }
 
# hyperparameters
hidden_size = 100 # size of hidden layer of neurons
seq_length = 25 # number of steps to unroll the RNN for
learning_rate = 1e-1
 
# model parameters
Wxh = np.random.randn(hidden_size, vocab_size)*0.01 # input to hidden
Whh = np.random.randn(hidden_size, hidden_size)*0.01 # hidden to hidden
Why = np.random.randn(vocab_size, hidden_size)*0.01 # hidden to output
bh = np.zeros((hidden_size, 1)) # hidden bias
by = np.zeros((vocab_size, 1)) # output bias
 
def lossFun(inputs, targets, hprev):
  """
  inputs,targets are both list of integers.
  hprev is Hx1 array of initial hidden state
  returns the loss, gradients on model parameters, and last hidden state
  """
  xs, hs, ys, ps = {}, {}, {}, {}
  hs[-1] = np.copy(hprev)
  loss = 0
  # forward pass
  for t in xrange(len(inputs)):
    xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation
    xs[t][inputs[t]] = 1
    hs[t] = np.tanh(np.dot(Wxh, xs[t]) + np.dot(Whh, hs[t-1]) + bh) # hidden state
    ys[t] = np.dot(Why, hs[t]) + by # unnormalized log probabilities for next chars
    ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # probabilities for next chars
    loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss)
  # backward pass: compute gradients going backwards
  dWxh, dWhh, dWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
  dbh, dby = np.zeros_like(bh), np.zeros_like(by)
  dhnext = np.zeros_like(hs[0])
  for t in reversed(xrange(len(inputs))):
    dy = np.copy(ps[t])
    dy[targets[t]] -= 1 # backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here
    dWhy += np.dot(dy, hs[t].T)
    dby += dy
    dh = np.dot(Why.T, dy) + dhnext # backprop into h
    dhraw = (1 - hs[t] * hs[t]) * dh # backprop through tanh nonlinearity
    dbh += dhraw
    dWxh += np.dot(dhraw, xs[t].T)
    dWhh += np.dot(dhraw, hs[t-1].T)
    dhnext = np.dot(Whh.T, dhraw)
  for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
    np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients
  return loss, dWxh, dWhh, dWhy, dbh, dby, hs[len(inputs)-1]
 
def sample(h, seed_ix, n):
  """
  sample a sequence of integers from the model
  h is memory state, seed_ix is seed letter for first time step
  """
  x = np.zeros((vocab_size, 1))
  x[seed_ix] = 1
  ixes = []
  for t in xrange(n):
    h = np.tanh(np.dot(Wxh, x) + np.dot(Whh, h) + bh)
    y = np.dot(Why, h) + by
    p = np.exp(y) / np.sum(np.exp(y))
    ix = np.random.choice(range(vocab_size), p=p.ravel())
    x = np.zeros((vocab_size, 1))
    x[ix] = 1
    ixes.append(ix)
  return ixes
 
n, p = 0, 0
mWxh, mWhh, mWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
mbh, mby = np.zeros_like(bh), np.zeros_like(by) # memory variables for Adagrad
smooth_loss = -np.log(1.0/vocab_size)*seq_length # loss at iteration 0
while True:
  # prepare inputs (we're sweeping from left to right in steps seq_length long)
  if p+seq_length+1 >= len(data) or n == 0:
    hprev = np.zeros((hidden_size,1)) # reset RNN memory
    p = 0 # go from start of data
  inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]]
  targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]]
 
  # sample from the model now and then
  if n % 100 == 0:
    sample_ix = sample(hprev, inputs[0], 200)
    txt = ''.join(ix_to_char[ix] for ix in sample_ix)
    print '----\n %s \n----' % (txt, )
 
  # forward seq_length characters through the net and fetch gradient
  loss, dWxh, dWhh, dWhy, dbh, dby, hprev = lossFun(inputs, targets, hprev)
  smooth_loss = smooth_loss * 0.999 + loss * 0.001
  if n % 100 == 0: print 'iter %d, loss: %f' % (n, smooth_loss) # print progress
   
  # perform parameter update with Adagrad
  for param, dparam, mem in zip([Wxh, Whh, Why, bh, by],
                                [dWxh, dWhh, dWhy, dbh, dby],
                                [mWxh, mWhh, mWhy, mbh, mby]):
    mem += dparam * dparam
    param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update
 
  p += seq_length # move data pointer
n += 1 # iteration counter

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM