PyTorch – 递归神经网络
递归神经网络是一种面向深度学习的算法,它采用的是顺序方法。在神经网络中,我们总是假设每个输入和输出都独立于所有其他层。这些类型的神经网络被称为递归,因为它们以连续的方式进行数学计算,完成一个又一个任务。
下图说明了递归神经网络的完整方法和工作原理。
在上图中,c1、c2、c3和x1被认为是输入,其中包括一些隐藏的输入值,即h1、h2和h3,提供o1的各自输出。现在我们将集中精力实现PyTorch,在递归神经网络的帮助下创建一个正弦波。
在训练过程中,我们将遵循一次一个数据点的训练方法来训练我们的模型。输入序列x由20个数据点组成,而目标序列被认为与输入序列相同。
第1步
使用以下代码导入实现递归神经网络的必要软件包 −
import torch
from torch.autograd import Variable
import numpy as np
import pylab as pl
import torch.nn.init as init
第2步
我们将设置模型的超参数,输入层的大小设置为7。将有6个上下文神经元和1个输入神经元用于创建目标序列。
dtype = torch.FloatTensor
input_size, hidden_size, output_size = 7, 6, 1
epochs = 300
seq_length = 20
lr = 0.1
data_time_steps = np.linspace(2, 10, seq_length + 1)
data = np.sin(data_time_steps)
data.resize((seq_length + 1, 1))
x = Variable(torch.Tensor(data[:-1]).type(dtype), requires_grad=False)
y = Variable(torch.Tensor(data[1:]).type(dtype), requires_grad=False)
我们将生成训练数据,其中x是输入数据序列,y是所需的目标序列。
第3步
递归神经网络的权重是使用正态分布的零平均值来初始化的。W1表示接受输入变量,W2表示产生的输出,如下所示。
w1 = torch.FloatTensor(input_size,
hidden_size).type(dtype)
init.normal(w1, 0.0, 0.4)
w1 = Variable(w1, requires_grad = True)
w2 = torch.FloatTensor(hidden_size, output_size).type(dtype)
init.normal(w2, 0.0, 0.3)
w2 = Variable(w2, requires_grad = True)
第4步
现在,为前馈创建一个函数是很重要的,它可以独特地定义神经网络。
def forward(input, context_state, w1, w2):
xh = torch.cat((input, context_state), 1)
context_state = torch.tanh(xh.mm(w1))
out = context_state.mm(w2)
return (out, context_state)
第5步
下一步是开始训练循环神经网络的正弦波实现程序。外循环对每个循环进行迭代,内循环对序列的元素进行迭代。在这里,我们还将计算平均平方误差(MSE),这有助于连续变量的预测。
for i in range(epochs):
total_loss = 0
context_state = Variable(torch.zeros((1, hidden_size)).type(dtype), requires_grad = True)
for j in range(x.size(0)):
input = x[j:(j+1)]
target = y[j:(j+1)]
(pred, context_state) = forward(input, context_state, w1, w2)
loss = (pred - target).pow(2).sum()/2
total_loss += loss
loss.backward()
w1.data -= lr * w1.grad.data
w2.data -= lr * w2.grad.data
w1.grad.data.zero_()
w2.grad.data.zero_()
context_state = Variable(context_state.data)
if i % 10 == 0:
print("Epoch: {} loss {}".format(i, total_loss.data[0]))
context_state = Variable(torch.zeros((1, hidden_size)).type(dtype), requires_grad = False)
predictions = []
for i in range(x.size(0)):
input = x[i:i+1]
(pred, context_state) = forward(input, context_state, w1, w2)
context_state = context_state
predictions.append(pred.data.numpy().ravel()[0])
第6步
现在,是时候按照需要的方式来绘制正弦波了。
pl.scatter(data_time_steps[:-1], x.data.numpy(), s = 90, label = "Actual")
pl.scatter(data_time_steps[1:], predictions, label = "Predicted")
pl.legend()
pl.show()
输出
上述过程的输出如下 –