pytorch时空数据处理1——LSTM介绍及图像分类

了解LSTM网络(From http://colah.github.io/posts/2015-08-Understanding-LSTMs/ )

递归神经网络简单提要

LSTM-RNN展开图

遗忘门:第一个利用上一次的输出和这次的输入通过sigmoid函数的0~1的取值转化为一个权重矩阵,通过与Ct-1相乘按权重矩阵值选择性保留Ct-1中的信息。
遗忘门(forget gate)

输入门:(可详细分为左边输入门那些作为输入,右边更新门哪些需要强调)

输入门(input gate)

输出门:输出门用来控制当前的单元状态有多少被过滤掉。先将单元状态激活,输出门为其中每一项产生一个在[0,1]内的值,控制单元状态被过滤的程度。

这里写图片描述

举例说明

纬度的变化通过权重矩阵W来实现。

1.假设经过上层传入LSTM的x1=[1,2,3],那么如果为第一个则初始化h=[0,0,0,0,0](假设神经元个数为5),初始s=[0,0,0,0,0],每个门的权重W矩阵维度为(5,8),偏置b的维度为(5,);

2.执行第一步,拼接x1和h形成一个维度为(8,)的输入,这里暂且记为input;根据上面公式算每个门的值,以遗忘门为例:

f=sigmoid(np.dot(wf,input)+bf)可以得出f的维度为(5,)你会发现f的维度跟初始的C一样,所以可以进行相乘运算;那么我们易知每个门的计算值的维度均为(5,),所以你会发现一切的点乘和相加都能够正常计算;那么我们可以推出h的维度也为(5,)

 综上,可以直达在LSTM网络中的S也作C的维度为(神经元个数,),h的维度也为(神经元个数,)

https://www.zhihu.com/question/41949741/answer/318771336

Lstm 计算过程动图表示

pytorch下LSTM实验

pytorch时空数据处理1——LSTM介绍及图像分类_第1张图片

代码实现 pytorch使用LSTM实现手写数字图像分类

载入需要的包

import torch
import numpy as np
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt
import os
os.environ["CUDA_VISIBLE_EDVICES"] = '9' #指定代号为9的那块GPU

设定超参数,自动下载手写数字图像数据集

#超参数设定
epoch = 2
lr = 0.01
batch_size=50
train_data = torchvision.datasets.MNIST(
    root='./datas/',   #下载到该目录下
    train=True,                                     #为训练数据
    transform=torchvision.transforms.ToTensor(),    #将其装换为tensor的形式
    download=False, #第一次设置为true表示下载,下载完成后,将其置成false
)
test_data = torchvision.datasets.MNIST(
    root='./datas/',
    train=False, # this is training data
    transform=torchvision.transforms.ToTensor(),
    download=True,
)

设定数据载入方式

train_loader = Data.DataLoader(dataset=train_data, batch_size=batch_size, shuffle=True)
test_x = test_data.data.type(torch.FloatTensor)[:2000]/255
test_y = test_data.targets[:2000]

定义LSTM网络

class LSTMnet(nn.Module):
    def __init__(self, in_dim, hidden_dim, n_layer, n_class):
        super(LSTMnet, self).__init__()
        self.n_layer = n_layer
        self.hidden_dim = hidden_dim
        self.lstm = nn.LSTM(in_dim, hidden_dim, n_layer, batch_first=True)
        self.linear = nn.Linear(hidden_dim, n_class)

    def forward(self, x):                  # x‘s shape (batch_size, 序列长度, 序列中每个数据的长度)
        out, _ = self.lstm(x)              # out‘s shape (batch_size, 序列长度, hidden_dim)
        out = out[:, -1, :]                # 中间的序列长度取-1,表示取序列中的最后一个数据,这个数据长度为hidden_dim,
                                           # 得到的out的shape为(batch_size, hidden_dim)
        out = self.linear(out)             # 经过线性层后,out的shape为(batch_size, n_class)
        return out

训练与测试

torch.cuda.set_device(9)
model = LSTMnet(28, 56, 2, 10)             # 图片大小28*28,lstm的每个隐藏层56(自己设定数量大小)个节点,2层隐藏层
if torch.cuda.is_available():
    model = model.cuda()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
criterion = nn.CrossEntropyLoss()


# training and testing
for epoch in range(2):
    for iteration, (train_x, train_y) in enumerate(train_loader):    # train_x‘s shape (BATCH_SIZE,1,28,28)
        train_x = train_x.squeeze()# after squeeze, train_x‘s shape (BATCH_SIZE,28,28),
        #print(train_x.size())  # 第一个28是序列长度(看做句子的长度),第二个28是序列中每个数据的长度(词纬度)。
        train_x = train_x.cuda()
        print(train_x[0])
        train_y = train_y.cuda()
        test_x = test_x.cuda()
        #print(test_x[0])
        test_y = test_y.cuda()
        output = model(train_x)
        loss = criterion(output, train_y)  # cross entropy loss
        optimizer.zero_grad()              # clear gradients for this training step
        loss.backward()                    # backpropagation, compute gradients
        optimizer.step()                   # apply gradients

        if iteration % 100 == 0:
            test_output = model(test_x)
            predict_y = torch.max(test_output, 1)[1].cpu().numpy()
            accuracy = float((predict_y == test_y.cpu().numpy()).astype(int).sum()) / float(test_y.size(0))
            print('epoch:{:<2d} | iteration:{:<4d} | loss:{:<6.4f} | accuracy:{:<4.2f}'.format(epoch, iteration, loss, accuracy))

结果截图

epoch:0  | iteration:0    | loss:0.2809 | accuracy:0.88
epoch:0  | iteration:100  | loss:0.2044 | accuracy:0.92
epoch:0  | iteration:200  | loss:0.4246 | accuracy:0.88
epoch:0  | iteration:300  | loss:0.3319 | accuracy:0.92
epoch:0  | iteration:400  | loss:0.1774 | accuracy:0.95
epoch:0  | iteration:500  | loss:0.1981 | accuracy:0.95
epoch:0  | iteration:600  | loss:0.4158 | accuracy:0.92

 

你可能感兴趣的:(pytorch,#,视频异常事件挖掘,#,pytorch时空数据处理,深度学习,神经网络,人工智能)