深度学习与神经网络 之 时间序列预测实战(RNN)

预测一个正弦曲线的下一段的波形

 

深度学习与神经网络 之 时间序列预测实战(RNN)_第1张图片

例如输入[0,49]的值,要求预测[1,50]的值

 

我们这是数字数据,就不需要embedding了,所以word_vec也就是1

batch也就是1,没有多个

word_num即sequence设置为50,就是1次喂50个点的数据

所以,输入数据的shape是[1,50,1],这里采用的是第②种表达方式

深度学习与神经网络 之 时间序列预测实战(RNN)_第2张图片

start是开始的点

 

 

 

import  numpy as np
import  torch
import  torch.nn as nn
import  torch.optim as optim
from    matplotlib import pyplot as plt


num_time_steps = 50
input_size = 1
hidden_size = 16
output_size = 1
lr=0.01



class Net(nn.Module):

    def __init__(self, ):
        super(Net, self).__init__()

        self.rnn = nn.RNN(
            input_size=input_size,
            hidden_size=hidden_size,
            num_layers=1,
            batch_first=True,
        )
        for p in self.rnn.parameters():
          nn.init.normal_(p, mean=0.0, std=0.001)

        self.linear = nn.Linear(hidden_size, output_size)

    def forward(self, x, hidden_prev):  #hidden_prev是h0

       out, hidden_prev = self.rnn(x, hidden_prev)
       # [b, seq, h]
       out = out.view(-1, hidden_size)  #把out打平
       out = self.linear(out)
       out = out.unsqueeze(dim=0)  #插入一个新的维度,因为后面要和y做MSE比较
       return out, hidden_prev




model = Net()
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr)

hidden_prev = torch.zeros(1, 1, hidden_size)  #h0

for iter in range(6000):
    start = np.random.randint(3, size=1)[0]
    time_steps = np.linspace(start, start + 10, num_time_steps)
    data = np.sin(time_steps)
    data = data.reshape(num_time_steps, 1)
    x = torch.tensor(data[:-1]).float().view(1, num_time_steps - 1, 1)
    y = torch.tensor(data[1:]).float().view(1, num_time_steps - 1, 1)

    output, hidden_prev = model(x, hidden_prev)
    hidden_prev = hidden_prev.detach()

    #将x和h0送进去得到output,output又和y进行MSE误差更新
    loss = criterion(output, y)
    model.zero_grad()
    loss.backward()
    optimizer.step()

    if iter % 100 == 0:
        print("Iteration: {} loss {}".format(iter, loss.item()))

start = np.random.randint(3, size=1)[0]  #start在0-3之间随机地初始化,只会取0,1,2
time_steps = np.linspace(start, start + 10, num_time_steps)#将[start,start+10]的波形作为一个输入,在其中采样50个点
data = np.sin(time_steps)
data = data.reshape(num_time_steps, 1) #reshape成50行1列
x = torch.tensor(data[:-1]).float().view(1, num_time_steps - 1, 1)
y = torch.tensor(data[1:]).float().view(1, num_time_steps - 1, 1)
#首先x和y都是sin函数的函数值,y是相当于x的x轴整体向右平移了一个得到的



predictions = []
input = x[:, 0, :]
#由input得到predict点,在作为下一个的input,......
for _ in range(x.shape[1]):
  input = input.view(1, 1, 1)
  (pred, hidden_prev) = model(input, hidden_prev)
  input = pred
  predictions.append(pred.detach().numpy().ravel()[0])

x = x.data.numpy().ravel()
y = y.data.numpy()
plt.scatter(time_steps[:-1], x.ravel(), s=90)
plt.plot(time_steps[:-1], x.ravel())

plt.scatter(time_steps[1:], predictions)
plt.show()

深度学习与神经网络 之 时间序列预测实战(RNN)_第3张图片

深度学习与神经网络 之 时间序列预测实战(RNN)_第4张图片

 

 

 

 

 

你可能感兴趣的:(时间序列,RNN)