pytorch时空数据处理1 您所在的位置:网站首页 pytorch三分类分类预测 pytorch时空数据处理1

pytorch时空数据处理1

2024-07-15 07:34| 来源: 网络整理| 查看: 265

了解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使用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:{:


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有