rnn

import numpy as np

"""

This file defines layer types that are commonly used for recurrent neural

networks.

"""

def rnn_step_forward(x, prev_h, Wx, Wh, b):

"""

Run the forward pass for a single timestep of a vanilla RNN that uses a tanh

activation function.

The input data has dimension D, the hidden state has dimension H, and we use

a minibatch size of N.

Inputs:

- x: Input data for this timestep, of shape (N, D).

- prev_h: Hidden state from previous timestep, of shape (N, H)

- Wx: Weight matrix for input-to-hidden connections, of shape (D, H)

- Wh: Weight matrix for hidden-to-hidden connections, of shape (H, H)

- b: Biases of shape (H,)

Returns a tuple of:

- next_h: Next hidden state, of shape (N, H)

- cache: Tuple of values needed for the backward pass.

"""

next_h, cache = None, None

##############################################################################

# TODO: Implement a single forward step for the vanilla RNN. Store the next  #

# hidden state and any values you need for the backward pass in the next_h  #

# and cache variables respectively.                                          #

##############################################################################

a = prev_h.dot(Wh) + x.dot(Wx) + b

next_h = np.tanh(a)

cache = (x, prev_h, Wh, Wx, b, next_h)

#pass

##############################################################################

#                              END OF YOUR CODE                            #

##############################################################################

return next_h, cache

def rnn_step_backward(dnext_h, cache):

"""

Backward pass for a single timestep of a vanilla RNN.

Inputs:

- dnext_h: Gradient of loss with respect to next hidden state

- cache: Cache object from the forward pass

Returns a tuple of:

- dx: Gradients of input data, of shape (N, D)

- dprev_h: Gradients of previous hidden state, of shape (N, H)

- dWx: Gradients of input-to-hidden weights, of shape (N, H)

- dWh: Gradients of hidden-to-hidden weights, of shape (H, H)

- db: Gradients of bias vector, of shape (H,)

"""

dx, dprev_h, dWx, dWh, db = None, None, None, None, None

##############################################################################

# TODO: Implement the backward pass for a single step of a vanilla RNN.      #

#                                                                            #

# HINT: For the tanh function, you can compute the local derivative in terms #

# of the output value from tanh.                                            #

##############################################################################

x, prev_h, Wh, Wx, b, next_h =  cache

da = dnext_h * (1 - next_h * next_h)

dx = da.dot(Wx.T)

dprev_h = da.dot(Wh.T)

dWx = x.T.dot(da)

dWh = prev_h.T.dot(da)

db = np.sum(da, axis = 0)

#pass

##############################################################################

#                              END OF YOUR CODE                            #

##############################################################################

return dx, dprev_h, dWx, dWh, db

def rnn_forward(x, h0, Wx, Wh, b):

"""

Run a vanilla RNN forward on an entire sequence of data. We assume an input

sequence composed of T vectors, each of dimension D. The RNN uses a hidden

size of H, and we work over a minibatch containing N sequences. After running

the RNN forward, we return the hidden states for all timesteps.

Inputs:

- x: Input data for the entire timeseries, of shape (N, T, D).

- h0: Initial hidden state, of shape (N, H)

- Wx: Weight matrix for input-to-hidden connections, of shape (D, H)

- Wh: Weight matrix for hidden-to-hidden connections, of shape (H, H)

- b: Biases of shape (H,)

Returns a tuple of:

- h: Hidden states for the entire timeseries, of shape (N, T, H).

- cache: Values needed in the backward pass

"""

h, cache = None, None

##############################################################################

# TODO: Implement forward pass for a vanilla RNN running on a sequence of    #

# input data. You should use the rnn_step_forward function that you defined  #

# above.                                                                    #

##############################################################################

N, T, D = x.shape

(H ,) = b.shape

h = np.zeros((N, T, H))

prev_h = h0

for t in range(T):

xt = x[:, t, :]

next_h,_ = rnn_step_forward(xt, prev_h, Wx, Wh, b)

prev_h = next_h

h[:, t, :] = prev_h

cache = (x, h0, Wh, Wx, b, h)

#pass

##############################################################################

#                              END OF YOUR CODE                            #

##############################################################################

return h, cache

def rnn_backward(dh, cache):

"""

Compute the backward pass for a vanilla RNN over an entire sequence of data.

Inputs:

- dh: Upstream gradients of all hidden states, of shape (N, T, H)

Returns a tuple of:

- dx: Gradient of inputs, of shape (N, T, D)

- dh0: Gradient of initial hidden state, of shape (N, H)

- dWx: Gradient of input-to-hidden weights, of shape (D, H)

- dWh: Gradient of hidden-to-hidden weights, of shape (H, H)

- db: Gradient of biases, of shape (H,)

"""

dx, dh0, dWx, dWh, db = None, None, None, None, None

##############################################################################

# TODO: Implement the backward pass for a vanilla RNN running an entire      #

# sequence of data. You should use the rnn_step_backward function that you  #

# defined above.                                                            #

##############################################################################

x, h0, Wh, Wx, b, h = cache

N, T, H = dh.shape

_, _, D = x.shape

next_h = h[:,T-1,:]

dprev_h = np.zeros((N, H))

dx = np.zeros((N, T, D))

dh0 = np.zeros((N, H))

dWx= np.zeros((D, H))

dWh = np.zeros((H, H))

db = np.zeros((H,))

for t in range(T):

t = T-1-t

xt = x[:,t,:]

if t ==0:

prev_h = h0

else:

prev_h = h[:,t-1,:]

step_cache = (xt, prev_h, Wh, Wx, b, next_h)

next_h = prev_h

dnext_h = dh[:,t,:] + dprev_h

dx[:,t,:], dprev_h, dWxt, dWht, dbt = rnn_step_backward(dnext_h, step_cache)

dWx, dWh, db = dWx+dWxt, dWh+dWht, db+dbt

dh0 = dprev_h

#pass

##############################################################################

#                              END OF YOUR CODE                            #

##############################################################################

return dx, dh0, dWx, dWh, db

def word_embedding_forward(x, W):

"""

Forward pass for word embeddings. We operate on minibatches of size N where

each sequence has length T. We assume a vocabulary of V words, assigning each

to a vector of dimension D.

Inputs:

- x: Integer array of shape (N, T) giving indices of words. Each element idx

of x muxt be in the range 0 <= idx < V.

- W: Weight matrix of shape (V, D) giving word vectors for all words.

Returns a tuple of:

- out: Array of shape (N, T, D) giving word vectors for all input words.

- cache: Values needed for the backward pass

"""

out, cache = None, None

##############################################################################

# TODO: Implement the forward pass for word embeddings.                      #

#                                                                            #

# HINT: This should be very simple.                                          #

##############################################################################

N, T = x.shape

V, D = W.shape

out = np.zeros((N, T, D))

for i in range(N):

for j in range(T):

out[i, j] = W[x[i,j]]

cache = (x, W.shape)

#pass

##############################################################################

#                              END OF YOUR CODE                            #

##############################################################################

return out, cache

def word_embedding_backward(dout, cache):

"""

Backward pass for word embeddings. We cannot back-propagate into the words

since they are integers, so we only return gradient for the word embedding

matrix.

HINT: Look up the function np.add.at

Inputs:

- dout: Upstream gradients of shape (N, T, D)

- cache: Values from the forward pass

Returns:

- dW: Gradient of word embedding matrix, of shape (V, D).

"""

dW = None

##############################################################################

# TODO: Implement the backward pass for word embeddings.                    #

#                                                                            #

# HINT: Look up the function np.add.at                                      #

##############################################################################

x, W_shape = cache

dW = np.zeros(W_shape)

np.add.at(dW, x, dout)

#pass

##############################################################################

#                              END OF YOUR CODE                            #

##############################################################################

return dW

def sigmoid(x):

"""

A numerically stable version of the logistic sigmoid function.

"""

pos_mask = (x >= 0)

neg_mask = (x < 0)

z = np.zeros_like(x)

z[pos_mask] = np.exp(-x[pos_mask])

z[neg_mask] = np.exp(x[neg_mask])

top = np.ones_like(x)

top[neg_mask] = z[neg_mask]

return top / (1 + z)

def lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b):

"""

Forward pass for a single timestep of an LSTM.

The input data has dimension D, the hidden state has dimension H, and we use

a minibatch size of N.

Inputs:

- x: Input data, of shape (N, D)

- prev_h: Previous hidden state, of shape (N, H)

- prev_c: previous cell state, of shape (N, H)

- Wx: Input-to-hidden weights, of shape (D, 4H)

- Wh: Hidden-to-hidden weights, of shape (H, 4H)

- b: Biases, of shape (4H,)

Returns a tuple of:

- next_h: Next hidden state, of shape (N, H)

- next_c: Next cell state, of shape (N, H)

- cache: Tuple of values needed for backward pass.

"""

next_h, next_c, cache = None, None, None

#############################################################################

# TODO: Implement the forward pass for a single timestep of an LSTM.        #

# You may want to use the numerically stable sigmoid implementation above.  #

#############################################################################

H = Wh.shape[0]

a = x.dot(Wx) + prev_h.dot(Wh) + b

z_i = sigmoid(a[:,:H])

z_f = sigmoid(a[:,H:2*H])

z_o = sigmoid(a[:,2*H:3*H])

z_g = np.tanh(a[:,3*H:])

next_c = z_f * prev_c + z_i * z_g

z_t = np.tanh(next_c)

next_h = z_o * z_t

cache = (z_i, z_f, z_o, z_g, z_t, prev_c, prev_h, Wx, Wh, x)

#pass

##############################################################################

#                              END OF YOUR CODE                            #

##############################################################################

return next_h, next_c, cache

def lstm_step_backward(dnext_h, dnext_c, cache):

"""

Backward pass for a single timestep of an LSTM.

Inputs:

- dnext_h: Gradients of next hidden state, of shape (N, H)

- dnext_c: Gradients of next cell state, of shape (N, H)

- cache: Values from the forward pass

Returns a tuple of:

- dx: Gradient of input data, of shape (N, D)

- dprev_h: Gradient of previous hidden state, of shape (N, H)

- dprev_c: Gradient of previous cell state, of shape (N, H)

- dWx: Gradient of input-to-hidden weights, of shape (D, 4H)

- dWh: Gradient of hidden-to-hidden weights, of shape (H, 4H)

- db: Gradient of biases, of shape (4H,)

"""

dx, dh, dc, dWx, dWh, db = None, None, None, None, None, None

#############################################################################

# TODO: Implement the backward pass for a single timestep of an LSTM.      #

#                                                                          #

# HINT: For sigmoid and tanh you can compute local derivatives in terms of  #

# the output value from the nonlinearity.                                  #

#############################################################################

H = dnext_h.shape[1]

z_i, z_f, z_o, z_g, z_t, prev_c, prev_h, Wx, Wh, x = cache

dz_o = z_t * dnext_h

dc_t = z_o * (1 - z_t * z_t) * dnext_h + dnext_c

dz_f = prev_c * dc_t

dz_i = z_g * dc_t

dprev_c = z_f * dc_t

dz_g = z_i * dc_t

da_i = (1 - z_i) * z_i * dz_i

da_f = (1 - z_f) * z_f * dz_f

da_o = (1 - z_o) * z_o * dz_o

da_g = (1 - z_g * z_g) * dz_g

da = np.hstack((da_i, da_f, da_o, da_g))

dWx = x.T.dot(da)

dWh = prev_h.T.dot(da)

db = np.sum(da, axis = 0)

dx = da.dot(Wx.T)

dprev_h = da.dot(Wh.T)

#pass

##############################################################################

#                              END OF YOUR CODE                            #

##############################################################################

return dx, dprev_h, dprev_c, dWx, dWh, db

def lstm_forward(x, h0, Wx, Wh, b):

"""

Forward pass for an LSTM over an entire sequence of data. We assume an input

sequence composed of T vectors, each of dimension D. The LSTM uses a hidden

size of H, and we work over a minibatch containing N sequences. After running

the LSTM forward, we return the hidden states for all timesteps.

Note that the initial cell state is passed as input, but the initial cell

state is set to zero. Also note that the cell state is not returned; it is

an internal variable to the LSTM and is not accessed from outside.

Inputs:

- x: Input data of shape (N, T, D)

- h0: Initial hidden state of shape (N, H)

- Wx: Weights for input-to-hidden connections, of shape (D, 4H)

- Wh: Weights for hidden-to-hidden connections, of shape (H, 4H)

- b: Biases of shape (4H,)

Returns a tuple of:

- h: Hidden states for all timesteps of all sequences, of shape (N, T, H)

- cache: Values needed for the backward pass.

"""

h, cache = None, None

#############################################################################

# TODO: Implement the forward pass for an LSTM over an entire timeseries.  #

# You should use the lstm_step_forward function that you just defined.      #

#############################################################################

N, T, D = x.shape

H = b.shape[0]/4

h = np.zeros((N, T, H))

cache = {}

prev_h = h0

prev_c = np.zeros((N, H))

for t in range(T):

xt = x[:, t, :]

next_h, next_c, cache[t] = lstm_step_forward(xt, prev_h, prev_c, Wx, Wh, b)

prev_h = next_h

prev_c = next_c

h[:, t, :] = prev_h

#pass

##############################################################################

#                              END OF YOUR CODE                            #

##############################################################################

return h, cache

def lstm_backward(dh, cache):

"""

Backward pass for an LSTM over an entire sequence of data.]

Inputs:

- dh: Upstream gradients of hidden states, of shape (N, T, H)

- cache: Values from the forward pass

Returns a tuple of:

- dx: Gradient of input data of shape (N, T, D)

- dh0: Gradient of initial hidden state of shape (N, H)

- dWx: Gradient of input-to-hidden weight matrix of shape (D, 4H)

- dWh: Gradient of hidden-to-hidden weight matrix of shape (H, 4H)

- db: Gradient of biases, of shape (4H,)

"""

dx, dh0, dWx, dWh, db = None, None, None, None, None

#############################################################################

# TODO: Implement the backward pass for an LSTM over an entire timeseries.  #

# You should use the lstm_step_backward function that you just defined.    #

#############################################################################

N, T, H = dh.shape

z_i, z_f, z_o, z_g, z_t, prev_c, prev_h, Wx, Wh, x = cache[T-1]

D = x.shape[1]

dprev_h = np.zeros((N, H))

dprev_c = np.zeros((N, H))

dx = np.zeros((N, T, D))

dh0 = np.zeros((N, H))

dWx= np.zeros((D, 4*H))

dWh = np.zeros((H, 4*H))

db = np.zeros((4*H,))

for t in range(T):

t = T-1-t

step_cache = cache[t]

dnext_h = dh[:,t,:] + dprev_h

dnext_c = dprev_c

dx[:,t,:], dprev_h, dprev_c, dWxt, dWht, dbt = lstm_step_backward(dnext_h, dnext_c, step_cache)

dWx, dWh, db = dWx+dWxt, dWh+dWht, db+dbt

dh0 = dprev_h

#pass

##############################################################################

#                              END OF YOUR CODE                            #

##############################################################################

return dx, dh0, dWx, dWh, db

def temporal_affine_forward(x, w, b):

"""

Forward pass for a temporal affine layer. The input is a set of D-dimensional

vectors arranged into a minibatch of N timeseries, each of length T. We use

an affine function to transform each of those vectors into a new vector of

dimension M.

Inputs:

- x: Input data of shape (N, T, D)

- w: Weights of shape (D, M)

- b: Biases of shape (M,)

Returns a tuple of:

- out: Output data of shape (N, T, M)

- cache: Values needed for the backward pass

"""

N, T, D = x.shape

M = b.shape[0]

out = x.reshape(N * T, D).dot(w).reshape(N, T, M) + b

cache = x, w, b, out

return out, cache

def temporal_affine_backward(dout, cache):

"""

Backward pass for temporal affine layer.

Input:

- dout: Upstream gradients of shape (N, T, M)

- cache: Values from forward pass

Returns a tuple of:

- dx: Gradient of input, of shape (N, T, D)

- dw: Gradient of weights, of shape (D, M)

- db: Gradient of biases, of shape (M,)

"""

x, w, b, out = cache

N, T, D = x.shape

M = b.shape[0]

dx = dout.reshape(N * T, M).dot(w.T).reshape(N, T, D)

dw = dout.reshape(N * T, M).T.dot(x.reshape(N * T, D)).T

db = dout.sum(axis=(0, 1))

return dx, dw, db

def temporal_softmax_loss(x, y, mask, verbose=False):

"""

A temporal version of softmax loss for use in RNNs. We assume that we are

making predictions over a vocabulary of size V for each timestep of a

timeseries of length T, over a minibatch of size N. The input x gives scores

for all vocabulary elements at all timesteps, and y gives the indices of the

ground-truth element at each timestep. We use a cross-entropy loss at each

timestep, summing the loss over all timesteps and averaging across the

minibatch.

As an additional complication, we may want to ignore the model output at some

timesteps, since sequences of different length may have been combined into a

minibatch and padded with NULL tokens. The optional mask argument tells us

which elements should contribute to the loss.

Inputs:

- x: Input scores, of shape (N, T, V)

- y: Ground-truth indices, of shape (N, T) where each element is in the range

0 <= y[i, t] < V

- mask: Boolean array of shape (N, T) where mask[i, t] tells whether or not

the scores at x[i, t] should contribute to the loss.

Returns a tuple of:

- loss: Scalar giving loss

- dx: Gradient of loss with respect to scores x.

"""

N, T, V = x.shape

x_flat = x.reshape(N * T, V)

y_flat = y.reshape(N * T)

mask_flat = mask.reshape(N * T)

probs = np.exp(x_flat - np.max(x_flat, axis=1, keepdims=True))

probs /= np.sum(probs, axis=1, keepdims=True)

loss = -np.sum(mask_flat * np.log(probs[np.arange(N * T), y_flat])) / N

dx_flat = probs.copy()

dx_flat[np.arange(N * T), y_flat] -= 1

dx_flat /= N

dx_flat *= mask_flat[:, None]

if verbose: print 'dx_flat: ', dx_flat.shape

dx = dx_flat.reshape(N, T, V)

return loss, dx

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,302评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,563评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,433评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,628评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,467评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,354评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,777评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,419评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,725评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,768评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,543评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,387评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,794评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,032评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,305评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,741评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,946评论 2 336

推荐阅读更多精彩内容