温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何进行RNN总结及sin与cos拟合应用

发布时间:2022-01-04 17:23:49 来源:亿速云 阅读:179 作者:柒染 栏目:大数据

如何进行RNN总结及sin与cos拟合应用,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

一、RNN总结

    一个简单的RNN模型由输入层,一个隐藏层,一个输出层组成。

如何进行RNN总结及sin与cos拟合应用

我们给出这个抽象图对应的具体图,能够很清楚的看到,上一时刻的隐藏层是如何影响当前时刻的隐藏层的。

如何进行RNN总结及sin与cos拟合应用

基于RNN还可以继续扩展到双向循环神经网络,深度循环神经网络。RNN公式如下:如何进行RNN总结及sin与cos拟合应用

                                                     如何进行RNN总结及sin与cos拟合应用                                   

定义RNN类,代码如下:

from torch import nn

class RNN(nn.Module):
    def __init__(self):
        super(RNN, self).__init__()

        self.rnn = nn.RNN(
            input_size=INPUT_SIZE, # The number of expected features in the input `x`
            hidden_size=32, # The number of features in the hidden state `h`
            num_layers=1, # Number of recurrent layers
            batch_first=True # batch维度是否在前,If ``True``, tensors as `(batch, seq, feature)`
        )
        self.out = nn.Linear(32, 1) # 线性变换

    def forward(self, x, h_state):
        out, h_state = self.rnn(x, h_state)
        return out, h_state

Tips: 1. RNN的训练算法是BPTT,它的基本原理核BP算法一致,包含同样的三个步骤:1) 前向计算每个神经元的输出值;2)反向计算每个神经元的误差项ᵟ_j值,它是误差函数E对神经元j的加权输出net_j的偏导数;3)计算每个权重的梯度。

2. RNN的梯度消失核爆炸,根据公式的指数形式,β大于或小于1都将造成梯度消失核爆炸问题。如何进行RNN总结及sin与cos拟合应用

如何避免:1) 梯度爆炸:设置一个梯度阈值,当梯度超过这个阈值的时候可以直接截取 (Gradient Clipping(pytorch  nn.utils.clip_grad_norm )) ;好的参数初始化方式,如He初始化; 非饱和的激活函数(如 ReLU) ; 批量规范化(Batch Normalization); LSTM 。2)梯度消失:改进网络LSTM,加入了forget gate。

二、sin与cos拟合应用

函数sin拟合为cos,模型黑盒子类似sin(π/2+α)= cosα

import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt

# 定义超参数
TIME_STEP = 10
INPUT_SIZE = 1
learning_rate = 0.001

class RNN(nn.Module):
    def __init__(self):
        super(RNN, self).__init__()

        self.rnn = nn.RNN(
            input_size=INPUT_SIZE,
            hidden_size=32,
            num_layers=1,
            batch_first=True
        )
        self.out = nn.Linear(32, 1)

    def forward(self, x, h_state):
        # r_out.shape:seq_len,batch,hidden_size*num_direction(1,10,32)
        r_out, h_state = self.rnn(x, h_state)
        out = self.out(r_out).squeeze()
        return out, h_state

rnn = RNN()

criterion = nn.MSELoss()
optimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)

h_state = None

plt.figure(1, figsize=(12, 5))
plt.ion() # 开启动态交互

for step in range(100):
    start, end = step * np.pi, (step + 1) * np.pi
    steps = np.linspace(start, end, TIME_STEP, dtype=np.float32, endpoint=False)
    x_np = np.sin(steps) # x_np.shape: 10
    y_np = np.cos(steps) # y_np.shape: 10

    x = torch.from_numpy(x_np[np.newaxis, :, np.newaxis]) # x.shape: 1,10,1
    y = torch.from_numpy(y_np) # y.shape: 10

    prediction, h_state = rnn(x, h_state)
    h_state = h_state.data

    loss = criterion(prediction, y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    plt.plot(steps, y_np.flatten(), 'r-')
    plt.plot(steps, prediction.data.numpy().flatten(), 'b-')
    plt.draw()
    plt.pause(.05)

plt.ioff()
plt.show()

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI