当前位置:   article > 正文

python代码Bi-LSTM、CNN-BiLSTM_bi-lstm热失控python代码

bi-lstm热失控python代码

一、Bi-LSTM

时间序列单变量预测

模型

  1. import numpy as np
  2. import tensorflow as tf
  3. gpus = tf.config.list_physical_devices("GPU")
  4. if gpus:
  5. tf.config.experimental.set_memory_growth(gpus[0], True) #设置GPU显存用量按需使用
  6. tf.config.set_visible_devices([gpus[0]],"GPU")
  7. from sklearn.preprocessing import MinMaxScaler
  8. from sklearn.metrics import mean_squared_error
  9. from math import sqrt
  10. import matplotlib.pyplot as plt
  11. import pandas as pd
  12. # 支持中文
  13. plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
  14. plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
  15. # 确保结果尽可能重现
  16. from numpy.random import seed
  17. seed(1)
  18. tf.random.set_seed(1)
  19. #导入数据
  20. oil=pd.read_csv('D:/April/postgraduate/研1/课程/时间序列分析/期末论文/china_oil.csv')
  21. data=oil
  22. oil
  23. from tensorflow.keras.regularizers import l2
  24. # 数据归一化
  25. scaler = MinMaxScaler(feature_range=(-1, 1))
  26. data_normalized = scaler.fit_transform(data.values.reshape(-1, 1)).reshape(-1)
  27. # 创建时间窗口
  28. def create_sequence_data(data, time_steps):
  29. sequences = []
  30. labels = []
  31. for i in range(len(data) - time_steps):
  32. seq = data[i:i+time_steps]
  33. label = data[i+time_steps:i+time_steps+1]
  34. sequences.append(seq)
  35. labels.append(label)
  36. return np.array(sequences), np.array(labels)
  37. time_steps = 3 # 可以根据需要调整时间窗口大小
  38. X, y = create_sequence_data(data_normalized, time_steps)
  39. # 划分训练集和验证集
  40. val_size = 100
  41. X_train, X_val = X[:-val_size], X[-val_size:]
  42. y_train, y_val = y[:-val_size], y[-val_size:]
  43. # 构建Bi-LSTM模型
  44. model = tf.keras.Sequential([
  45. tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(50, activation='relu', kernel_regularizer=l2(0.01)), input_shape=(X_train.shape[1], 1)),
  46. tf.keras.layers.Dense(1)
  47. ])
  48. model.compile(optimizer='adam', loss='mse')
  49. # 训练模型
  50. history = model.fit(X_train, y_train,
  51. epochs=20,
  52. batch_size=32,
  53. validation_data=(X_val, y_val),
  54. verbose=2)
  55. # 进行预测
  56. predicted = model.predict(X_val)
  57. # 反归一化
  58. predicted = scaler.inverse_transform(predicted)
  59. y_val_original = scaler.inverse_transform(y_val)

测试集效果图

  1. # 绘制预测结果
  2. plt.plot(predicted, label='Predicted')
  3. plt.plot(y_val_original, label='True')
  4. plt.title('price - Predicted vs True')
  5. plt.legend()
  6. plt.show()

loss曲线

  1. # 获取训练过程中的损失值
  2. train_loss = history.history['loss']
  3. val_loss = history.history['val_loss']
  4. # 绘制损失曲线
  5. plt.plot(train_loss, label='Training Loss')
  6. plt.plot(val_loss, label='Validation Loss')
  7. plt.title('price Training and Validation Loss')
  8. plt.xlabel('Epoch')
  9. plt.ylabel('Loss')
  10. plt.legend()
  11. plt.show()

模型评估

  1. from sklearn.metrics import mean_squared_error, mean_absolute_error
  2. from sklearn.utils import check_array
  3. from sklearn.metrics import r2_score
  4. # 使用RMSE评估模型性能
  5. rmse = sqrt(mean_squared_error(y_val_original, predicted))
  6. print(f'MSE: {round(rmse,4)}')
  7. # 计算MAPE
  8. def mean_absolute_percentage_error(y_true, y_pred):
  9. y_true, y_pred = np.array(y_true), np.array(y_pred)
  10. return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
  11. mape = mean_absolute_percentage_error(y_val_original, predicted)
  12. print(f'MAPE: {round(mape,4)}')
  13. # 计算R-squared (R2)
  14. r2 = r2_score(y_val_original, predicted)
  15. print(f'R2: {round(r2,4)}')
  16. # 使用RMSE评估模型性能
  17. rmse = sqrt(mean_squared_error(y_val_original, predicted))
  18. print(f'验证集RMSE: {round(rmse,4)}')
  19. from sklearn.metrics import mean_absolute_error
  20. # 计算MAE
  21. mae = mean_absolute_error(y_val_original, predicted)
  22. print("Mean Absolute Error: ", mae)

二、CNN-BiLSTM

模型

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. from sklearn.preprocessing import MinMaxScaler
  5. from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
  6. from tensorflow.keras.models import Sequential
  7. from tensorflow.keras.layers import Conv1D, MaxPooling1D, Bidirectional, LSTM, Dense, Flatten
  8. # 假设有一个名为data的DataFrame,其中包含你的电力负荷时间序列数据
  9. # 数据归一化
  10. scaler = MinMaxScaler(feature_range=(-1, 1))
  11. data_normalized = scaler.fit_transform(data.values.reshape(-1, 1)).reshape(-1)
  12. # 创建时间窗口
  13. def create_sequence_data(data, time_steps):
  14. sequences = []
  15. labels = []
  16. for i in range(len(data) - time_steps):
  17. seq = data[i:i+time_steps]
  18. label = data[i+time_steps]
  19. sequences.append(seq)
  20. labels.append(label)
  21. return np.array(sequences), np.array(labels)
  22. time_steps =10 # 可以根据需要调整时间窗口大小
  23. X, y = create_sequence_data(data_normalized, time_steps)
  24. # 划分训练集和验证集
  25. val_size = 100 # 取后200个数据
  26. X_train, X_val = X[:-val_size], X[-val_size:]
  27. y_train, y_val = y[:-val_size], y[-val_size:]
  28. # 调整 X_train 和 X_val 的形状以匹配模型输入
  29. X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
  30. X_val = X_val.reshape(X_val.shape[0], X_val.shape[1], 1)
  31. # 构建CNN-BiLSTM模型
  32. model = Sequential([
  33. Conv1D(filters=64, kernel_size=1, activation='relu', input_shape=(X_train.shape[1], 1)),
  34. MaxPooling1D(pool_size=2),
  35. Bidirectional(LSTM(128, activation='tanh')),
  36. Dense(1)
  37. ])
  38. model.compile(optimizer='adam', loss='mse')
  39. # 训练模型
  40. history = model.fit(X_train, y_train,
  41. epochs=50,
  42. batch_size=32,
  43. validation_data=(X_val, y_val),
  44. verbose=2)
  45. # 进行预测
  46. predicted = model.predict(X_val)
  47. # 反归一化
  48. predicted = scaler.inverse_transform(predicted)
  49. y_val_original = scaler.inverse_transform(y_val)

loss

  1. # 绘制损失曲线
  2. plt.plot(history.history['loss'], label='Training Loss')
  3. plt.plot(history.history['val_loss'], label='Validation Loss')
  4. plt.title('Training and Validation Loss')
  5. plt.xlabel('Epoch')
  6. plt.ylabel('Loss')
  7. plt.legend()
  8. plt.show()

测试集效果

  1. # 绘制预测结果
  2. plt.plot(y_val_original, label='True')
  3. plt.plot(predicted, label='Predicted')
  4. plt.title('Validation Set - True vs Predicted')
  5. plt.xlabel('Time')
  6. plt.ylabel('Power Load')
  7. plt.legend()
  8. plt.show()

模型评估

  1. # 计算模型评估指标
  2. rmse = np.sqrt(mean_squared_error(y_val_original, predicted))
  3. mape = np.mean(np.abs((y_val_original - predicted) / y_val_original))
  4. r2 = r2_score(y_val_original, predicted)
  5. # 打印模型评估指标
  6. print(f'Root Mean Squared Error (RMSE): {rmse:.4f}')
  7. print(f'Mean Absolute Percentage Error (MAPE): {mape:.4f}')
  8. print(f'R-squared (R2): {r2:.2f}')
  9. from sklearn.metrics import mean_absolute_error
  10. # 计算MAE
  11. mae = mean_absolute_error(y_val_original, predicted)
  12. print("Mean Absolute Error: ", mae)

三、copula相关系数

  1. import numpy as np
  2. from scipy.stats import kendalltau
  3. from sklearn.neighbors import KernelDensity
  4. ##函数
  5. def calculate_kendall_tau(X, Y, bandwidth=1.0, kernel='gaussian', sample_size=len(data), random_seed=45):
  6. """
  7. 计算两个变量之间的Kendall Tau相关系数。
  8. 参数:
  9. - X: 第一个变量的数据
  10. - Y: 第二个变量的数据
  11. - bandwidth: 核密度估计的带宽
  12. - kernel: 核函数的类型
  13. - sample_size: 从估计的分布中生成样本的大小,默认为输入数据的大小
  14. - random_seed: 随机种子,用于生成样本
  15. 返回:
  16. - kendall_tau: Kendall Tau相关系数
  17. """
  18. # 将变量堆叠成一个2D数组
  19. data = np.column_stack((X, Y))
  20. # 拟合核密度估计模型
  21. kde = KernelDensity(bandwidth=bandwidth, kernel=kernel)
  22. kde.fit(data)
  23. # 从估计的分布中生成样本
  24. if sample_size is None:
  25. sample_size = len(data)
  26. if random_seed is not None:
  27. np.random.seed(random_seed)
  28. copula_samples = kde.sample(sample_size)
  29. # 计算Kendall Tau相关系数
  30. kendall_tau, _ = kendalltau(copula_samples[:, 0], copula_samples[:, 1])
  31. return kendall_tau

举例

  1. no2=data['no2']
  2. pm2_5=data['pm2_5']
  3. pm10=data['pm10']
  4. co=data['co']
  5. o3=data['o3']
  6. so2=data['so2']
  7. # 示例用法
  8. # 注意:请替换下面的 X_data 和 Y_data 为你的实际数据
  9. result = calculate_kendall_tau(no2, Y)
  10. print(f'no2 Kendall Tau 相关系数: {result:.2f}')

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/327745
推荐阅读
相关标签
  

闽ICP备14008679号