from data_provider.data_factory import data_provider
from exp.exp_basic import Exp_Basic
from utils.tools import EarlyStopping, adjust_learning_rate, visual
from utils.metrics import metric
import torch
import torch.nn as nn
from torch import optim
import os
import time
import warnings
import numpy as np
warnings.filterwarnings('ignore')
#长期预测类
class Exp_Long_Term_Forecast(Exp_Basic):
#构造函数
def __init__(self, args):
super(Exp_Long_Term_Forecast, self).__init__(args)
#创建模型
def _build_model(self):
model = self.model_dict[self.args.model].Model(self.args).float()
#多gpu且gpu可用
if self.args.use_multi_gpu and self.args.use_gpu:
model = nn.DataParallel(model, device_ids=self.args.device_ids)
return model
#从data_provider函数获取数据集合和数据加载器,并提供标志(train,val,test)
def _get_data(self, flag):
data_set, data_loader = data_provider(self.args, flag)
return data_set, data_loader
#选择优化器,该函数使用adam优化器,从传入的参数self 添加self.args.learning_rate学习率
def _select_optimizer(self):
model_optim = optim.Adam(self.model.parameters(), lr=self.args.learning_rate)
return model_optim
#选择损失函数,MSELoss(均方误差损失)
def _select_criterion(self):
criterion = nn.MSELoss()
return criterion
#验证方法,通过计算模型验证的误差来评估模型性能,即向前传播时不根据学习率计算梯度
def vali(self, vali_data, vali_loader, criterion):
total_loss = []
#设置评估模式
self.model.eval()
with torch.no_grad():
for i, (batch_x, batch_y, batch_x_mark, batch_y_mark) in enumerate(vali_loader):
#将转化为浮点型的数据加载到cpu或gpu
batch_x = batch_x.float().to(self.device)
batch_y = batch_y.float()
#将转化为浮点型的数据加载到cpu或gpu
batch_x_mark = batch_x_mark.float().to(self.device)
batch_y_mark = batch_y_mark.float().to(self.device)
# decoder input
#输出一个形状与输入一致的全零张量,并转化为浮点型格式
dec_inp = torch.zeros_like(batch_y[:, -self.args.pred_len:, :]).float()
#在给定维度对输入的张量序列进行连续操作,并加载到cpu或者gpu
dec_inp = torch.cat([batch_y[:, :self.args.label_len, :], dec_inp], dim=1).float().to(self.device)
# encoder - decoder
if self.args.use_amp:
with torch.cuda.amp.autocast():
if self.args.output_attention:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)[0]
else:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)
else:
if self.args.output_attention:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)[0]
else:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)
#根据配置文档参数self.args.features进行降维
f_dim = -1 if self.args.features == 'MS' else 0
outputs = outputs[:, -self.args.pred_len:, f_dim:]
batch_y = batch_y[:, -self.args.pred_len:, f_dim:].to(self.device)
#返回一个与当前 graph 分离的、不再需要梯度的新张量
pred = outputs.detach().cpu()
true = batch_y.detach().cpu()
#通过预测值、真实值计算损失函数
loss = criterion(pred, true)
#将loss添加total_loss列表
total_loss.append(loss)
#计算total_loss列表均值
total_loss = np.average(total_loss)
#将模型切换成训练模型
self.model.train()
return total_loss
def train(self, setting):
#获取数据
train_data, train_loader = self._get_data(flag='train')
vali_data, vali_loader = self._get_data(flag='val')
test_data, test_loader = self._get_data(flag='test')
#创建模型存储文件
path = os.path.join(self.args.checkpoints, setting)
if not os.path.exists(path):
os.makedirs(path)
#获取时间戳
time_now = time.time()
#训练步长
train_steps = len(train_loader)
#早起停止函数,避免过拟合 patience 容忍升高次数
early_stopping = EarlyStopping(patience=self.args.patience, verbose=True)
#选择优化器
model_optim = self._select_optimizer()
#选择损失函数,这里选择的是MSELoss(均方误差损失)
criterion = self._select_criterion()
if self.args.use_amp:
#自动混合精度GradScaler实例化
scaler = torch.cuda.amp.GradScaler()
#根据训练次数循环
for epoch in range(self.args.train_epochs):
iter_count = 0
train_loss = []
#设置为训练模式
self.model.train()
#训练开始时间
epoch_time = time.time()
#从训练数据集中加载每个样本数据
for i, (batch_x, batch_y, batch_x_mark, batch_y_mark) in enumerate(train_loader):
iter_count += 1
#模型参数梯度值选择为0
model_optim.zero_grad()
#将转化为浮点型的数据加载到cpu或gpu
batch_x = batch_x.float().to(self.device)
batch_y = batch_y.float().to(self.device)
batch_x_mark = batch_x_mark.float().to(self.device)
batch_y_mark = batch_y_mark.float().to(self.device)
# decoder input
#输出一个形状与输入一致的全零张量,并转化为浮点型格式
dec_inp = torch.zeros_like(batch_y[:, -self.args.pred_len:, :]).float()
#在给定维度对输入的张量序列进行连续操作,并加载到cpu或者gpu
dec_inp = torch.cat([batch_y[:, :self.args.label_len, :], dec_inp], dim=1).float().to(self.device)
# encoder - decoder
if self.args.use_amp:
#自动切换精度
with torch.cuda.amp.autocast():
if self.args.output_attention:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)[0]
else:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)
f_dim = -1 if self.args.features == 'MS' else 0
outputs = outputs[:, -self.args.pred_len:, f_dim:]
batch_y = batch_y[:, -self.args.pred_len:, f_dim:].to(self.device)
#通过训练值、真实值计算损失函数
loss = criterion(outputs, batch_y)
#将loss里的高精度值添加在train_loss列表
train_loss.append(loss.item())
else:
if self.args.output_attention:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)[0]
else:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)
#跟据元素设置确定f_dim为-1或者0,多元素进行降维操作
f_dim = -1 if self.args.features == 'MS' else 0
outputs = outputs[:, -self.args.pred_len:, f_dim:]
batch_y = batch_y[:, -self.args.pred_len:, f_dim:].to(self.device)
#通过训练值、真实值计算损失函数
loss = criterion(outputs, batch_y)
#将loss里的高精度值添加在train_loss列表
train_loss.append(loss.item())
if (i + 1) % 100 == 0:
print(" iters: {0}, epoch: {1} | loss: {2:.7f}".format(i + 1, epoch + 1, loss.item()))
speed = (time.time() - time_now) / iter_count
left_time = speed * ((self.args.train_epochs - epoch) * train_steps - i)
print(' speed: {:.4f}s/iter; left time: {:.4f}s'.format(speed, left_time))
iter_count = 0
time_now = time.time()
if self.args.use_amp:
scaler.scale(loss).backward()
scaler.step(model_optim)
scaler.update()
else:
#计算当前梯度,反向传播
loss.backward()
model_optim.step()
#训练所花费时间
print("Epoch: {} cost time: {}".format(epoch + 1, time.time() - epoch_time))
#计算total_loss列表均值
train_loss = np.average(train_loss)
#验证方法,通过计算模型验证的误差来评估模型性能,即向前传播时不根据学习率计算梯度
vali_loss = self.vali(vali_data, vali_loader, criterion)
test_loss = self.vali(test_data, test_loader, criterion)
print("Epoch: {0}, Steps: {1} | Train Loss: {2:.7f} Vali Loss: {3:.7f} Test Loss: {4:.7f}".format(
epoch + 1, train_steps, train_loss, vali_loss, test_loss))
early_stopping(vali_loss, self.model, path)
if early_stopping.early_stop:
print("Early stopping")
break
adjust_learning_rate(model_optim, epoch + 1, self.args)
#加载训练模型
best_model_path = path + '/' + 'checkpoint.pth'
self.model.load_state_dict(torch.load(best_model_path))
return self.model
#定义测试函数,setting 路径,test标志是否加载模型,0表示不加载
def test(self, setting, test=0):
test_data, test_loader = self._get_data(flag='test')
#若是test参数为真,打印loading model
if test:
print('loading model')
self.model.load_state_dict(torch.load(os.path.join('./checkpoints/' + setting, 'checkpoint.pth')))
#清空列表
preds = []
trues = []
folder_path = './test_results/' + setting + '/'
#检测是否已经创建文件路径,未存在路径则创建该文件
if not os.path.exists(folder_path):
os.makedirs(folder_path)
#设置评估模型
self.model.eval()
#开启上下文管理器,关闭梯度计算,节省内存和计算资源
with torch.no_grad():
#迭代测试数据加载器,每次迭代添加数据标签
for i, (batch_x, batch_y, batch_x_mark, batch_y_mark) in enumerate(test_loader):
#将数据的数据类型转化为浮点型,加载到GPU或CPU
batch_x = batch_x.float().to(self.device)
batch_y = batch_y.float().to(self.device)
#将数据的数据类型转化为浮点型,加载到GPU或CPU
batch_x_mark = batch_x_mark.float().to(self.device)
batch_y_mark = batch_y_mark.float().to(self.device)
# decoder input
#输出一个形状与输入一致的全零张量,并转化为浮点型格式
dec_inp = torch.zeros_like(batch_y[:, -self.args.pred_len:, :]).float()
dec_inp = torch.cat([batch_y[:, :self.args.label_len, :], dec_inp], dim=1).float().to(self.device)
# encoder - decoder
#如果启动了自动混合精度,则使用该上下文管理器提升计算速度和减少内存使用
if self.args.use_amp:
with torch.cuda.amp.autocast():
#根据是否输出注意力权重
if self.args.output_attention:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)[0]
else:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)
else:
if self.args.output_attention:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)[0]
else:
outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)
#跟据元素设置确定f_dim为-1或者0,多元素进行降维操作
f_dim = -1 if self.args.features == 'MS' else 0
outputs = outputs[:, -self.args.pred_len:, :]
batch_y = batch_y[:, -self.args.pred_len:, :].to(self.device)
#将输出和真实标签从模型运行的设备转移到cpu,并将数据转换为numpy格式
outputs = outputs.detach().cpu().numpy()
batch_y = batch_y.detach().cpu().numpy()
#如果数据被缩放过并且设置了逆转缩放操作
if test_data.scale and self.args.inverse:
#将模型的输出和批量标签通过数据集的inverse_transform方法逆转缩放,已还原原始尺度
shape = outputs.shape
outputs = test_data.inverse_transform(outputs.squeeze(0)).reshape(shape)
batch_y = test_data.inverse_transform(batch_y.squeeze(0)).reshape(shape)
#根据f_dim选择特定的特征
outputs = outputs[:, :, f_dim:]
batch_y = batch_y[:, :, f_dim:]
#将输出和真实标签分别赋值给pred和true
pred = outputs
true = batch_y
#讲这些预测和真实标签添加到之前初始化的列表中
preds.append(pred)
trues.append(true)
#每20批次,执行以下代码块
if i % 20 == 0:
#将该批次的输入数据移动到cpu,并将数据转换为numpy数组
input = batch_x.detach().cpu().numpy()
if test_data.scale and self.args.inverse:
shape = input.shape
#如果设置了缩放,逆转输入数据的缩放
input = test_data.inverse_transform(input.squeeze(0)).reshape(shape)
gt = np.concatenate((input[0, :, -1], true[0, :, -1]), axis=0)
pd = np.concatenate((input[0, :, -1], pred[0, :, -1]), axis=0)
#将输入数据和真实标签的最后一维拼接起来,形成gt(真实值图),将输入数据和预测结果的最后一维拼接起来,形成pd预测图
visual(gt, pd, os.path.join(folder_path, str(i) + '.pdf'))
preds = np.array(preds)
trues = np.array(trues)
print('test shape:', preds.shape, trues.shape)
preds = preds.reshape(-1, preds.shape[-2], preds.shape[-1])
trues = trues.reshape(-1, trues.shape[-2], trues.shape[-1])
print('test shape:', preds.shape, trues.shape)
# result save
folder_path = './results/' + setting + '/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
#输出各个评估参数
mae, mse, rmse, mape, mspe = metric(preds, trues)
print('mse:{}, mae:{}'.format(mse, mae))
f = open("result_long_term_forecast.txt", 'a')
f.write(setting + "
")
f.write('mse:{}, mae:{}'.format(mse, mae))
f.write('
')
f.write('
')
f.close()
#将测试结果存储在.npy文件
np.save(folder_path + 'metrics.npy', np.array([mae, mse, rmse, mape, mspe]))
np.save(folder_path + 'pred.npy', preds)
np.save(folder_path + 'true.npy', trues)
return