From ddbf3e5d6124d598fff3c6eb4841468d50fb79d5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=B8=BD=E5=AD=90?= <2316994765@qq.com>
Date: Fri, 27 Oct 2023 15:11:16 +0800
Subject: [PATCH] =?UTF-8?q?=E7=94=B5=E5=8E=8B=E7=AD=89=E7=BA=A7=E8=BE=93?=
=?UTF-8?q?=E5=87=BA=E4=B8=BA5lstm?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.idea/misc.xml | 2 +-
.idea/pytorch2.iml | 2 +-
bp神经网络.py | 72 +++----
入模数据/1.py | 1 -
浙江电压等级电量/test1.py | 7 +
.../电压等级_输出为3.py | 176 ------------------
.../电压等级_输出为5.py | 172 +++++++++++++++++
7 files changed, 217 insertions(+), 215 deletions(-)
create mode 100644 浙江电压等级电量/test1.py
delete mode 100644 浙江电压等级电量/电压等级_输出为3.py
create mode 100644 浙江电压等级电量/电压等级_输出为5.py
diff --git a/.idea/misc.xml b/.idea/misc.xml
index 695b918..3141537 100644
--- a/.idea/misc.xml
+++ b/.idea/misc.xml
@@ -1,4 +1,4 @@
-
+
\ No newline at end of file
diff --git a/.idea/pytorch2.iml b/.idea/pytorch2.iml
index 5cfdc49..719cec4 100644
--- a/.idea/pytorch2.iml
+++ b/.idea/pytorch2.iml
@@ -2,7 +2,7 @@
-
+
\ No newline at end of file
diff --git a/bp神经网络.py b/bp神经网络.py
index 4dd32e5..dd3197f 100644
--- a/bp神经网络.py
+++ b/bp神经网络.py
@@ -3,33 +3,37 @@ import pandas as pd
import matplotlib.pyplot as plt
import torch
from sklearn import preprocessing
+from torch.utils.data import DataLoader,TensorDataset
-data = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\杭州数据.xlsx',index_col='dtdate')
+
+
+data = pd.read_excel(r'C:\python-project\pytorch3\入模数据\杭州数据.xlsx',index_col='dtdate')
print(data.columns)
-y = np.array(data['售电量']) # 制作标签,用于比对训练结果
-x = data.drop(columns=['售电量','city_name']) # 在特征数据集中去掉label
-# df.drop(label, axis=0)
-# label:要删除的列或者行,如果要删除多个,传入列表
-# axis:轴的方向,0为行,1为列,默认为0
-fea_train = np.array(x) # 转换为ndarray格式
+x = np.array(data.drop(columns=['售电量','city_name']).loc['2021-1':'2023-6'])
+y = np.array(data['售电量'].loc['2021-1':'2023-6'])
# 数据标准化操作:(x-均值μ) / 标准差σ ,使数据关于原点对称,提升训练效率
-input_features = preprocessing.StandardScaler().fit_transform(fea_train) # fit:求出均值和标准差 transform:求解
+input_features = preprocessing.StandardScaler().fit_transform(np.array(x)) # fit:求出均值和标准差 transform:求解
+
+# y归一化
+min = np.min(y)
+max = np.max(y)
+y = (y - min)/(max - min)
+
+x_eval = torch.from_numpy(data.drop(columns=['售电量','city_name']).loc['2023-7'].values).type(torch.float32)
+y_eval = torch.from_numpy(data['售电量'].loc['2023-7'].values).type(torch.float32)
+
+ds = TensorDataset(torch.from_numpy(x),torch.from_numpy(y))
+dl = DataLoader(ds,batch_size=12,shuffle=True,drop_last=True)
-# y归一化 防止梯度爆炸
-y = (y - np.min(y))/(np.max(y) - np.min(y))
-print(y)
# 设定神经网络的输入参数、隐藏层神经元、输出参数的个数
input_size = input_features.shape[1] # 设定输入特征个数
-# np.shape[1]
-# 0为行,1为列,默认为0
-# 在此表格中因为每行为各样本的值,每列为不同的特征分类,所以此处0表示样本数,1表示特征数
-hidden_size = 64 # 设定隐藏层包含64个神经元
-output_size = 1 # 设定输出特征个数为1
-batch_size = 32 # 每一批迭代的特征数量
+
+hidden_size = 64
+output_size =1
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # 选择使用GPU训练
@@ -40,24 +44,21 @@ my_nn = torch.nn.Sequential(
torch.nn.ReLU().to(device),
torch.nn.Linear(hidden_size, hidden_size).to(device), # 第二层 → 第三层
torch.nn.ReLU().to(device),
- torch.nn.Linear(hidden_size, hidden_size).to(device), # 第三层 → 第四层
- torch.nn.ReLU().to(device),
- torch.nn.Linear(hidden_size, output_size).to(device) # 第四层 → 输出层
+ torch.nn.Linear(hidden_size, output_size)
).to(device)
cost = torch.nn.MSELoss().to(device)
-optimizer = torch.optim.Adam(my_nn.parameters(), lr=0.001)
+optimizer = torch.optim.Adam(my_nn.parameters(), lr=0.0001)
# 训练网络
losses = []
-for i in range(300):
+for i in range(1000):
batch_loss = []
# 采用MINI-Batch的方法进行训练
- for start in range(0, len(input_features), batch_size):
- end = start + batch_size if start + batch_size < len(input_features) else len(input_features)
- x_train = torch.tensor(input_features[start:end], dtype=torch.float32, requires_grad=True).to(device)
- y_train = torch.tensor(y[start:end], dtype=torch.float32, requires_grad=True).to(device)
- prediction = my_nn(x_train)
- loss = cost(y_train, prediction)
+ for X,y in dl:
+ X,y = X.to(device).type(torch.float32),y.to(device).type(torch.float32)
+
+ prediction = my_nn(X)
+ loss = cost(y, prediction)
optimizer.zero_grad()
loss.backward(retain_graph=True)
optimizer.step()
@@ -65,17 +66,16 @@ for i in range(300):
if i % 10 == 0:
losses.append(np.mean(batch_loss))
- print(losses)
print(i, np.mean(batch_loss))
# 保存模型
# torch.save(my_nn, 'BP.pt')
# 绘制图像
-dev_x = [i * 10 for i in range(20)]
-plt.xlabel('step count')
-plt.ylabel('loss')
-plt.xlim((0, 200))
-plt.ylim((0, 1000))
-plt.plot(dev_x, losses)
-plt.show()
+# dev_x = [i * 10 for i in range(20)]
+# plt.xlabel('step count')
+# plt.ylabel('loss')
+# plt.xlim((0, 200))
+# plt.ylim((0, 1000))
+# plt.plot(dev_x, losses)
+# plt.show()
diff --git a/入模数据/1.py b/入模数据/1.py
index ee25aa9..f382c45 100644
--- a/入模数据/1.py
+++ b/入模数据/1.py
@@ -17,7 +17,6 @@ def hf_season(x):
return list1
-
def season(x):
if str(x)[5:7] in ('06','07','08','12','01','02'):
return 1
diff --git a/浙江电压等级电量/test1.py b/浙江电压等级电量/test1.py
new file mode 100644
index 0000000..6d9eca7
--- /dev/null
+++ b/浙江电压等级电量/test1.py
@@ -0,0 +1,7 @@
+import numpy as np
+n1 = np.array([[1,1,1]])
+n2 = np.array([1,1,1]).reshape(1,-1)
+print(n2)
+n2 = np.array([]).reshape(3,-1)
+
+print(np.max([[1,2,3],[4,5,6]]))
\ No newline at end of file
diff --git a/浙江电压等级电量/电压等级_输出为3.py b/浙江电压等级电量/电压等级_输出为3.py
deleted file mode 100644
index 06d144c..0000000
--- a/浙江电压等级电量/电压等级_输出为3.py
+++ /dev/null
@@ -1,176 +0,0 @@
-import numpy as np
-import pandas as pd
-import torch
-from torch import nn
-from multiprocessing import Pool
-import matplotlib.pyplot as plt
-import os
-os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
-DAYS_FOR_TRAIN = 10
-torch.manual_seed(42)
-class LSTM_Regression(nn.Module):
-
- def __init__(self, input_size, hidden_size, output_size=1, num_layers=2):
- super().__init__()
-
- self.lstm = nn.LSTM(input_size, hidden_size, num_layers)
- self.fc = nn.Linear(hidden_size, output_size)
-
- def forward(self, _x):
- x, _ = self.lstm(_x) # _x is input, size (seq_len, batch, input_size)
- s, b, h = x.shape # x is output, size (seq_len, batch, hidden_size)
- x = x.view(s * b, h)
- x = self.fc(x)
- x = x.view(s, b, -1) # 把形状改回来
- return x
-
-
-def create_dataset(data, days_for_train=5) -> (np.array, np.array):
- dataset_x, dataset_y = [], []
- for i in range(len(data) - days_for_train-3):
- _x = data[i:(i + days_for_train)]
- dataset_x.append(_x)
- dataset_y.append(data[i + days_for_train:i + days_for_train+3])
- return (np.array(dataset_x), np.array(dataset_y))
-
-def normal(nd):
- high = nd.describe()['75%'] + 1.5*(nd.describe()['75%']-nd.describe()['25%'])
- low = nd.describe()['25%'] - 1.5*(nd.describe()['75%']-nd.describe()['25%'])
- return nd[(ndlow)]
-
-
-
-# def get_data():
-file_dir = r'C:\Users\鸽子\Desktop\浙江各地市分电压日电量数据'
-dataset_x = []
-for excel in os.listdir(file_dir):
- data = pd.read_excel(os.path.join(file_dir,excel), sheet_name=0,index_col=' stat_date ')
- data.columns = data.columns.map(lambda x: x.strip())
-
- data.index = pd.to_datetime(data.index,format='%Y%m%d')
- data.sort_index(inplace=True)
-
- data = data.loc['2021-01':'2023-08']
- data.drop(columns=[i for i in data.columns if (data[i] == 0).sum() / len(data) >= 0.5], inplace=True) # 去除0值列
- print('len(data):', len(data))
- list_app = []
- for level in data.columns:
- df = data[level]
- df = df[df.values != 0] # 去除0值行
- df = normal(df)
- df = df.astype('float32').values # 转换数据类型
- dataset_x create_dataset(df,DAYS_FOR_TRAIN)
-
-
-def run(file_dir,excel):
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
-
- data = pd.read_excel(os.path.join(file_dir,excel), sheet_name=0,index_col=' stat_date ')
-
- data.columns = data.columns.map(lambda x: x.strip())
-
- data.index = pd.to_datetime(data.index,format='%Y%m%d')
- data.sort_index(inplace=True)
- print(data.head())
- data = data.loc['2021-01':'2023-09']
-
- data.drop(columns=[i for i in data.columns if (data[i] == 0).sum() / len(data) >= 0.5], inplace=True) # 去除0值列
- print('len(data):', len(data))
- list_app = []
- for level in data.columns:
- df = data[level]
- df = df[df.values != 0] # 去除0值行
- df = normal(df)
- df = df.astype('float32').values # 转换数据类型
-
-
- # 标准化到0~1
- max_value = np.max(df)
- min_value = np.min(df)
- df = (df - min_value) / (max_value - min_value)
-
- dataset_x, dataset_y = create_dataset(df, DAYS_FOR_TRAIN)
- print('len(dataset_x:)', len(dataset_x))
-
- # 划分训练集和测试集
- train_size = len(dataset_x) - 3
- train_x = dataset_x[:train_size]
- train_y = dataset_y[:train_size]
-
- # 将数据改变形状,RNN 读入的数据维度是 (seq_size, batch_size, feature_size)
- train_x = train_x.reshape(-1, 1, DAYS_FOR_TRAIN)
- train_y = train_y.reshape(-1, 1, 3)
-
- # 转为pytorch的tensor对象
- train_x = torch.from_numpy(train_x).to(device)
- train_y = torch.from_numpy(train_y).to(device)
-
- model = LSTM_Regression(DAYS_FOR_TRAIN, 32, output_size=3, num_layers=2).to(device) # 导入模型并设置模型的参数输入输出层、隐藏层等
-
-
- train_loss = []
- loss_function = nn.MSELoss()
- optimizer = torch.optim.Adam(model.parameters(), lr=0.005, betas=(0.9, 0.999), eps=1e-08, weight_decay=0)
- for i in range(1500):
- out = model(train_x)
- loss = loss_function(out, train_y)
- loss.backward()
- optimizer.step()
- optimizer.zero_grad()
- train_loss.append(loss.item())
- # print(loss)
- # 保存模型
- # torch.save(model.state_dict(),save_filename)
- # torch.save(model.state_dict(),os.path.join(model_save_dir,model_file))
-
- # for test
- model = model.eval() # 转换成测试模式
- # model.load_state_dict(torch.load(os.path.join(model_save_dir,model_file))) # 读取参数
- dataset_x = dataset_x.reshape(-1, 1, DAYS_FOR_TRAIN) # (seq_size, batch_size, feature_size)
- dataset_x = torch.from_numpy(dataset_x).to(device)
-
- pred_test = model(dataset_x) # 全量训练集
- # 模型输出 (seq_size, batch_size, output_size)
- pred_test = pred_test.view(-1)
- pred_test = np.concatenate((np.zeros(DAYS_FOR_TRAIN), pred_test.cpu().detach().numpy()))
-
- # plt.plot(pred_test, 'r', label='prediction')
- # plt.plot(df, 'b', label='real')
- # plt.plot((train_size, train_size), (0, 1), 'g--') # 分割线 左边是训练数据 右边是测试数据的输出
- # plt.legend(loc='best')
- # plt.show()
-
-
- # 创建测试集
- # result_list = []
- # 以x为基础实际数据,滚动预测未来3天
- x = torch.from_numpy(df[-14:-4]).to(device)
- pred = model(x.reshape(-1,1,DAYS_FOR_TRAIN)).view(-1).detach().numpy()
-
-
- # 反归一化
- pred = pred * (max_value - min_value) + min_value
- df = df * (max_value - min_value) + min_value
-
- print(pred)
- # 打印指标
- print(abs(pred - df[-3:]).mean() / df[-3:].mean())
- result_eight = pd.DataFrame({'pred': np.round(pred,1),'real': df[-3:]})
- target = (result_eight['pred'].sum() - result_eight['real'].sum()) / df[-31:].sum()
- result_eight['loss_rate'] = round(target, 5)
- result_eight['industry'] = industry
- list_app.append(result_eight)
- print(target)
- print(result_eight)
- final_df = pd.concat(list_app,ignore_index=True)
- final_df.to_csv('市行业电量.csv',encoding='gbk')
- print(final_df)
-
- # result_eight.to_csv(f'./月底预测结果/9月{excel[:2]}.txt', sep='\t', mode='a')
- # with open(fr'./偏差/9月底偏差率.txt', 'a', encoding='utf-8') as f:
- # f.write(f'{excel[:2]}{industry}:{round(target, 5)}\n')
-
-if __name__ == '__main__':
- file_dir = r'C:\Users\鸽子\Desktop\浙江各地市分电压日电量数据'
-
- run(file_dir,'杭州.xlsx')
diff --git a/浙江电压等级电量/电压等级_输出为5.py b/浙江电压等级电量/电压等级_输出为5.py
new file mode 100644
index 0000000..9767442
--- /dev/null
+++ b/浙江电压等级电量/电压等级_输出为5.py
@@ -0,0 +1,172 @@
+import numpy as np
+import pandas as pd
+import torch
+from torch import nn
+from multiprocessing import Pool
+import matplotlib.pyplot as plt
+import os
+os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
+DAYS_FOR_TRAIN = 10
+torch.manual_seed(42)
+class LSTM_Regression(nn.Module):
+
+ def __init__(self, input_size, hidden_size, output_size=1, num_layers=2):
+ super().__init__()
+
+ self.lstm = nn.LSTM(input_size, hidden_size, num_layers)
+ self.fc = nn.Linear(hidden_size, output_size)
+
+ def forward(self, _x):
+ x, _ = self.lstm(_x) # _x is input, size (seq_len, batch, input_size)
+ s, b, h = x.shape # x is output, size (seq_len, batch, hidden_size)
+ x = x.view(s * b, h)
+ x = self.fc(x)
+ x = x.view(s, b, -1) # 把形状改回来
+ return x
+
+
+def create_dataset(data, days_for_train=5) -> (np.array, np.array):
+ dataset_x, dataset_y = [], []
+ for i in range(len(data) - days_for_train-5):
+ dataset_x.append(data[i:(i + days_for_train)])
+ dataset_y.append(data[i + days_for_train:i + days_for_train+5])
+ # print(dataset_x,dataset_y)
+ return (np.array(dataset_x), np.array(dataset_y))
+
+def normal(nd):
+ high = nd.describe()['75%'] + 1.5*(nd.describe()['75%']-nd.describe()['25%'])
+ low = nd.describe()['25%'] - 1.5*(nd.describe()['75%']-nd.describe()['25%'])
+ return nd[(ndlow)]
+
+def data_preprocessing(data):
+ data.columns = data.columns.map(lambda x: x.strip())
+ data.index = pd.to_datetime(data.index)
+ data.sort_index(inplace=True)
+ data = data.loc['2021-01':'2023-08']
+ data.drop(columns=[i for i in data.columns if (data[i] == 0).sum() / len(data) >= 0.5], inplace=True) # 去除0值列
+ data = data[data.values != 0]
+ data = data.astype(float)
+ for col in data.columns:
+ data[col] = normal(data[col])
+
+ return data
+
+
+# 拼接数据集
+file_dir = r'C:\Users\鸽子\Desktop\浙江各地市分电压日电量数据'
+excel = os.listdir(file_dir)[0]
+
+data = pd.read_excel(os.path.join(file_dir, excel), sheet_name=0, index_col=' stat_date ')
+
+data = data_preprocessing(data)
+
+df = data[data.columns[0]]
+df.dropna(inplace = True)
+dataset_x, dataset_y = create_dataset(df, DAYS_FOR_TRAIN)
+
+for level in data.columns[1:]:
+ df = data[level]
+ df.dropna(inplace=True)
+ x, y = create_dataset(df, DAYS_FOR_TRAIN)
+ dataset_x = np.concatenate((dataset_x, x))
+ dataset_y = np.concatenate((dataset_y, y))
+
+
+for excel in os.listdir(file_dir)[1:]:
+ data = pd.read_excel(os.path.join(file_dir,excel), sheet_name=0,index_col=' stat_date ')
+ data = data_preprocessing(data)
+
+ for level in data.columns:
+ df = data[level]
+ df.dropna(inplace=True)
+ x,y = create_dataset(df,DAYS_FOR_TRAIN)
+ dataset_x = np.concatenate((dataset_x,x))
+ dataset_y = np.concatenate((dataset_y,y))
+
+print(dataset_x,dataset_y,dataset_x.shape,dataset_y.shape)
+
+# 训练
+device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+
+# 标准化到0~1
+max_value = np.max(dataset_x)
+min_value = np.min(dataset_x)
+dataset_x = (dataset_x - min_value) / (max_value - min_value)
+dataset_y = (dataset_y - min_value) / (max_value - min_value)
+
+# 划分训练集和测试集
+train_size = len(dataset_x)*0.7
+train_x = dataset_x[:train_size]
+train_y = dataset_y[:train_size]
+
+# 将数据改变形状,RNN 读入的数据维度是 (seq_size, batch_size, feature_size)
+train_x = train_x.reshape(-1, 1, DAYS_FOR_TRAIN)
+train_y = train_y.reshape(-1, 1, 5)
+
+# 转为pytorch的tensor对象
+train_x = torch.from_numpy(train_x).to(device)
+train_y = torch.from_numpy(train_y).to(device)
+
+model = LSTM_Regression(DAYS_FOR_TRAIN, 32, output_size=3, num_layers=2).to(device) # 导入模型并设置模型的参数输入输出层、隐藏层等
+
+
+train_loss = []
+loss_function = nn.MSELoss()
+optimizer = torch.optim.Adam(model.parameters(), lr=0.005, betas=(0.9, 0.999), eps=1e-08, weight_decay=0)
+for i in range(1500):
+ out = model(train_x)
+ loss = loss_function(out, train_y)
+ loss.backward()
+ optimizer.step()
+ optimizer.zero_grad()
+ train_loss.append(loss.item())
+ # print(loss)
+# 保存模型
+torch.save(model.state_dict(),'dy5.pth')
+
+
+# for test
+model = model.eval() # 转换成测试模式
+# model.load_state_dict(torch.load(os.path.join(model_save_dir,model_file))) # 读取参数
+dataset_x = dataset_x.reshape(-1, 1, DAYS_FOR_TRAIN) # (seq_size, batch_size, feature_size)
+dataset_x = torch.from_numpy(dataset_x).to(device)
+
+pred_test = model(dataset_x) # 全量训练集
+# 模型输出 (seq_size, batch_size, output_size)
+pred_test = pred_test.view(-1)
+pred_test = np.concatenate((np.zeros(DAYS_FOR_TRAIN), pred_test.cpu().detach().numpy()))
+
+plt.plot(pred_test, 'r', label='prediction')
+plt.plot(df, 'b', label='real')
+plt.plot((train_size, train_size), (0, 1), 'g--') # 分割线 左边是训练数据 右边是测试数据的输出
+plt.legend(loc='best')
+plt.show()
+
+
+# 创建测试集
+# result_list = []
+# 以x为基础实际数据,滚动预测未来3天
+# x = torch.from_numpy(df[-14:-4]).to(device)
+# pred = model(x.reshape(-1,1,DAYS_FOR_TRAIN)).view(-1).detach().numpy()
+
+
+# 反归一化
+# pred = pred * (max_value - min_value) + min_value
+# df = df * (max_value - min_value) + min_value
+
+# print(pred)
+# # 打印指标
+# print(abs(pred - df[-3:]).mean() / df[-3:].mean())
+# result_eight = pd.DataFrame({'pred': np.round(pred,1),'real': df[-3:]})
+# target = (result_eight['pred'].sum() - result_eight['real'].sum()) / df[-31:].sum()
+# result_eight['loss_rate'] = round(target, 5)
+# result_eight['level'] = level
+# list_app.append(result_eight)
+# print(target)
+# print(result_eight)
+# final_df = pd.concat(list_app,ignore_index=True)
+# final_df.to_csv('市行业电量.csv',encoding='gbk')
+# print(final_df)
+
+
+