时间序列预测:用电量预测 05 BP神经网络

🌮开发平台:jupyter lab

🍖运行环境:python3、TensorFlow2.x

----------------------------------------------- 2022.9.16 测验成功 ----------------------------------------------------------------
1. 时间序列预测:用电量预测 01 数据分析与建模
2. 时间序列预测:用电量预测 02 KNN(K邻近算法)
3. 时间序列预测:用电量预测 03 Linear(多元线性回归算法 & 数据未标准化)
4.时间序列预测:用电量预测 04 Std_Linear(多元线性回归算法 & 数据标准化)
5. 时间序列预测:用电量预测 05 BP神经网络
6.时间序列预测:用电量预测 06 长短期记忆网络LSTM
7. 时间序列预测:用电量预测 07 灰色预测算法

说明:根据上述列表中 1.时间序列预测:用电量预测 01 数据分析与建模 进行数据整理,得到household_power_consumption_days.csv文件,部分数据展示如下:

在这里插入图片描述

1.导包

### 线性回归
## 测试数据:训练数据和测试数据比例分别占0.9、0.1
## BP神经网络
import tensorflow as tf
from tensorflow.keras.preprocessing import sequence
from tensorflow.keras.models import Sequential
from tensorflow.keras.datasets import boston_housing
from tensorflow.keras.layers import Dense, Dropout
# from tensorflow.keras.utils import multi_gpu_model
from tensorflow.keras import regularizers  # 正则化
import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
import warnings
warnings.filterwarnings('ignore')

2. 数据获取

2.1 数据划分

### 2.1 将日期变作index
data = pd.read_csv('../1_pusu/household_power_consumption_days.csv', header=0, infer_datetime_format=True, parse_dates=['datetime'], index_col=['datetime'])

### 2.2 查看data的状态
data.shape  ##(1442, 8)

### 2.3 定义自变量和因变量
## 定义自变量
x_keys = ['Global_active_power', 'Global_reactive_power', 'Voltage',
       'Global_intensity', 'Sub_metering_1', 'Sub_metering_2',
       'Sub_metering_3']
x = data[x_keys]
## 定义因变量
y_keys = ['sub_metering_4']
y = data[y_keys]
x.shape,y.shape   ## ((1442, 7), (1442, 1))

## 2.4 划分测试集和训练集
from sklearn.model_selection import train_test_split
x_train_pd,x_valid_pd,y_train_pd,y_valid_pd = train_test_split(x,y,test_size=0.1)
x_train_pd.shape,x_valid_pd.shape,y_train_pd.shape,y_valid_pd.shape  ## ((1297, 7), (145, 7), (1297, 1), (145, 1))

2.2 数据集、测试集标准化

# 训练集归一化
min_max_scaler = MinMaxScaler()
min_max_scaler.fit(x_train_pd)
x_train = min_max_scaler.transform(x_train_pd)

min_max_scaler.fit(y_train_pd)
y_train = min_max_scaler.transform(y_train_pd)

# 验证集归一化
min_max_scaler.fit(x_valid_pd)
x_valid = min_max_scaler.transform(x_valid_pd)

min_max_scaler.fit(y_valid_pd)
y_valid = min_max_scaler.transform(y_valid_pd)

3.模型

3.1 模型构建,并训练

# 单CPU or GPU版本,若有GPU则自动切换
model = Sequential()  # 初始化,很重要!
model.add(Dense(units = 10,   # 输出大小
                activation='relu',  # 激励函数
                input_shape=(x_train_pd.shape[1],)  # 输入大小, 也就是列的大小
               )
         )

model.add(Dropout(0.2))  # 丢弃神经元链接概率

model.add(Dense(units = 15,
#                 kernel_regularizer=regularizers.l2(0.01),  # 施加在权重上的正则项
#                 activity_regularizer=regularizers.l1(0.01),  # 施加在输出上的正则项
                activation='relu' # 激励函数
                # bias_regularizer=keras.regularizers.l1_l2(0.01)  # 施加在偏置向量上的正则项
               )
         )
model.add(Dense(units = 1,   
                activation='linear'  # 线性激励函数 回归一般在输出层用这个激励函数  
               )
         )

print(model.summary())  # 打印网络层次结构

model.compile(loss='mse',  # 损失均方误差
              optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),  # 优化器
             )

history = model.fit(x_train, y_train,
          epochs=200,  # 迭代次数
          batch_size=200,  # 每次用来梯度下降的批处理数据大小
          verbose=2,  # verbose:日志冗长度,int:冗长度,0:不输出训练过程,1:输出训练进度,2:输出每一个epoch
          validation_data = (x_valid, y_valid)  # 验证集
        )

在这里插入图片描述
在这里插入图片描述

3.2 模型损失loss和val_loss对比图

import matplotlib.pyplot as plt
# 绘制训练 & 验证的损失值
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()

在这里插入图片描述

3.3 数据预测,并反标准化

# 预测
y_new = model.predict(x_valid)
# 反归一化
min_max_scaler.fit(y_valid_pd)
y_new = min_max_scaler.inverse_transform(y_new)

4.数据展示

4.1 以表格形式对比测试集原始目标数据和预测目标数据

## 1.提取原y列的值
col_vali=y_valid_pd.iloc[:,-1]
y_test=col_vali.values

## 2.提取预测列的值
col_pre=y_new[:,-1]
y_test_predict=col_pre

## 3.将array列合并成df表格
compare = pd.DataFrame({
        "原数据":y_test,
    "预测数据":y_test_predict
    })
compare

## 注意:直接df形式合成,会自带原index,若是array,则index为常规序号值

在这里插入图片描述

4.2 以可视化图的形式对比测试集原始目标数据和预测目标数据

# 绘制 预测与真值结果
plt.figure(figsize=(16,8))
plt.plot(y_test, 'b-',label="True value")
plt.plot(y_test_predict, 'r--',label="Predict value")
plt.legend(loc='best')
plt.show()

在这里插入图片描述

5.保存模型

from tensorflow.keras.utils import plot_model
# 保存模型
model.save('model_MLP.h5')  # creates a HDF5 file 'my_model.h5'

#模型可视化 pip install pydot
plot_model(model, to_file='model_MLP.png', show_shapes=True)

6.加载模型并预测,以表格形式对比测试及原始目标数据和预测目标数据

## 1.提取模型进行预测
from tensorflow.keras.models import load_model
# 加载模型
model = load_model('model_MLP.h5')

## 2.预测
y_new = model.predict(x_valid)

## 3.反归一化
min_max_scaler.fit(y_valid_pd)
y_new = min_max_scaler.inverse_transform(y_new)
  • 以表格形式对比测试集原始目标数据和预测目标数据
## 1.提取原y列的值
col_vali=y_valid_pd.iloc[:,-1]
y_test=col_vali.values

## 2.提取预测列的值
col_pre=y_new[:,-1]
y_test_predict=col_pre

## 3.compare = pd.DataFrame({
        "原数据":y_test,
    "预测数据":y_test_predict
    })
compare

在这里插入图片描述

  • 3
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值