如何编写循环神经网络的简单前向传播?

数据挖掘 Python 深度学习 lstm 麻木的 rnn
2022-03-04 13:10:57

我知道递归神经网络或 RNN 背后的理论,但我对它的实现感到困惑。这是我从网上得到的一个rnn方程, 在此处输入图像描述

我试图在 python 的 numpy 中单独编码前向传播

import numpy as np

outputs = 5
inputs = 3

# Input value
# (batch_size,seq_len, vocab_len)
X = np.ones((10,3,3))


# Initializing rnn weights and hidden states
Wxh = np.random.rand(outputs,inputs)
Whh = np.random.rand(outputs,inputs)
Why = np.random.rand(outputs,inputs)
h = np.zeros((1,inputs))

# Forward propagation
def rnn(x,h):
    h = np.tanh(np.dot(Whh,h.T) + np.dot(Wxh,x.T))
    y = np.dot(Why,h.T)
    return y,h

for i in X:
    _,h = rnn(i,h)

但我收到广播错误。我们如何实现 rnn 的前向传播?

1个回答

换句话说,RNN 的前向传播是什么样的。您阅读了有关使用来自前一个节点的输入加上值(这里将是 prev_s)首先初始化权重,然后执行前向传递。我突出显示了您要查找的内容。

U = np.random.uniform(0, 1, (hidden_dim, T))
W = np.random.uniform(0, 1, (hidden_dim, hidden_dim))
V = np.random.uniform(0, 1, (output_dim, hidden_dim))


 for i in range(Y.shape[0]):
        x, y = X[i], Y[i]

        layers = []
        prev_s = np.zeros((hidden_dim, 1))
        dU = np.zeros(U.shape)
        dV = np.zeros(V.shape)
        dW = np.zeros(W.shape)

        dU_t = np.zeros(U.shape)
        dV_t = np.zeros(V.shape)
        dW_t = np.zeros(W.shape)

        dU_i = np.zeros(U.shape)
        dW_i = np.zeros(W.shape)

        # forward pass
        for t in range(T):
            new_input = np.zeros(x.shape)
            new_input[t] = x[t]
            mulu = np.dot(U, new_input)
            mulw = np.dot(W, prev_s)
            add = mulw + mulu
            s = sigmoid(add)
            ***mulv = np.dot(V, s)***
            layers.append({'s':s, 'prev_s':prev_s})
            prev_s = s

所以' * * '区域可以大致翻译为:mulv = np.dot(V, s) 是权重乘以当前状态。(与之前相同,s==input_vector)但不同之处在于 s 将使用来自先前输出和当前输入的权重来计算,即

mulu = np.dot(U, new_input)
mulw = np.dot(W, prev_s)
add = mulw + mulu
s = sigmoid(add)

这就是为什么我们首先有 3 个初始权重。