from data_provider.data_factory import data_provider #数据提供模块
from data_provider.m4 import M4Meta #M4数据集的元数据
from exp.exp_basic import Exp_Basic #实验基类
from utils.tools import EarlyStopping, adjust_learning_rate, visual #工具函数
from utils.losses import mape_loss, mase_loss, smape_loss #自定义损失函数
from utils.m4_summary import M4Summary #M4数据集的汇总统计
import torch
import torch.nn as nn
from torch import optim
import os
import time
import warnings
import numpy as np
import pandas
warnings.filterwarnings('ignore') #忽略警告信息
#短期预测类
class Exp_Short_Term_Forecast(Exp_Basic):
#构造函数
def __init__(self, args):
super(Exp_Short_Term_Forecast, self).__init__(args)
#创建模型
def _build_model(self):
if self.args.data == 'm4':
self.args.pred_len = M4Meta.horizons_map[self.args.seasonal_patterns] # Up to M4 config
self.args.seq_len = 2 * self.args.pred_len # input_len = 2*pred_len
self.args.label_len = self.args.pred_len
self.args.frequency_map = M4Meta.frequency_map[self.args.seasonal_patterns]
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函数获取数据集合和数据加载器
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, loss_name='MSE'):
if loss_name == 'MSE':
return nn.MSELoss()
elif loss_name == 'MAPE':
return mape_loss()
elif loss_name == 'MASE':
return mase_loss()
elif loss_name == 'SMAPE':
return smape_loss()
#训练方法
def train(self, setting):
#获取数据
train_data, train_loader = self._get_data(flag='train')
vali_data, vali_loader = self._get_data(flag='val')
#创建模型存储文件
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(self.args.loss)
mse = nn.MSELoss()
#根据训练次数循环
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_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)
outputs = self.model(batch_x, None, dec_inp, None)
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)
batch_y_mark = batch_y_mark[:, -self.args.pred_len:, f_dim:].to(self.device)
#通过训练值、真实值计算损失函数
loss_value = criterion(batch_x, self.args.frequency_map, outputs, batch_y, batch_y_mark)
loss_sharpness = mse((outputs[:, 1:, :] - outputs[:, :-1, :]), (batch_y[:, 1:, :] - batch_y[:, :-1, :]))
loss = loss_value # + loss_sharpness * 1e-5
#将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()
#计算当前梯度,反向传播
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(train_loader, vali_loader, criterion)
test_loss = vali_loss
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
#验证方法,通过计算模型验证的误差来评估模型性能,即向前传播时不根据学习率计算梯度
def vali(self, train_loader, vali_loader, criterion):
x, _ = train_loader.dataset.last_insample_window()
y = vali_loader.dataset.timeseries
x = torch.tensor(x, dtype=torch.float32).to(self.device)
x = x.unsqueeze(-1)
#设置评估模式
self.model.eval()
#开启上下文管理器,关闭梯度计算,节省内存和计算资源
with torch.no_grad():
# decoder input
#获取输入x的形状
B, _, C = x.shape
#初始化一个全零的解码器输入
dec_inp = torch.zeros((B, self.args.pred_len, C)).float().to(self.device)
#将解码器的输入拼接到x上
dec_inp = torch.cat([x[:, -self.args.label_len:, :], dec_inp], dim=1).float()
# encoder - decoder
#初始化输出张量
outputs = torch.zeros((B, self.args.pred_len, C)).float() # .to(self.device)
#创建一个指示每个样本批次开始的索引列表
id_list = np.arange(0, B, 500) # validation set size
id_list = np.append(id_list, B)
#为每个批次的数据执行模型预测
for i in range(len(id_list) - 1):
outputs[id_list[i]:id_list[i + 1], :, :] = self.model(x[id_list[i]:id_list[i + 1]], None,
dec_inp[id_list[i]:id_list[i + 1]],
None).detach().cpu()
#根据特征选择输出结果
f_dim = -1 if self.args.features == 'MS' else 0
outputs = outputs[:, -self.args.pred_len:, f_dim:]
pred = outputs
#将输出从gpu转移到cpu,并转换成numpy数组
true = torch.from_numpy(np.array(y))
#创建一个指定shape全部为1的张量
batch_y_mark = torch.ones(true.shape)
#计算损失函数
loss = criterion(x.detach().cpu()[:, :, 0], self.args.frequency_map, pred[:, :, 0], true, batch_y_mark)
self.model.train()
return loss
#定义测试函数,setting 路径,test标志是否加载模型,0表示不加载
def test(self, setting, test=0):
_, train_loader = self._get_data(flag='train')
_, test_loader = self._get_data(flag='test')
x, _ = train_loader.dataset.last_insample_window()
y = test_loader.dataset.timeseries
x = torch.tensor(x, dtype=torch.float32).to(self.device)
x = x.unsqueeze(-1)
#若是test参数为真,打印loading model
if test:
print('loading model')
self.model.load_state_dict(torch.load(os.path.join('./checkpoints/' + setting, 'checkpoint.pth')))
#检测是否已经创建文件路径,未存在路径则创建该文件
folder_path = './test_results/' + setting + '/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
#设置评估模型
self.model.eval()
#开启上下文管理器,关闭梯度计算,节省内存和计算资源
with torch.no_grad():
#获取输入x的形状
B, _, C = x.shape
#初始化一个全零的解码器输入
dec_inp = torch.zeros((B, self.args.pred_len, C)).float().to(self.device)
#将解码器的输入拼接到x上
dec_inp = torch.cat([x[:, -self.args.label_len:, :], dec_inp], dim=1).float()
# encoder - decoder
#初始化输出张量
outputs = torch.zeros((B, self.args.pred_len, C)).float().to(self.device)
#创建一个指示每个样本批次开始的索引列表
id_list = np.arange(0, B, 1)
id_list = np.append(id_list, B)
#为每个批次的数据执行模型预测
for i in range(len(id_list) - 1):
outputs[id_list[i]:id_list[i + 1], :, :] = self.model(x[id_list[i]:id_list[i + 1]], None,
dec_inp[id_list[i]:id_list[i + 1]], None)
if id_list[i] % 1000 == 0:
print(id_list[i])
#根据特征选择输出结果
f_dim = -1 if self.args.features == 'MS' else 0
outputs = outputs[:, -self.args.pred_len:, f_dim:]
#将输出从gpu转移到cpu,并转换成numpy数组
outputs = outputs.detach().cpu().numpy()
#可视化预测值和实际值
preds = outputs
trues = y
x = x.detach().cpu().numpy()
#对结果进行可视化
for i in range(0, preds.shape[0], preds.shape[0] // 10):
gt = np.concatenate((x[i, :, 0], trues[i]), axis=0)
pd = np.concatenate((x[i, :, 0], preds[i, :, 0]), axis=0)
visual(gt, pd, os.path.join(folder_path, str(i) + '.pdf'))
print('test shape:', preds.shape)
# result save
#结果存储
folder_path = './m4_results/' + self.args.model + '/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
#将预测结果保存到cvs中
forecasts_df = pandas.DataFrame(preds[:, :, 0], columns=[f'V{i + 1}' for i in range(self.args.pred_len)])
forecasts_df.index = test_loader.dataset.ids[:preds.shape[0]]
forecasts_df.index.name = 'id'
forecasts_df.set_index(forecasts_df.columns[0], inplace=True)
forecasts_df.to_csv(folder_path + self.args.seasonal_patterns + '_forecast.csv')
#打印当前使用的模型名称
print(self.args.model)
#检查路径是否包含所有所需的预测文件
file_path = './m4_results/' + self.args.model + '/'
if 'Weekly_forecast.csv' in os.listdir(file_path)
and 'Monthly_forecast.csv' in os.listdir(file_path)
and 'Yearly_forecast.csv' in os.listdir(file_path)
and 'Daily_forecast.csv' in os.listdir(file_path)
and 'Hourly_forecast.csv' in os.listdir(file_path)
and 'Quarterly_forecast.csv' in os.listdir(file_path):
#如果各种文件都存在,执行摘要计算
m4_summary = M4Summary(file_path, self.args.root_path)
# m4_forecast.set_index(m4_winner_forecast.columns[0], inplace=True)
smape_results, owa_results, mape, mase = m4_summary.evaluate()
#打印各种评估指标
print('smape:', smape_results)
print('mape:', mape)
print('mase:', mase)
print('owa:', owa_results)
else:
print('After all 6 tasks are finished, you can calculate the averaged index')
return