trandfoemer时间序列预测代码

import torch
import torch.nn as nn
import numpy as np
import time
import math
from matplotlib import pyplot
import matplotlib.pyplot as plt;
import pandas as pd
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
import tensorflow as tf
from math import sqrt
from sklearn import metrics

torch.manual_seed(0)
np.random.seed(0)

import warnings
warnings.filterwarnings('ignore')


class PositionalEncoding(nn.Module):

    def __init__(self, d_model, max_len=5000):
        super(PositionalEncoding, self).__init__()       
        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        pe = pe.unsqueeze(0).transpose(0, 1)
        #pe.requires_grad = False
        self.register_buffer('pe', pe)

    def forward(self, x):
        return x + self.pe[:x.size(0), :]
          

#构建transformer模型
class TransAm(nn.Module):
    def __init__(self,feature_size=250,num_layers=1,dropout=0.1):
        super(TransAm, self).__init__()
        self.model_type = 'Transformer'
        
        self.src_mask = None
        self.pos_encoder = PositionalEncoding(feature_size)
        self.encoder_layer = nn.TransformerEncoderLayer(d_model=feature_size, nhead=10, dropout=dropout)
        self.transformer_encoder = nn.TransformerEncoder(self.encoder_layer, num_layers=num_layers)        
        self.decoder = nn.Linear(feature_size,1)
        self.init_weights()

    def init_weights(self):
        initrange = 0.1    
        self.decoder.bias.data.zero_()
        self.decoder.weight.data.uniform_(-initrange, initrange)

    def forward(self,src):
        if self.src_mask is None or self.src_mask.size(0) != len(src):
            device = src.device
            mask = self._generate_square_subsequent_mask(len(src)).to(device)
            self.src_mask = mask

        src = self.pos_encoder(src)
        output = self.transformer_encoder(src,self.src_mask)#, self.src_mask)
        output = self.decoder(output)
        return output

    def _generate_square_subsequent_mask(self, sz):
        mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
        mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))
        return mask


def get_batch(source, i,batch_size):
    seq_len = min(batch_size, len(source) - 1 - i)
    data = source[i:i+seq_len]    
    input = torch.stack(torch.stack([item[0] for item in data]).chunk(input_window,1)) # 1 is feature size
    target = torch.stack(torch.stack([item[1] for item in data]).chunk(input_window,1))
    return input, target

#训练模型
def train(train_data):
    model.train() # Turn on the train mode \o/
    total_loss = 0.
    start_time = time.time()

    for batch, i in enumerate(range(0, len(train_data) - 1, batch_size)):
        data, targets = get_batch(train_data, i,batch_size)
        optimizer.zero_grad()
        output = model(data)
        loss = criterion(output, targets)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 0.7)
        optimizer.step()

        total_loss += loss.item()
        log_interval = int(len(train_data) / batch_size / 5)
        if batch % log_interval == 0 and batch > 0:
            cur_loss = total_loss / log_interval
            elapsed = time.time() - start_time
            print('| epoch {:3d} | {:5d}/{:5d} batches | '
                  'lr {:02.6f} | {:5.2f} ms | '
                  'loss {:5.5f} | ppl {:8.2f}'.format(
                    epoch, batch, len(train_data) // batch_size, scheduler.get_lr()[0],
                    elapsed * 1000 / log_interval,
                    cur_loss, math.exp(cur_loss)))
            total_loss = 0
            start_time = time.time()

#预测
def plot_and_loss(eval_model, data_source,epoch):
    eval_model.eval() 
    total_loss = 0.
    test_result = torch.Tensor(0)    
    truth = torch.Tensor(0)
    
    with torch.no_grad():
        for i in range(0, len(data_source) - 1):
            data, target = get_batch(data_source, i,1)
            output = eval_model(data)            
            total_loss += criterion(output, target).item()
            test_result = torch.cat((test_result, output[-1].view(-1).cpu()), 0)
            truth = torch.cat((truth, target[-1].view(-1).cpu()), 0)
            
    #test_result = test_result.cpu().numpy() -> no need to detach stuff.. 
    len(test_result)

    pyplot.plot(test_result,color="red")
    pyplot.plot(truth[:500],color="blue")
    # pyplot.plot(test_result-truth,color="green")
    pyplot.grid(True, which='both')
    pyplot.axhline(y=0, color='k')
    # pyplot.savefig('graph/transformer-epoch%d.png'%epoch)
    plt.show()
    # pyplot.close()
    real=truth.tolist()
    pre=test_result.tolist()
    


    
    return total_loss / i,real,pre


# predict the next n steps based on the input data 
# def predict_future(eval_model, data_source,steps):
#     eval_model.eval() 
#     total_loss = 0.
#     test_result = torch.Tensor(0)    
#     truth = torch.Tensor(0)
#     data, _ = get_batch(data_source, 0,1)

#     with torch.no_grad():
#         for i in range(0, steps):            
#             output = eval_model(data[-input_window:])                        
#             data = torch.cat((data, output[-1:]))
            
#     data = data.cpu().view(-1)
#     # print(data)
#     # I used this plot to visualize if the model pics up any long therm struccture within the data. 
#     pyplot.plot(data,color="red")       
#     pyplot.plot(data[:input_window],color="blue")    
#     pyplot.grid(True, which='both')
#     pyplot.axhline(y=0, color='k')
#     # pyplot.savefig('graph/transformer-future%d.png'%steps)
#     # pyplot.close()
#     plt.show()
        

def evaluate(eval_model, data_source):
    eval_model.eval() # Turn on the evaluation mode
    total_loss = 0.
    eval_batch_size = 1000
    with torch.no_grad():
        for i in range(0, len(data_source) - 1, eval_batch_size):
            data, targets = get_batch(data_source, i,eval_batch_size)
            output = eval_model(data)            
            total_loss += len(data[0])* criterion(output, targets).cpu().item()
    return total_loss / len(data_source)


input_window = 30 # number of input steps
output_window = 1 # number of prediction steps, in this model its fixed to one
batch_size = 10 
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# if window is 100 and prediction step is 1
# in -> [0..99]
# target -> [1..100]
def create_inout_sequences(input_data, tw):
    inout_seq = []
    L = len(input_data)
    for i in range(L-tw):
        train_seq = input_data[i:i+tw]
        train_label = input_data[i+output_window:i+tw+output_window]
        inout_seq.append((train_seq ,train_label))
    return torch.FloatTensor(inout_seq)


#构建数据
def get_data():
    # construct a littel toy dataset
    # time = np.arange(0, 200, 0.1)
    # print("输入数据time:")
    # print(time.shape)
    # amplitude = np.sin(time) + np.sin(time*0.05) +np.sin(time*0.12) *np.random.normal(-0.2, 0.2, len(time))
    # print("输入数据amplitude1:")
    # print(amplitude.shape)
    # print(amplitude)

    #loading data from a file
    from pandas import read_csv
    dataset= pd.read_excel(r"D:\alldata\pythonfiles\九寨沟\数据\九寨沟数据.xlsx")
    dataset.drop('日期',axis=1, inplace=True)
    amplitude=dataset.values
    print(amplitude)

    # looks like normalizing input values curtial for the model
    from sklearn.preprocessing import MinMaxScaler
    scaler = MinMaxScaler(feature_range=(-1, 1)) 
    #amplitude = scaler.fit_transform(series.to_numpy().reshape(-1, 1)).reshape(-1)
    amplitude = scaler.fit_transform(amplitude.reshape(-1, 1)).reshape(-1)
    print("输入数据amplitude2:")
    print(amplitude.shape)
    
    
    # sampels = 2600
    sampels = 1246
    train_data = amplitude[:sampels]
    test_data = amplitude[sampels:]
    test_data2 = amplitude[sampels:]
    print("输入数据train_data1:")
    print(train_data.shape)
    print("输入数据test_data1:")
    print(test_data.shape)

    # convert our train data into a pytorch train tensor
    #train_tensor = torch.FloatTensor(train_data).view(-1)
    # todo: add comment.. 
    train_sequence = create_inout_sequences(train_data,input_window)
    train_sequence = train_sequence[:-output_window] #todo: fix hack? -> din't think this through, looks like the last n sequences are to short, so I just remove them. Hackety Hack.. 

    #test_data = torch.FloatTensor(test_data).view(-1) 
    test_data = create_inout_sequences(test_data,input_window)
    test_data = test_data[:-output_window] #todo: fix hack?
    print("输入数据train_sequence:")
    print(train_sequence.shape)
    print("输入数据test_data2:")
    print(test_data.shape)

    return train_sequence.to(device),test_data.to(device),test_data2,scaler



model = TransAm().to(device)

criterion = nn.MSELoss()
lr = 0.005
#optimizer = torch.optim.SGD(model.parameters(), lr=lr)
optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)

train_data, val_data,val_data2,scaler= get_data()
best_val_loss = float("inf")
epochs = 100 # The number of epochs
best_model = None

for epoch in range(1, epochs + 1):
    epoch_start_time = time.time()
    train(train_data)
    #val_loss,pre,real = plot_and_loss(model, val_data,epoch)
    

    if(epoch % 100 is 0):
        val_loss,pre,real = plot_and_loss(model, val_data,epoch)
        pre=np.array(pre).reshape(1,len(pre))
        pre= scaler.inverse_transform(pre).flatten()
        print(pre)
        real=np.array(real).reshape(1,len(real))
        real= scaler.inverse_transform(real).flatten()
        print(real)
        plt.plot(real)
        plt.plot(pre)
        plt.ylabel('finalpre')
        plt.xlabel('y')
        plt.legend(['finalpre','y'])
        plt.show()

        MSE = mean_squared_error(real,pre)
        RMSE = math.sqrt(MSE)
        MAE=mean_absolute_error(real, pre)
        MAPE = metrics.mean_absolute_percentage_error(real,pre)
        print("rmse :",RMSE)
        print("mae :", MAE)
        print("mape :", MAPE)

        # predict_future(model, val_data,200)
    else:
        val_loss = evaluate(model, val_data)

    print('-' * 89)
    print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.5f} | valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),
                                     val_loss, math.exp(val_loss)))
    print('-' * 89)

    if val_loss < best_val_loss:
       best_val_loss = val_loss
       best_model = model

    scheduler.step()

你可能感兴趣的:(python,transformer)