├── __init__.py ├── main ├── __init__.py ├── config.py ├── plot_main.py └── main.py ├── models ├── __init__.py ├── create_data.py └── Model.py ├── README.md ├── LSTM.py ├── .gitignore └── LICENSE /__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /main/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LSTM_Project 2 | LSTM与电力负荷预测 3 | -------------------------------------------------------------------------------- /models/create_data.py: -------------------------------------------------------------------------------- 1 | import torch.utils.data.dataset as Dataset 2 | 3 | 4 | class generate_dataset(Dataset.Dataset): 5 | def __init__(self, Data, label): 6 | super(generate_dataset, self).__init__() 7 | # 初始化,定义数据内容和标签 8 | self.Data = Data 9 | self.label = label 10 | 11 | # 返回数据集大小 12 | def __len__(self): 13 | return len(self.Data) 14 | 15 | # 得到数据内容和标签 16 | def __getitem__(self, item): 17 | data = self.Data[item] 18 | label = self.label[item] 19 | 20 | return data, label -------------------------------------------------------------------------------- /main/config.py: -------------------------------------------------------------------------------- 1 | class Config: 2 | data_path = '../data/' # 数据读取路径 3 | save_log_dir = 'log/' # 存放日志 4 | save_res_dir = 'result/' # 存放预测结果及loss变化 5 | save_param_dir = 'params/' # 存放参数 6 | save_plot_dir = 'plot/' # 存放绘制的图片 7 | save_record_dir = 'record/' # 存放每个州训练过程结束后的loss,包括mse和smoothl1loss 8 | device = 'cpu:0' # 没有gpu可以选择cpu:0 9 | 10 | seed = 1 11 | 12 | model_name = 'MLP' # LR,RNN,MLP 13 | 14 | # for LSTM(RNN) 15 | look_back = 2 # 以多少个小时作为特征,例如1,2,3,4,如果look_back为2,则1,2为特征,3为标签;下一次则是2,3为特征,4为标签,以此类推 16 | hidden_dims = 8 # LSTM隐藏层 17 | bi_lstm = 2 # 2个LSTM串联,第二个LSTM接收第一个的计算结果 18 | 19 | neuron_nums = [32, 16] # MLP的神经网络结构 20 | dropout_rate = 0.2 # MLP dropout的比例 21 | 22 | epochs = 500 # 训练轮次 23 | batch_size = 128 # 批次大小 24 | print_interval = 10 # 每print_interval打印 25 | lr = 3e-4 # 学习率 26 | weight_decay = 1e-5 # 正则项 27 | num_workers = 8 # 如果cpu只有4核则改为4 28 | 29 | plot_gap = 50 # 图片打印间隔,因为原始数据又8000多条,因此每隔plot_gap取一个点作为画图的数据 -------------------------------------------------------------------------------- /LSTM.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch.autograd import Variable 3 | import torch.nn as nn 4 | import pandas as pd 5 | from pandas import DataFrame 6 | import matplotlib.pyplot as plt 7 | import numpy as np 8 | 9 | class RNN(nn.Module): 10 | def __init__(self): 11 | super(RNN,self).__init__() #面向对象中的继承 12 | self.lstm = nn.LSTM(2,6,2) #输入数据2个特征维度,6个隐藏层维度,2个LSTM串联,第二个LSTM接收第一个的计算结果 13 | self.out = nn.Linear(6,1) #线性拟合,接收数据的维度为6,输出数据的维度为1 14 | def forward(self,x): 15 | x1,_ = self.lstm(x) 16 | a,b,c = x1.shape 17 | out = self.out(x1.view(-1,c)) #因为线性层输入的是个二维数据,所以此处应该将lstm输出的三维数据x1调整成二维数据,最后的特征维度不能变 18 | out1 = out.view(a,b,-1) #因为是循环神经网络,最后的时候要把二维的out调整成三维数据,下一次循环使用 19 | return out1 20 | 21 | df1 = pd.read_csv('data/ele_loads.csv') 22 | 23 | #一、数据准备 24 | 25 | datas = df1.values[:, 2] 26 | print(datas.shape) 27 | 28 | #归一化处理,这一步必不可少,不然后面训练数据误差会很大,模型没法用 29 | 30 | max_value = np.max(datas) 31 | min_value = np.min(datas) 32 | scalar = max_value - min_value 33 | datas = list(map(lambda x: x / scalar, datas)) 34 | 35 | #数据集和目标值赋值,dataset为数据,look_back为以几行数据为特征维度数量 36 | 37 | def creat_dataset(dataset,look_back): 38 | data_x = [] 39 | data_y = [] 40 | for i in range(len(dataset)-look_back): 41 | data_x.append(dataset[i:i+look_back]) 42 | data_y.append(dataset[i+look_back]) 43 | return np.asarray(data_x), np.asarray(data_y) #转为ndarray数据 44 | 45 | #以2为特征维度,得到数据集 46 | 47 | dataX, dataY = creat_dataset(datas,2) 48 | 49 | train_size = int(len(dataX)*0.7) 50 | 51 | x_train = dataX[:train_size] #训练数据 52 | y_train = dataY[:train_size] #训练数据目标值 53 | 54 | x_train = x_train.reshape(-1, 1, 2) #将训练数据调整成pytorch中lstm算法的输入维度 55 | y_train = y_train.reshape(-1, 1, 1) #将目标值调整成pytorch中lstm算法的输出维度 56 | 57 | #将ndarray数据转换为张量,因为pytorch用的数据类型是张量 58 | 59 | x_train = torch.from_numpy(x_train) 60 | y_train = torch.from_numpy(y_train) 61 | 62 | rnn = RNN() 63 | 64 | #参数寻优,计算损失函数 65 | 66 | optimizer = torch.optim.Adam(rnn.parameters(),lr = 0.02) 67 | loss_func = nn.MSELoss() 68 | 69 | for i in range(1000): 70 | var_x = Variable(x_train).type(torch.FloatTensor) 71 | var_y = Variable(y_train).type(torch.FloatTensor) 72 | print(var_y) 73 | out = rnn(var_x) 74 | loss = loss_func(out,var_y) 75 | optimizer.zero_grad() 76 | loss.backward() 77 | optimizer.step() 78 | if (i+1) % 10==0: 79 | print('Epoch:{}, Loss:{:.5f}'.format(i+1, loss.item())) 80 | 81 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | .idea/ 132 | 133 | main/plot/ 134 | main/record/ 135 | main/result/ 136 | 137 | -------------------------------------------------------------------------------- /models/Model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import torch.utils.data 5 | 6 | import numpy as np 7 | 8 | def weight_init(layers): 9 | for layer in layers: 10 | if isinstance(layer, nn.BatchNorm1d): 11 | layer.weight.data.fill_(1) 12 | layer.bias.data.zero_() 13 | elif isinstance(layer, nn.Linear): 14 | n = layer.in_features 15 | y = 1.0 / np.sqrt(n) 16 | layer.weight.data.uniform_(-y, y) 17 | layer.bias.data.fill_(0) 18 | # nn.init.kaiming_normal_(layer.weight.data, nonlinearity='relu') 19 | 20 | # 传统的预测点击率模型 21 | class LR(nn.Module): 22 | def __init__(self, 23 | feature_nums, 24 | output_dim = 1): 25 | super(LR, self).__init__() 26 | self.linear = nn.Linear(feature_nums, output_dim) 27 | 28 | self.bias = nn.Parameter(torch.zeros((output_dim,))) 29 | 30 | def forward(self, x): 31 | """ 32 | :param x: Int tensor of size (batch_size, feature_nums, latent_nums) 33 | :return: pctrs 34 | """ 35 | out = self.bias + torch.sum(self.linear(x), dim=1) 36 | 37 | return out.unsqueeze(1) 38 | 39 | 40 | class RNN(nn.Module): 41 | def __init__(self, 42 | feature_nums, 43 | hidden_dims, 44 | bi_lstm, 45 | out_dims=1): 46 | super(RNN, self).__init__() 47 | self.feature_nums = feature_nums # 输入数据特征维度 48 | self.hidden_dims = hidden_dims # 隐藏层维度 49 | self.bi_lism = bi_lstm # LSTM串联数量 50 | 51 | self.lstm = nn.LSTM(self.feature_nums, self.hidden_dims, self.bi_lism) 52 | self.out = nn.Linear(self.hidden_dims, out_dims) 53 | 54 | def forward(self,x): 55 | x1, _ = self.lstm(x) 56 | a, b, c = x1.shape 57 | out = self.out(x1.view(-1, c)) 58 | out1 = out.view(a, b, -1) 59 | 60 | return out1 61 | 62 | class MLP(nn.Module): 63 | def __init__(self, 64 | feature_nums, 65 | neuron_nums, 66 | dropout_rate, 67 | output_dim=1): 68 | super(MLP, self).__init__() 69 | self.feature_nums = feature_nums 70 | self.neuron_nums = neuron_nums 71 | self.dropout_rate = dropout_rate 72 | 73 | deep_input_dims = self.feature_nums 74 | 75 | layers = list() 76 | 77 | neuron_nums = self.neuron_nums 78 | for neuron_num in neuron_nums: 79 | layers.append(nn.Linear(deep_input_dims, neuron_num)) 80 | # layers.append(nn.BatchNorm1d(neuron_num)) 81 | layers.append(nn.ReLU()) 82 | layers.append(nn.Dropout(p=0.2)) 83 | deep_input_dims = neuron_num 84 | 85 | weight_init(layers) 86 | 87 | layers.append(nn.Linear(deep_input_dims, output_dim)) 88 | 89 | self.mlp = nn.Sequential(*layers) 90 | 91 | def forward(self, x): 92 | """ 93 | :param x: Int tensor of size (batch_size, feature_nums, latent_nums) 94 | :return: pctrs 95 | """ 96 | out = self.mlp(x) 97 | 98 | return out -------------------------------------------------------------------------------- /main/plot_main.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import tqdm 4 | import datetime 5 | import os 6 | import argparse 7 | import random 8 | import models.Model as Model 9 | import models.create_data as Data 10 | import matplotlib.pyplot as plt 11 | 12 | import torch 13 | import torch.nn as nn 14 | import torch.utils.data 15 | 16 | import logging 17 | import sys 18 | 19 | from config import Config 20 | 21 | def setup_seed(seed): 22 | torch.manual_seed(seed) 23 | torch.cuda.manual_seed_all(seed) 24 | np.random.seed(seed) 25 | random.seed(seed) 26 | torch.backends.cudnn.deterministic = True 27 | 28 | def get_dataset(data_path, dataset_name, city_name, look_back): 29 | ''' 30 | :param data_path: 数据根目录 31 | :param dataset_name: 数据名称 32 | :param city_name: 城市名称 33 | :param look_back: 为几行数据作为为特征维度数量 34 | :return: 35 | ''' 36 | # AEP,AP,ATSI,DAY,DEOK,DOM,DUQ,EKPC,MIDATL,NI 37 | data_path = data_path + dataset_name 38 | datas = pd.read_csv(data_path)[[city_name]].values # 取出对应city的数据 39 | 40 | # 归一化 41 | max_value = np.max(datas) 42 | min_value = np.min(datas) 43 | scalar = max_value - min_value 44 | datas = list(map(lambda x: x / scalar, datas)) 45 | 46 | data_x = [] # 特征 47 | data_y = [] # 标签 48 | for i in range(len(datas) - look_back): 49 | data_x.append(datas[i:i + look_back]) 50 | data_y.append(datas[i + look_back]) 51 | 52 | return np.asarray(data_x).reshape(-1, 1, look_back), np.asarray(data_y).reshape(-1, 1, 1), scalar 53 | 54 | 55 | def mk_dir(dir_name, model_name): 56 | if not os.path.exists(dir_name): 57 | os.mkdir(dir_name) 58 | 59 | dir_path = dir_name + model_name + '/' 60 | if not os.path.exists(dir_path): 61 | os.mkdir(dir_path) 62 | 63 | # 用于预训练传统预测点击率模型 64 | if __name__ == '__main__': 65 | parser = argparse.ArgumentParser() 66 | parser.add_argument('--data_path', default=Config.data_path) 67 | parser.add_argument('--dataset_name', default='ele_loads.csv', help='dataset') 68 | parser.add_argument('--model_name', default=Config.model_name, help='LR, RNN, MLP') 69 | parser.add_argument('--look_back', default=Config.look_back, help='以几行数据为特征维度数量') 70 | 71 | parser.add_argument('--plot_gap', type=int, default=Config.plot_gap) 72 | parser.add_argument('--loss_type', type=str, default='mse', help='smoothl1loss') 73 | parser.add_argument('--save_log_dir', default=Config.save_log_dir) 74 | parser.add_argument('--save_plot_dir', default=Config.save_plot_dir) 75 | parser.add_argument('--save_record_dir', default=Config.save_record_dir) 76 | parser.add_argument('--save_res_dir', default=Config.save_res_dir) 77 | 78 | args = parser.parse_args() 79 | 80 | # 设置随机数种子 81 | setup_seed(Config.seed) 82 | 83 | # 创建文件夹 84 | mk_dir(args.save_plot_dir, args.model_name) 85 | save_plot_dir = args.save_plot_dir + args.model_name + '/' 86 | 87 | mk_dir(args.save_record_dir, args.model_name) 88 | save_record_dir = args.save_record_dir + args.model_name + '/' 89 | 90 | logging.basicConfig(level=logging.DEBUG, 91 | filename=args.save_log_dir + args.model_name + '_plot.log', 92 | datefmt='%Y/%m/%d %H:%M:%S', 93 | format='%(asctime)s - %(name)s - %(levelname)s - %(lineno)d - %(module)s - %(message)s') 94 | 95 | logger = logging.getLogger(__name__) 96 | logger.setLevel(logging.DEBUG) 97 | 98 | stream_handler = logging.StreamHandler(sys.stdout) 99 | stream_handler.setLevel(logging.INFO) 100 | logger.addHandler(stream_handler) 101 | 102 | logger.info('===> current model is {}!'.format(args.model_name)) 103 | logger.info('===> start ploting! ') 104 | current_city_output_dicts = dict.fromkeys(tuple('AEP,AP,ATSI,DAY,DEOK,DOM,DUQ,EKPC,MIDATL,NI'.split(','))) 105 | 106 | for city_name in current_city_output_dicts.keys(): 107 | logger.info('===> now plot the figures for the city {} '.format(city_name)) 108 | args.city_name = city_name 109 | 110 | data_x, data_y, scalar = get_dataset(args.data_path, args.dataset_name, args.city_name, args.look_back) # 获取当前州的数据 111 | 112 | for loss_type in ['mse', 'smoothl1loss']: 113 | args.loss_type = loss_type 114 | preds = pd.read_csv(args.save_res_dir + 'ele_' + args.loss_type + '_preds_' + args.model_name + '.csv') 115 | 116 | # 绘图 117 | plt.plot(preds[[args.city_name]].values.flatten()[::args.plot_gap], 'r', label='prediction') 118 | plt.plot(np.multiply(data_y.flatten()[::args.plot_gap], scalar), 'b', label='real') 119 | plt.legend(loc='best') 120 | plt.savefig(save_plot_dir + args.city_name + '_' + args.loss_type + '.jpg') 121 | # plt.show() 122 | plt.close() 123 | 124 | # 取各个州训练的最后一轮loss 125 | logger.info('===> now record the lowest loss for all cities') 126 | for loss_type in ['mse', 'smoothl1loss']: 127 | args.loss_type = loss_type 128 | losses = pd.read_csv(args.save_res_dir + 'ele_' + args.loss_type + '_losses_' + args.model_name + '.csv') 129 | losses.iloc[-1, :].to_csv(save_record_dir + args.loss_type + '_' + args.model_name + '.csv') -------------------------------------------------------------------------------- /main/main.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import tqdm 4 | import datetime 5 | import os 6 | import argparse 7 | import random 8 | import models.Model as Model 9 | import models.create_data as Data 10 | import matplotlib.pyplot as plt 11 | 12 | import torch 13 | import torch.nn as nn 14 | import torch.utils.data 15 | 16 | import logging 17 | import sys 18 | 19 | from config import Config 20 | 21 | def setup_seed(seed): 22 | torch.manual_seed(seed) 23 | torch.cuda.manual_seed_all(seed) 24 | np.random.seed(seed) 25 | random.seed(seed) 26 | torch.backends.cudnn.deterministic = True 27 | 28 | 29 | def get_model(model_name, feature_nums, hidden_dims, bi_lstm, neuron_nums, dropout_rate): 30 | ''' 31 | 获取模型 32 | :param model_name: 模型名 33 | :param feature_nums: 特征数量,其等于look_back 34 | :param hidden_dims: LSTM隐藏层数量 35 | :param bi_lstm: 是否使用双向LSTM 36 | :param neuron_nums: MLP的神经网络结构 37 | :return: 38 | ''' 39 | if model_name == 'LR': 40 | return Model.LR(args.feature_nums) 41 | if model_name == 'MLP': 42 | return Model.MLP(feature_nums, neuron_nums, dropout_rate) 43 | elif model_name == 'RNN': 44 | return Model.RNN(feature_nums, hidden_dims, bi_lstm) 45 | 46 | def get_dataset(data_path, dataset_name, city_name, look_back): 47 | ''' 48 | 读取数据 49 | :param data_path: 数据根目录 50 | :param dataset_name: 数据名称 51 | :param city_name: 城市名称 52 | :param look_back: 为几行数据作为为特征维度数量 53 | :return: 54 | ''' 55 | # AEP,AP,ATSI,DAY,DEOK,DOM,DUQ,EKPC,MIDATL,NI 56 | data_path = data_path + dataset_name 57 | datas = pd.read_csv(data_path)[[city_name]].values # 取出对应city的数据 58 | 59 | # 归一化 60 | max_value = np.max(datas) 61 | min_value = np.min(datas) 62 | scalar = max_value - min_value 63 | datas = list(map(lambda x: x / scalar, datas)) 64 | 65 | data_x = [] # 特征 66 | data_y = [] # 标签 67 | for i in range(len(datas) - look_back): 68 | data_x.append(datas[i:i + look_back]) 69 | data_y.append(datas[i + look_back]) 70 | 71 | return np.asarray(data_x).reshape(-1, 1, look_back), np.asarray(data_y).reshape(-1, 1, 1), scalar 72 | 73 | 74 | def train(model, optimizer, data_loader, loss, device): 75 | ''' 76 | 训练函数 77 | :param model: pytorch模型类 78 | :param optimizer: 优化器 79 | :param data_loader: pytorch数据加载器 80 | :param loss: 损失 81 | :param device: 采用cpu还是gpu 82 | :return: 83 | ''' 84 | model.train() # 转换为训练模式 85 | total_loss = 0 86 | log_intervals = 0 87 | for features, labels in data_loader: 88 | features, labels = features.float().to(device), labels.to(device) 89 | y = model(features) 90 | 91 | train_loss = loss(y, labels.float()) 92 | 93 | model.zero_grad() 94 | train_loss.backward() 95 | optimizer.step() 96 | total_loss += train_loss.item() # 取张量tensor里的标量值,如果直接返回train_loss很可能会造成GPU out of memory 97 | 98 | log_intervals += 1 99 | 100 | return total_loss / log_intervals 101 | 102 | 103 | def sub(model, data_loader, loss, device): 104 | ''' 105 | 评估函数 106 | :param model: pytorch模型类 107 | :param data_loader: pytorch数据加载器 108 | :param loss: 损失 109 | :param device: 采用cpu还是gpu 110 | :return: 111 | ''' 112 | model.eval() 113 | predicts = list() 114 | intervals = 0 115 | total_test_loss = 0 116 | with torch.no_grad(): 117 | for features, labels in data_loader: 118 | features, labels = features.float().to(device), labels.to(device) 119 | y = model(features) 120 | 121 | test_loss = loss(y, labels.float()) 122 | predicts.extend(y.tolist()) 123 | intervals += 1 124 | total_test_loss += test_loss.item() 125 | 126 | return total_test_loss / intervals, np.asarray(predicts).flatten() 127 | 128 | def main(args, logger): 129 | ''' 130 | 主函数 131 | :param args: 超参定义器 132 | :param logger: 日志句柄 133 | :return: 134 | ''' 135 | device = torch.device(args.device) # 指定运行设备 136 | 137 | data_x, data_y, scalar = get_dataset(args.data_path, args.dataset_name, args.city_name, args.look_back) 138 | 139 | ''' 140 | 写个划分训练集和测试集的方法,但我不建议这么做,因为会影响时序。最好还是利用新的测试集 141 | ''' 142 | # train_slice = int(data_x.shape[0] * 0.6) # 6 4划分训练集 143 | # train_dataset = Data.generate_dataset(data_x[:train_slice, :], data_y[:train_slice, :]) 144 | # train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, num_workers=args.num_workers) 145 | # test_dataset = Data.generate_dataset(data_x[train_slice:, :], data_y[train_slice:, :]) 146 | # test_data_loader = torch.utils.data.DataLoader(test_dataset, batch_size=args.batch_size, 147 | # num_workers=args.num_workers) 148 | 149 | train_dataset = Data.generate_dataset(data_x, data_y) 150 | train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, num_workers=args.num_workers) 151 | 152 | feature_nums = args.look_back 153 | model = get_model(args.model_name, feature_nums, args.hidden_dims, args.bi_lstm, args.neuron_nums, args.dropout_rate).to(device) 154 | logger.info(model) 155 | 156 | if args.loss_type == 'mse': 157 | loss = nn.MSELoss() 158 | elif args.loss_type == 'smoothl1loss': 159 | loss = nn.SmoothL1Loss() 160 | 161 | optimizer = torch.optim.Adam(params=model.parameters(), lr=args.lr, weight_decay=args.weight_decay) 162 | 163 | start_time = datetime.datetime.now() 164 | train_epoch_loss = [] 165 | for epoch_i in range(args.epochs): 166 | torch.cuda.empty_cache() # 清理无用的cuda中间变量缓存 167 | 168 | train_average_loss = train(model, optimizer, train_data_loader, loss, device) # 训练 169 | train_epoch_loss.append(train_average_loss) 170 | 171 | train_end_time = datetime.datetime.now() 172 | 173 | if epoch_i % args.print_interval == 0: # 打印结果 174 | logger.info('City {}, model {}, epoch {}, train_{}_loss {}, ' 175 | '[{}s]'.format(args.city_name, args.model_name, epoch_i, 176 | args.loss_type, train_average_loss, (train_end_time - start_time).seconds)) 177 | 178 | torch.save(model.state_dict(), os.path.join(args.save_param_dir, 179 | args.model_name + '_best_' + args.loss_type + '.pth')) # 存储参数 180 | 181 | valid_dataset = Data.generate_dataset(data_x, data_y) 182 | valid_data_loader = torch.utils.data.DataLoader(valid_dataset, batch_size=args.batch_size, num_workers=args.num_workers) 183 | 184 | # submission 185 | valid_loss, preds = sub(model, valid_data_loader, loss, device) 186 | 187 | ''' 188 | 如果从训练集中划分了测试集,这里可以改为如下形式,test_data_loader为上面第146行定义的变量 189 | ''' 190 | # valid_loss, preds = sub(model, test_data_loader, loss, device) 191 | 192 | output_dict = {} 193 | output_dict.setdefault(args.loss_type + '_loss', train_epoch_loss) 194 | output_dict.setdefault(args.loss_type + '_preds', (preds * scalar).tolist()) 195 | 196 | return output_dict 197 | 198 | 199 | # 用于预训练传统预测点击率模型 200 | if __name__ == '__main__': 201 | parser = argparse.ArgumentParser() 202 | parser.add_argument('--data_path', default=Config.data_path) 203 | parser.add_argument('--dataset_name', default='ele_loads.csv', help='dataset') 204 | parser.add_argument('--model_name', default=Config.model_name, help='LR, RNN, MLP') 205 | parser.add_argument('--neuron_nums', type=list, default=Config.neuron_nums) 206 | parser.add_argument('--dropout_rate', type=float, default=Config.dropout_rate) 207 | parser.add_argument('--num_workers', default=Config.num_workers, help='4, 8, 16, 32') 208 | parser.add_argument('--hidden_dims', default=Config.hidden_dims) 209 | parser.add_argument('--bi_lstm', default=Config.bi_lstm, help='1, 2') 210 | parser.add_argument('--look_back', default=Config.look_back, help='以几行数据为特征维度数量') 211 | parser.add_argument('--city_name', default='AEP', help='AEP,AP,ATSI,DAY,DEOK,DOM,DUQ,EKPC,MIDATL,NI') 212 | parser.add_argument('--epochs', type=int, default=Config.epochs) 213 | parser.add_argument('--lr', type=float, default=Config.lr) 214 | parser.add_argument('--weight_decay', type=float, default=Config.weight_decay) 215 | parser.add_argument('--batch_size', type=int, default=Config.batch_size) 216 | parser.add_argument('--print_interval', type=int, default=Config.print_interval) 217 | parser.add_argument('--device', default=Config.device) 218 | 219 | parser.add_argument('--loss_type', type=str, default='mse', help='smoothl1loss') 220 | parser.add_argument('--save_log_dir', default=Config.save_log_dir) 221 | parser.add_argument('--save_res_dir', default=Config.save_res_dir) 222 | parser.add_argument('--save_param_dir', default=Config.save_param_dir) 223 | 224 | args = parser.parse_args() 225 | 226 | # 设置随机数种子 227 | setup_seed(Config.seed) 228 | 229 | if not os.path.exists(args.save_log_dir): 230 | os.mkdir(args.save_log_dir) 231 | 232 | if not os.path.exists(args.save_res_dir): 233 | os.mkdir(args.save_res_dir) 234 | 235 | if not os.path.exists(args.save_param_dir): 236 | os.mkdir(args.save_param_dir) 237 | 238 | logging.basicConfig(level=logging.DEBUG, 239 | filename=args.save_log_dir + args.model_name + '_output.log', 240 | datefmt='%Y/%m/%d %H:%M:%S', 241 | format='%(asctime)s - %(name)s - %(levelname)s - %(lineno)d - %(module)s - %(message)s') 242 | 243 | logger = logging.getLogger(__name__) 244 | logger.setLevel(logging.DEBUG) 245 | 246 | stream_handler = logging.StreamHandler(sys.stdout) 247 | stream_handler.setLevel(logging.INFO) 248 | logger.addHandler(stream_handler) 249 | 250 | logger.info('===> start training! ') 251 | # 将各个州的数据保存到字典中 252 | current_city_output_dicts = dict.fromkeys(tuple('AEP,AP,ATSI,DAY,DEOK,DOM,DUQ,EKPC,MIDATL,NI'.split(','))) 253 | for city_name in current_city_output_dicts.keys(): 254 | logger.info('===> now excuate the city {} '.format(city_name)) 255 | args.city_name = city_name 256 | current_city_output_dict = {} 257 | for loss_type in ['mse', 'smoothl1loss']: 258 | args.loss_type = loss_type 259 | output_dict = main(args, logger) # 主运行函数 260 | for key in output_dict.keys(): 261 | current_city_output_dict.setdefault(key, output_dict[key]) 262 | current_city_output_dicts[city_name] = current_city_output_dict 263 | 264 | # 存储loss和preds 265 | for loss_type in ['mse', 'smoothl1loss']: 266 | city_preds = {} 267 | city_losses = {} 268 | for city_name in current_city_output_dicts.keys(): 269 | current_city_output_loss = current_city_output_dicts[city_name][loss_type + '_loss'] 270 | current_city_output_pred = current_city_output_dicts[city_name][loss_type + '_preds'] 271 | 272 | city_losses.setdefault(city_name, current_city_output_loss) 273 | city_preds.setdefault(city_name, current_city_output_pred) 274 | 275 | city_loss_df = pd.DataFrame(data=city_losses) 276 | city_loss_df.to_csv(args.save_res_dir + '/ele_' + loss_type + '_losses_' + args.model_name + '.csv', index=None) 277 | 278 | city_pred_df = pd.DataFrame(data=city_preds) 279 | city_pred_df.to_csv(args.save_res_dir + '/ele_' + loss_type + '_preds_' + args.model_name + '.csv', index=None) 280 | 281 | 282 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------