当前位置:   article > 正文

《PyTorch深度学习实践》第十二讲循环神经网络基础

《PyTorch深度学习实践》第十二讲循环神经网络基础

一、RNN简介

1、RNN网络最大的特点就是可以处理序列特征,就是我们的一组动态特征。比如,我们可以通过将前三天每天的特征(是否下雨,是否有太阳等)输入到网络,从而来预测第四天的天气。
       我们可以看RNN的网络结构如下:

二、RNN cell用法

  1. import torch
  2. batch_size = 1 # 批处理大小
  3. seq_len = 3 # 序列长度
  4. input_size = 4 # 输入维度
  5. hidden_size = 2 # 隐藏层维度
  6. cell = torch.nn.RNNCell(input_size=input_size, hidden_size=hidden_size)
  7. # (seq, batch, features)
  8. dataset = torch.randn(seq_len, batch_size, input_size)
  9. print(dataset)
  10. hidden = torch.zeros(batch_size, hidden_size)
  11. print(hidden)
  12. for idx, input in enumerate(dataset):
  13. print( '=' * 20, idx, '=' * 20)
  14. print( 'Input size: ', input.shape)
  15. hidden = cell(input, hidden)
  16. print( 'outputs size: ', hidden.shape)
  17. print(hidden)

三、RNN用法

  1. import torch
  2. batch_size = 1 # 批处理大小
  3. seq_len = 3 # 序列长度
  4. input_size = 4 # 输入维度
  5. hidden_size = 2 # 隐藏层维度
  6. num_layers = 4 # 隐藏层数量
  7. cell = torch.nn.RNN(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers)
  8. # (seqLen, batchSize, inputSize)
  9. inputs = torch.randn(seq_len, batch_size, input_size)
  10. hidden = torch.zeros(num_layers, batch_size, hidden_size)
  11. out, hidden = cell(inputs, hidden)
  12. print( 'Output size:', out.shape)
  13. print( 'Output:', out)
  14. print( 'Hidden size: ', hidden.shape)
  15. print( 'Hidden: ', hidden)

四、Embedding

把input变为稠密的数据

代码:

  1. import torch
  2. # parameters
  3. num_class = 4
  4. input_size = 4
  5. hidden_size = 8
  6. embedding_size = 10
  7. num_layers = 2
  8. batch_size = 1
  9. seq_len = 5
  10. # 准备数据集
  11. idx2char = ['e', 'h', 'l', 'o']
  12. x_data = [[1, 0, 2, 2, 3]] # (batch, seq_len)
  13. y_data = [3, 1, 2, 3, 2] # (batch * seq_len)
  14. inputs = torch.LongTensor(x_data) # Input should be LongTensor: (batchSize, seqLen)
  15. labels = torch.LongTensor(y_data) # Target should be LongTensor: (batchSize * seqLen)
  16. # 构建模型
  17. class Model(torch.nn.Module):
  18. def __init__(self):
  19. super(Model, self).__init__()
  20. self.emb = torch.nn.Embedding(input_size, embedding_size)
  21. self.rnn = torch.nn.RNN(input_size=embedding_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True)
  22. self.fc = torch.nn.Linear(hidden_size, num_class)
  23. def forward(self, x):
  24. hidden = torch.zeros(num_layers, x.size(0), hidden_size)
  25. x = self.emb(x) # (batch, seqLen, embeddingSize)
  26. x, _ = self.rnn(x, hidden) # 输出(
    声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/182953
    推荐阅读
    相关标签