Python实现基于PCA和随机森林的能源消耗预测模型
Python实现基于PCA和随机森林的能源消耗预测模型
本案例展示如何使用Python构建一个能源消耗预测模型。模型采用主成分分析(PCA)进行特征降维,并结合随机森林回归算法进行预测。
1. 数据准备
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
# 成分数据矩阵
data = np.array([[0.758, 0.171, 0.049, 0.022],
[0.758, 0.172, 0.047, 0.023],
[0.762, 0.17, 0.047, 0.021],
[0.762, 0.17, 0.047, 0.021],
[0.76, 0.171, 0.047, 0.021],
[0.762, 0.166, 0.051, 0.021],
[0.761, 0.171, 0.048, 0.02],
[0.757, 0.175, 0.049, 0.019],
[0.747, 0.182, 0.052, 0.019],
[0.75, 0.174, 0.057, 0.019],
[0.746, 0.175, 0.061, 0.018],
[0.747, 0.18, 0.055, 0.018],
[0.715, 0.204, 0.062, 0.017],
[0.696, 0.215, 0.067, 0.022],
[0.68, 0.232, 0.066, 0.022],
[0.661, 0.246, 0.068, 0.025],
[0.653, 0.243, 0.077, 0.027],
[0.661, 0.234, 0.078, 0.027],
[0.702, 0.201, 0.074, 0.023],
[0.702, 0.199, 0.076, 0.023],
[0.724, 0.178, 0.074, 0.024],
[0.724, 0.175, 0.074, 0.027],
[0.725, 0.17, 0.075, 0.03],
[0.715, 0.167, 0.084, 0.034],
[0.716, 0.164, 0.085, 0.035],
[0.692, 0.174, 0.094, 0.04],
[0.702, 0.168, 0.084, 0.046],
[0.685, 0.17, 0.097, 0.048],
[0.674, 0.171, 0.102, 0.053],
[0.658, 0.173, 0.113, 0.056],
[0.638, 0.184, 0.12, 0.058],
[0.622, 0.187, 0.13, 0.061],
[0.606, 0.189, 0.136, 0.069],
[0.59, 0.189, 0.145, 0.076],
[0.577, 0.19, 0.153, 0.08],
[0.569, 0.188, 0.159, 0.084],
[0.559, 0.186, 0.167, 0.088],
[0.562, 0.179, 0.175, 0.084]])
# 构建特征矩阵
feature_matrix = np.zeros((len(data) - 1, len(data[0]) - 1))
for i in range(len(data) - 1):
feature_matrix[i] = data[i, 1:] # 使用第2、3、4列作为特征矩阵
# 构建特征矩阵的DataFrame
df = pd.DataFrame(feature_matrix, columns=['Petroleum', 'Others', 'Gas'])
# 目标变量
target = data[1:, 0] # 使用第一列作为目标变量
# 数据归一化
scaler = MinMaxScaler()
df_scaled = scaler.fit_transform(df)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(df_scaled, target, test_size=0.13, random_state=42)
# 构建TSK模型管道
model = Pipeline([
('pca', PCA(n_components=2)),
('regressor', RandomForestRegressor(n_estimators=100))
])
# 拟合模型
model.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = model.predict(X_test)
# 计算CRMSE和CMAPE
crmse = np.sqrt(mean_squared_error(y_test, y_pred))
cmape = np.mean(np.abs((y_test - y_pred) / y_test)) * 100
print('CRMSE:', crmse)
print('CMAPE:', cmape)
2. 模型构建与训练
代码中使用Pipeline构建了一个机器学习流水线,包含PCA降维和随机森林回归两个步骤。
3. 模型评估
使用均方根误差(CRMSE)和平均绝对百分比误差(CMAPE)评估模型的预测性能。
注意:
- 代码中已修复了特征矩阵和目标变量样本数量不一致的问题。
- 可以根据实际情况调整模型参数,例如PCA的n_components和随机森林的n_estimators。
- 可以使用其他指标评估模型性能,例如R方值等。
希望以上内容能够帮助你更好地理解和应用PCA和随机森林算法进行能源消耗预测。
原文地址: http://www.cveoy.top/t/topic/mBI 著作权归作者所有。请勿转载和采集!