[开源] 基于RF(随机森林)算法的时间序列预测模型python代码

整理了基于RF(随机森林)算法的时间序列预测模型python代码,免费分享给大家,记得点赞哦

预测指标如下:

RMSE为:0.066 
MAE为:0.050 
R2为:0.804 
 

#!/usr/bin/env python
# coding: utf-8


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import preprocessing
from math import sqrt
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score
import math
from numpy import concatenate

feanum=1
window=5
Ra = 0.8
df1=pd.read_csv('shao - 单.csv', usecols=[1]) #读取数据
train_d, test_d = df1[0:int(len(df1)*Ra)], df1[int(len(df1)*Ra):]


min_max_scaler = preprocessing.MinMaxScaler()
df0=min_max_scaler.fit_transform(df1)
df = pd.DataFrame(df0, columns=df1.columns)


stock=df
seq_len=window
amount_of_features = len(stock.columns)#有几列
data = stock.values #pd.DataFrame(stock) 表格转化为矩阵
sequence_length = seq_len + 1#序列长度+1
result = []
for index in range(len(data) - sequence_length):#循环 数据长度-时间窗长度 次
    result.append(data[index: index + sequence_length])#第i行到i+5
result = np.array(result)#得到样本,样本形式为 window*feanum

cut=len(test_d)
train = result[:-cut, :]
x_train = train[:, :-1]
y_train = train[:, -1][:,-1]
x_test = result[-cut:, :-1]
y_test = result[-cut:, -1][:,-1]
X_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], amount_of_features))
X_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], amount_of_features)) 


X_train=X_train.reshape(len(X_train),window)
y_train=y_train.reshape(len(X_train))
X_test=X_test.reshape(cut,window)
y_test=y_test.reshape(cut)


rf = RandomForestRegressor(n_estimators=1500, max_depth=None, min_samples_split=50, random_state=0)
model = rf.fit(X_train, y_train)


#在训练集上的拟合结果
y_train_predict=model.predict(X_train)
#在测试集上的预测
y_test_predict=model.predict(X_test)


X = pd.DataFrame(y_test)
Y = pd.DataFrame(y_test_predict)
X = min_max_scaler.inverse_transform(X)
Y = min_max_scaler.inverse_transform(Y)

testScore = math.sqrt(mean_squared_error(X, Y))
print('RMSE为:%.3f ' %(testScore))
testScore = mean_absolute_error(X, Y)
print('MAE为:%.3f ' %(testScore))
testScore = r2_score(X, Y)
print('R2为:%.3f ' %(testScore))



plt.figure(figsize=(10, 4),dpi=150)
plt.plot(X, label="Actual", color='red',linewidth=4)
plt.plot(Y, color='blue',label='Prediction',linewidth=2.5,linestyle="--")
plt.title('Prediction', size=15)
plt.ylabel('AQI',size=15)
plt.xlabel('time/day',size=15)
plt.legend()
plt.show()





更多时间序列预测代码:时间序列预测算法全集合--深度学习

  • 14
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值