pytorch中的LSTM

RNN和RNNCell层的区别在于前者能处理整个序列,而后者一次只处理序列中一个时间点的数据,前者封装更完备更易于使用,后者更具灵活性。RNN层可以通过调用RNNCell来实现

# -*- coding: utf-8 -*-
#@Time    :2019/7/1 22:41
#@Author  :XiaoMa
import torch as t
from torch.autograd import Variable as V
from torch import nn
t.manual_seed(1000)#设置随机数种子,保证每次运行得到相同的结果
input=V(t.randn(2,3,4)) #batch_size=3,序列长度为2,序列中每个元素占4维

#LSTM输入向量为4维,3个隐藏元,1层
lstm=nn.LSTM(4,3,1)

#初始状态:1层,batch_size=3,3个隐藏元
h0=V(t.randn(1,3,3))
c0=V(t.randn(1,3,3))

out,hn=lstm(input,(h0,c0))
print(out)

输出结果:

tensor([[[-0.3610, -0.1643,  0.1631],
         [-0.0613, -0.4937, -0.1642],
         [ 0.5080, -0.4175,  0.2502]],

        [[-0.0703, -0.0393, -0.0429],
         [ 0.2085, -0.3005, -0.2686],
         [ 0.1482, -0.4728,  0.1425]]], grad_fn=<CatBackward>)

示例2:

# -*- coding: utf-8 -*-
#@Time    :2019/7/2 14:04
#@Author  :XiaoMa

import torch as t
from torch.autograd import Variable as V
from torch import nn
t.manual_seed(1000)#设置随机数种子,保证每次运行得到相同的结果
input=V(t.randn(2,3,4)) #batch_size=3,序列长度为2,序列中每个元素占4维


input=V(t.randn(2,3,4))
#一个LSTMCell对应的层数只能是一层
lstm=nn.LSTMCell(4,3)
hx=V(t.randn(3,3,))
cx=V(t.randn(3,3))
out=[]

for i_ in input:
    hx,cx=lstm(i_,(hx,cx))
    out.append(hx)
print(t.stack(out))

#pytorch中的embedding层
embedding=nn.Embedding(4,5) #有4个词,每个词有5维向量表示

#可以用预训练好的词向量初始化embedding
embedding.weight.data=t.arange(0,20).view(4,5)

input=V(t.arange(3,0,-1).long())
output=embedding(input)
print('output=',output)

输出结果:

         [ 0.2780,  0.0367, -0.0181],
         [-0.0443,  0.2794, -0.3031]],

        [[ 0.1455,  0.0193, -0.0891],
         [ 0.3409,  0.2397, -0.2647],
         [ 0.1984,  0.0731, -0.2611]]], grad_fn=<StackBackward>)
output= tensor([[15, 16, 17, 18, 19],
        [10, 11, 12, 13, 14],
        [ 5,  6,  7,  8,  9]], grad_fn=<EmbeddingBackward>)

 

 

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch ,可以通过 `nn.LSTM` 类来创建 LSTM 模型。 下面是一个简单的 LSTM 模型的示例代码: ```python import torch.nn as nn class LSTMModel(nn.Module): def __init__(self, input_size, hidden_size, num_layers, output_size): super(LSTMModel, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True) self.fc = nn.Linear(hidden_size, output_size) def forward(self, x): h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) out, _ = self.lstm(x, (h0, c0)) out = self.fc(out[:, -1, :]) return out ``` 在上面的代码,`nn.LSTM` 的第一个参数是输入特征的维度,第二个参数是隐藏层的维度,第三个参数是 LSTM 层数,`batch_first=True` 表示输入的第一个维度是 batch 的大小。 在 `forward` 方法,我们首先定义了初始的隐藏状态 `h0` 和记忆状态 `c0`,然后将输入 `x` 和初始状态传入 `nn.LSTM` ,得到输出 `out`。由于我们只关心最后一个时间步的输出,所以我们取 `out[:, -1, :]`,然后将其传入全连接层 `nn.Linear` 得到最终的输出。 需要注意的是,在使用 LSTM 模型时,需要将输入数据转换为 PyTorch 的张量,并将其发送到 GPU 上进行计算。例如,`x = torch.tensor(x).float().to(device)`。其 `x` 是输入数据,`device` 是计算设备。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值