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')
#定义类,,并继承基类Exp_Basic
class Exp_Imputation(Exp_Basic):
#结构函数-类的初始化
def __init__(self, args):
super(Exp_Imputation, self).__init__(args)
#创建模型
def _build_model(self):
model = self.model_dict[self.args.model].Model(self.args).float()
#若是使用多gpu且gpu可用,使用DataParallel打包model
if self.args.use_multi_gpu and self.args.use_gpu:
model = nn.DataParallel(model, device_ids=self.args.device_ids)
return model
#获取数据集的方法
def _get_data(self, flag):
data_set, data_loader = data_provider(self.args, flag)
return data_set, data_loader
#选择优化器
def _select_optimizer(self):
model_optim = optim.Adam(self.model.parameters(), lr=self.args.learning_rate)
return model_optim
#选择损失函数的方法
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_x_mark = batch_x_mark.float().to(self.device)
# random mask
B, T, N = batch_x.shape
"""
B = batch size
T = seq len
N = number of features
"""
mask = torch.rand((B, T, N)).to(self.device)
mask[mask <= self.args.mask_rate] = 0 # masked
mask[mask > self.args.mask_rate] = 1 # remained
inp = batch_x.masked_fill(mask == 0, 0)
outputs = self.model(inp, batch_x_mark, None, None, mask)
#根据特征选择输出结果
f_dim = -1 if self.args.features == 'MS' else 0
outputs = outputs[:, :, f_dim:]
pred = outputs.detach().cpu()
true = batch_x.detach().cpu()
mask = mask.detach().cpu()
#通过预测值、真实值计算损失函数
loss = criterion(pred[mask == 0], true[mask == 0])
#将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()
#根据训练次数循环
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_x_mark = batch_x_mark.float().to(self.device)
# random mask
#创建随机掩码用于弥补缺失数据
B, T, N = batch_x.shape
mask = torch.rand((B, T, N)).to(self.device)
mask[mask <= self.args.mask_rate] = 0 # masked #被掩盖
mask[mask > self.args.mask_rate] = 1 # remained #保留
inp = batch_x.masked_fill(mask == 0, 0)
#使用模型进行预测
outputs = self.model(inp, batch_x_mark, None, None, mask)
#根据特征选择输出维度
f_dim = -1 if self.args.features == 'MS' else 0
outputs = outputs[:, :, f_dim:]
#计算损失函数,并添加到train_loss列表
loss = criterion(outputs[mask == 0], batch_x[mask == 0])
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))
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
#定义测试方法
def test(self, setting, test=0):
#获取测试数据
test_data, test_loader = self._get_data(flag='test')
#如果测试为真,加载模型状态
if test:
print('loading model')
self.model.load_state_dict(torch.load(os.path.join('./checkpoints/' + setting, 'checkpoint.pth')))
preds = []
trues = []
masks = []
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_x_mark = batch_x_mark.float().to(self.device)
# random mask
#创建随机掩码用于弥补缺失数据
B, T, N = batch_x.shape
mask = torch.rand((B, T, N)).to(self.device)
mask[mask <= self.args.mask_rate] = 0 # masked #被掩盖
mask[mask > self.args.mask_rate] = 1 # remained #保留
inp = batch_x.masked_fill(mask == 0, 0)
# imputation
#使用模型进行预测
outputs = self.model(inp, batch_x_mark, None, None, mask)
# eval
#根据特征选择输出维度
f_dim = -1 if self.args.features == 'MS' else 0
outputs = outputs[:, :, f_dim:]
outputs = outputs.detach().cpu().numpy()
pred = outputs
true = batch_x.detach().cpu().numpy()
#讲这些预测、真实、掩码、标签添加到之前初始化的列表中
preds.append(pred)
trues.append(true)
masks.append(mask.detach().cpu())
#每20批次,执行以下代码块
if i % 20 == 0:
filled = true[0, :, -1].copy()
filled = filled * mask[0, :, -1].detach().cpu().numpy() +
pred[0, :, -1] * (1 - mask[0, :, -1].detach().cpu().numpy())
#将true数据和pred的最后一维拼接起来,存储
visual(true[0, :, -1], filled, os.path.join(folder_path, str(i) + '.pdf'))
#将preds、trues、masks分别拼接起来
preds = np.concatenate(preds, 0)
trues = np.concatenate(trues, 0)
masks = np.concatenate(masks, 0)
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[masks == 0], trues[masks == 0])
print('mse:{}, mae:{}'.format(mse, mae))
f = open("result_imputation.txt", 'a')
f.write(setting + "
")
f.write('mse:{}, mae:{}'.format(mse, mae))
f.write('
')
f.write('
')
f.close()
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