当前位置:   article > 正文

从零开始深度学习0614——pytorch入门之RNN实现图像分类和回归预测_transforms 输出hidden state

transforms 输出hidden state

RNN实现图像分类

用RNN处理图像

如何将图像的处理理解为时间序列

可以理解为时间序顺序为从上到下

Mnist图像的处理  一个图像为28*28 pixel

时间顺序就是从上往下,从第一行到第28行

  1. # Hyper Parameters
  2. EPOCH = 1     
  3. BATCH_SIZE = 64
  4. TIME_STEP = 28          # rnn time step / image height   一共输入time_step次。 时序步长数  seq_len
  5. INPUT_SIZE = 28         # rnn input size / image width   每次输入多少   输入维度
  6. LR = 0.01               # learning rate
  7. DOWNLOAD_MNIST = True   # set to True if haven't download the data

 

  1. self.rnn = nn.LSTM(         # if use nn.RNN(), it hardly learns
  2.     input_size=INPUT_SIZE,
  3.     hidden_size=64,         # rnn hidden unit  隐藏层神经元的个数
  4.     num_layers=1,           # number of rnn layer  多少层
  5.     batch_first=True,
  6. )

 

https://www.jianshu.com/p/41c15d301542 

理解为什么RNN输入默认不是batch first=True?这是为了便于并行计算。

r_out, (h_n, h_c) = self.rnn(x, None)

 

# x shape (batch, time_step, input_size)
# r_out shape (batch, time_step, output_size)
# h_n 的形状是 (n_layers, batch, hidden_size) t=time_step 时刻的隐层状态  分线剧情  hidden_state = (h_n, h_c)
# h_c 的形状是 (n_layers, batch, hidden_size) t=time_step 时刻的细胞状态  主线剧情
# 每一次处理完后会输出hidden_state 产生output , 结合下一次读取图像处理完输出的hidden_state 又产生output 这样循环
# 意思就是每一时刻的输入 会包括上一时刻的输入
# 其中hidden_state,又分为 h_n, h_c == h_state, c_state。

 

# h_n和output的关系: output包括了time_step中每一个时间点的隐层状态,
#                   而h_n是第time_step时刻的隐层状态, 所以output中最后一个元素就是h_n, 即output[-1] == h_n.

 

 

b_x = b_x.view(-1, 28, 28)     # 变一下维度 在pytorch中是.view()的形式表示reshape

 

完整代码:

LSTM实现是写数字识别

  1. import torch
  2. from torch import nn
  3. import torchvision.datasets as dsets
  4. import torchvision.transforms as transforms
  5. import matplotlib.pyplot as plt
  6. # torch.manual_seed(1)    # reproducible
  7. # Hyper Parameters
  8. EPOCH = 1               # train the training data n times, to save time, we just train 1 epoch
  9. BATCH_SIZE = 64
  10. TIME_STEP = 28          # rnn time step / image height   一共输入time_step次。 时序步长数  seq_len
  11. INPUT_SIZE = 28         # rnn input size / image width   每次输入多少   输入维度
  12. LR = 0.01               # learning rate
  13. DOWNLOAD_MNIST = True   # set to True if haven't download the data
  14. # Mnist digital dataset
  15. train_data = dsets.MNIST(
  16.     root='./mnist/',
  17.     train=True,                         # this is training data
  18.     transform=transforms.ToTensor(),    # Converts a PIL.Image or numpy.ndarray to
  19.                                         # torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
  20.     download=DOWNLOAD_MNIST,            # download it if you don't have it
  21. )
  22. # plot one example
  23. print(train_data.train_data.size())     # (60000, 28, 28)
  24. print(train_data.train_labels.size())   # (60000)
  25. plt.imshow(train_data.train_data[0].numpy(), cmap='gray')
  26. plt.title('%i' % train_data.train_labels[0])
  27. plt.show()
  28. # Data Loader for easy mini-batch return in training
  29. train_loader = torch.utils.data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)
  30. # convert test data into Variable, pick 2000 samples to speed up testing
  31. test_data = dsets.MNIST(root='./mnist/', train=False, transform=transforms.ToTensor())
  32. test_x = test_data.test_data.type(torch.FloatTensor)[:2000]/255.   # shape (2000, 28, 28) value in range(0,1)
  33. test_y = test_data.test_labels.numpy()[:2000]    # covert to numpy array
  34. class RNN(nn.Module):
  35.     def __init__(self):
  36.         super(RNN, self).__init__()
  37.         # LSTM 函数的参数和RNN都是一致的, 区别在于输入输出不同,LSTM 多了一个细胞的状态, 所以每一个循环层都增加了一个细胞状态h_c的输出.
  38.         self.rnn = nn.LSTM(         # if use nn.RNN(), it hardly learns
  39.             input_size=INPUT_SIZE,
  40.             hidden_size=64,         # rnn hidden unit  隐藏层神经元的个数
  41.             num_layers=1,           # number of rnn layer  多少层
  42.             batch_first=True,
  43.             # https://www.jianshu.com/p/41c15d301542  理解为什么RNN输入默认不是batch first=True?这是为了便于并行计算。
  44.             # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)
  45.             # 默认是(time_step, batch, input_size) 如果batch_first=True, 则 (batch, time_step, input_size)
  46.         )
  47.         self.out = nn.Linear(64, 10)
  48.     def forward(self, x):
  49.         # x shape (batch, time_step, input_size)
  50.         # r_out shape (batch, time_step, output_size)
  51.         # h_n 的形状是 (n_layers, batch, hidden_size) t=time_step 时刻的隐层状态  分线剧情  hidden_state = (h_n, h_c)
  52.         # h_c 的形状是 (n_layers, batch, hidden_size) t=time_step 时刻的细胞状态  主线剧情
  53.         # 每一次处理完后会输出hidden_state 产生output , 结合下一次读取图像处理完输出的hidden_state 又产生output 这样循环
  54.         # 意思就是每一时刻的输入 会包括上一时刻的输入
  55.         # 其中hidden_state,又分为 h_n, h_c == h_state, c_state。
  56.         r_out, (h_n, h_c) = self.rnn(x, None)   # None represents zero initial hidden state
  57.         # h_n和output的关系: output包括了time_step中每一个时间点的隐层状态,
  58.         #                   而h_n是第time_step时刻的隐层状态, 所以output中最后一个元素就是h_n, 即output[-1] == h_n.
  59.         # choose r_out at the last time step
  60.         out = self.out(r_out[:, -1, :])  # r_out shape (batch, time_step, output_size)  在time_step位置插上-1就表示最后一个时刻
  61.         return out
  62. rnn = RNN()
  63. print(rnn)
  64. optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)   # optimize all cnn parameters
  65. loss_func = nn.CrossEntropyLoss()                       # the target label is not one-hotted
  66. # training and testing
  67. for epoch in range(EPOCH):
  68.     for step, (b_x, b_y) in enumerate(train_loader):        # gives batch data
  69.         b_x = b_x.view(-1, 28, 28)                      # 变一下维度 在pytorch中是.view()的形式表示reshape    reshape x to (batch, time_step, input_size)
  70.         output = rnn(b_x)                               # rnn output
  71.         loss = loss_func(output, b_y)                   # cross entropy loss
  72.         optimizer.zero_grad()                           # clear gradients for this training step
  73.         loss.backward()                                 # backpropagation, compute gradients
  74.         optimizer.step()                                # apply gradients
  75.         if step % 50 == 0:
  76.             test_output = rnn(test_x)                   # (samples, time_step, input_size)
  77.             pred_y = torch.max(test_output, 1)[1].data.numpy()
  78.             accuracy = float((pred_y == test_y).astype(int).sum()) / float(test_y.size)
  79.             print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)
  80. # print 10 predictions from test data
  81. test_output = rnn(test_x[:10].view(-1, 28, 28))
  82. pred_y = torch.max(test_output, 1)[1].data.numpy()
  83. print(pred_y, 'prediction number')
  84. print(test_y[:10], 'real number')

运行结果:

 

-------------------------------------------------RNN regressor----------------------------------------------------------------------

##################################################################################

############################################################################

目的

通过sin曲线

去生成cos曲线

 

其中

  1. def forward(self, x, h_state):
  2.     # x (batch, time_step, input_size)
  3.     # h_state (n_layers, batch, hidden_size)
  4.     # r_out (batch, time_step, hidden_size)
  5.     # r_out 保存所有time_step的hidden_state
  6.     r_out, h_state = self.rnn(x, h_state)
  7.     outs = []  # save all predictions
  8.     for time_step in range(r_out.size(1)):  # calculate output for each time step
  9.         outs.append(self.out(r_out[:, time_step, :]))
  10.     return torch.stack(outs, dim=1), h_state

其中有一个类似递归的思想

不断的产生h_state 然后再作为输入

所以在后面调用的时候需要第一次传入一个h_state

 

其次self.rnn()  会生成r_out , h_state

区别于 self.lstm()   会生成r_out , (h_n , h_c)

 

将每一次time_step 的r_out 作为输入到out中

将结果存入outs[ ]

因为r_out shape (batch, time_step, hidden_size)

所以

  1. outs = []  # save all predictions
  2. for time_step in range(r_out.size(1)):  # calculate output for each time step
  3.     outs.append(self.out(r_out[:, time_step, :]))

 

最后的返回值将outs[ ] 是一个list 将其变为Tensor的形式,将里面的东西压在一起

return torch.stack(outs, dim=1), h_state

 

 

在训练阶段

step 是训练的步数

 

start, end = step * np.pi, (step + 1) * np.pi

截取一小段距离

 

  1. steps = np.linspace(start, end, TIME_STEP, dtype=np.float32,endpoint=False# float32 for converting torch FloatTensor
  2. x_np = np.sin(steps)
  3. y_np = np.cos(steps)

在每段距离上撒点  生成训练sin曲线 x_np   预测曲线cos曲线  y_np

 

  1. x = torch.from_numpy(
  2.     x_np[np.newaxis, :, np.newaxis])  # shape (batch, time_step, input_size)  增加了2个维度 batch 和 input_size 为1
  3. y = torch.from_numpy(y_np[np.newaxis, :, np.newaxis])

增加两个维度  变为pytorch接收的维度

 

  1. # !! next step is important !!
  2. h_state = h_state.data  # repack the hidden state, break the connection from last iteration

这步非常重要

将每次训练的h_state结果 变为h_state.data 形式赋值给h_state

以下是完整的代码结果

  1. import torch
  2. from torch import nn
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. # torch.manual_seed(1)    # reproducible
  6. # Hyper Parameters
  7. TIME_STEP = 10      # rnn time step
  8. INPUT_SIZE = 1      # rnn input size
  9. LR = 0.02           # learning rate
  10. # show data
  11. steps = np.linspace(0, np.pi*2, 100, dtype=np.float32)  # float32 for converting torch FloatTensor
  12. x_np = np.sin(steps)
  13. y_np = np.cos(steps)
  14. plt.plot(steps, y_np, 'r-', label='target (cos)')
  15. plt.plot(steps, x_np, 'b-', label='input (sin)')
  16. plt.legend(loc='best')
  17. plt.show()
  18. class RNN(nn.Module):
  19.     def __init__(self):
  20.         super(RNN, self).__init__()
  21.         self.rnn = nn.RNN(
  22.             input_size=INPUT_SIZE,
  23.             hidden_size=32,     # rnn hidden unit
  24.             num_layers=1,       # number of rnn layer
  25.             batch_first=True,   # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)
  26.         )
  27.         self.out = nn.Linear(32, 1)
  28.     def forward(self, x, h_state):
  29.         # x (batch, time_step, input_size)
  30.         # h_state (n_layers, batch, hidden_size)
  31.         # r_out (batch, time_step, hidden_size)
  32.         r_out, h_state = self.rnn(x, h_state)
  33.         outs = []    # save all predictions
  34.         for time_step in range(r_out.size(1)):    # calculate output for each time step
  35.             outs.append(self.out(r_out[:, time_step, :]))
  36.         return torch.stack(outs, dim=1), h_state
  37.         # instead, for simplicity, you can replace above codes by follows
  38.         # r_out = r_out.view(-1, 32)
  39.         # outs = self.out(r_out)
  40.         # outs = outs.view(-1, TIME_STEP, 1)
  41.         # return outs, h_state
  42.        
  43.         # or even simpler, since nn.Linear can accept inputs of any dimension
  44.         # and returns outputs with same dimension except for the last
  45.         # outs = self.out(r_out)
  46.         # return outs
  47. rnn = RNN()
  48. print(rnn)
  49. optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)   # optimize all cnn parameters
  50. loss_func = nn.MSELoss()
  51. h_state = None      # for initial hidden state
  52. plt.figure(1, figsize=(12, 5))
  53. plt.ion()           # continuously plot
  54. for step in range(100):
  55.     start, end = step * np.pi, (step+1)*np.pi   # time range  截取一小段的距离
  56.     # use sin predicts cos
  57.     steps = np.linspace(start, end, TIME_STEP, dtype=np.float32, endpoint=False# float32 for converting torch FloatTensor
  58.     x_np = np.sin(steps)
  59.     y_np = np.cos(steps)
  60.     x = torch.from_numpy(x_np[np.newaxis, :, np.newaxis])    # shape (batch, time_step, input_size)  增加了2个维度 batch 和 input_size 为1
  61.     y = torch.from_numpy(y_np[np.newaxis, :, np.newaxis])
  62.     prediction, h_state = rnn(x, h_state)   # rnn output
  63.     # !! next step is important !!
  64.     h_state = h_state.data        # repack the hidden state, break the connection from last iteration
  65.     loss = loss_func(prediction, y)         # calculate loss
  66.     optimizer.zero_grad()                   # clear gradients for this training step
  67.     loss.backward()                         # backpropagation, compute gradients
  68.     optimizer.step()                        # apply gradients
  69.     # plotting
  70.     plt.plot(steps, y_np.flatten(), 'r-')
  71.     plt.plot(steps, prediction.data.numpy().flatten(), 'b-')
  72.     plt.draw(); plt.pause(0.05)
  73. plt.ioff()
  74. plt.show()

运行结果:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/897239
推荐阅读
相关标签
  

闽ICP备14008679号