牛客题解 | 实现一个简单的循环神经网络

题目

题目链接

循环神经网络(RNN)是一种能够处理序列数据的神经网络,其特点是能够处理时间序列数据。
RNN的具体步骤如下:

  1. 计算隐藏状态更新
    h t = tanh ⁡ ( W x ⋅ x t + W h ⋅ h t − 1 + b ) h_t = \tanh(W_x \cdot x_t + W_h \cdot h_{t-1} + b) ht=tanh(Wxxt+Whht1+b)
  2. 计算输出
    y t = W y ⋅ h t + b y y_t = W_y \cdot h_t + b_y yt=Wyht+by
  3. 计算损失
    l o s s = ∑ t = 1 T ( y t − y ^ t ) 2 loss = \sum_{t=1}^{T} (y_t - \hat{y}_t)^2 loss=t=1T(yty^t)2
  4. 反向传播
    ∂ l o s s ∂ W h = ∑ t = 1 T ∂ l o s s ∂ y t ⋅ ∂ y t ∂ h t ⋅ ∂ h t ∂ W h \frac{\partial loss}{\partial W_h} = \sum_{t=1}^{T} \frac{\partial loss}{\partial y_t} \cdot \frac{\partial y_t}{\partial h_t} \cdot \frac{\partial h_t}{\partial W_h} Whloss=t=1TytlosshtytWhht
    本题只要求实现前向传播,反向传播不要求实现。

标准代码如下

def rnn_forward(input_sequence, initial_hidden_state, Wx, Wh, b):
    h = np.array(initial_hidden_state)
    Wx = np.array(Wx)
    Wh = np.array(Wh)
    b = np.array(b)
    for x in input_sequence:
        x = np.array(x)
        h = np.tanh(np.dot(Wx, x) + np.dot(Wh, h) + b)
    final_hidden_state = np.round(h, 4)
    return final_hidden_state.tolist()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值