pytorch中LSTM笔记

title: pytorch中LSTM笔记
date: 2018-07-12 16:52:53
tags:
- torch项目
categories:
- pytorch


单向LSTM笔记

专业笔记见中文参考英文参考

torch.nn.LSTM()输入API

  • 重要参数
    • input_size: 每一个时步(time_step)输入到lstm单元的维度.(实际输入的数据size为[batch_size, input_size])
    • hidden_size: 确定了隐含状态hidden_state的维度. 可以简单的看成: 构造了一个权重 , 隐含状态
    •  

       

      num_layers: 叠加的层数。如图所示num_layers为3

      图 1.

  • batch_first: 输入数据的size为[batch_size, time_step, input_size]还是[time_step, batch_size, input_size]

示例代码

使用单向LSTM进行MNIST分类

 

import torch
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt
import numpy as np
BATCH_SIZE = 50

class RNN(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.rnn=torch.nn.LSTM(
            input_size=28,
            hidden_size=64,
            num_layers=1,
            batch_first=True
        )
        self.out=torch.nn.Linear(in_features=64,out_features=10)

    def forward(self,x):
        # 一下关于shape的注释只针对单项
        # output: [batch_size, time_step, hidden_size]
        # h_n: [num_layers,batch_size, hidden_size] # 虽然LSTM的batch_first为True,但是h_n/c_n的第一维还是num_layers
        # c_n: 同h_n
        output,(h_n,c_n)=self.rnn(x)
        print(output.size())
        # output_in_last_timestep=output[:,-1,:] # 也是可以的
        output_in_last_timestep=h_n[-1,:,:]
        # print(output_in_last_timestep.equal(output[:,-1,:])) #ture
        x=self.out(output_in_last_timestep)
        return x

if __name__ == "__main__":
    # 1. 加载数据
    training_dataset = torchvision.datasets.MNIST("./mnist", train=True,
                                                  transform=torchvision.transforms.ToTensor(), download=True)
    dataloader = Data.DataLoader(dataset=training_dataset,
                                          batch_size=BATCH_SIZE, shuffle=True, num_workers=2)
    # showSample(dataloader)
    test_data=torchvision.datasets.MNIST(root="./mnist",train=False,
                                        transform=torchvision.transforms.ToTensor(),download=False)
    test_dataloader=Data.DataLoader(
        dataset=test_data,batch_size=1000,shuffle=False,num_workers=2)
    testdata_iter=iter(test_dataloader)
    test_x,test_y=testdata_iter.next()
    test_x=test_x.view(-1,28,28)
    # 2. 网络搭建
    net=RNN()
    # 3. 训练
    # 3. 网络的训练(和之前CNN训练的代码基本一样)
    optimizer=torch.optim.Adam(net.parameters(),lr=0.001)
    loss_F=torch.nn.CrossEntropyLoss()
    for epoch in range(1): # 数据集只迭代一次
        for step, input_data in enumerate(dataloader):
            x,y=input_data
            pred=net(x.view(-1,28,28))
    
            loss=loss_F(pred,y) # 计算loss
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            if step%50==49: # 每50步,计算精度
                with torch.no_grad():
                    test_pred=net(test_x)
                    prob=torch.nn.functional.softmax(test_pred,dim=1)
                    pred_cls=torch.argmax(prob,dim=1)
                    acc=(pred_cls==test_y).sum().numpy()/pred_cls.size()[0]
                    print(f"{epoch}-{step}: accuracy:{acc}")

LSTM输出API

由上面代码可以看到输出为:output,(h_n,c_n)=self.rnn(x)

image

  • output: 如果num_layer为3,则output只记录最后一层(即,第三层)的输出

    • 对应图中向上的各个time_step的,也即output
    • 其size根据batch_first而不同。可能是[batch_size, time_step, hidden_size][time_step, batch_size, hidden_size]
  • h_n: 各个层的最后一个时步的隐含状态h.

    • size为[num_layers,batch_size, hidden_size]
    • 对应图中向右的. 可以看出对于单层单向的LSTM, 其h_n最后一层输出h_n[-1,:,:],和output最后一个时步的输出output[:,-1,:]相等。在示例代码中print(h_n[-1,:,:].equal(output[:,-1,:]))会打印True
  • c_n: 各个层的最后一个时步的隐含状态C

    • c_n可以看成另一个隐含状态,size和h_n相同

参考文献



作者:FantDing
链接:https://www.jianshu.com/p/043083d114d4
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值