最近有一个需求,需要用到GBDT算法去实现对时序数据进行预测(回归任务),数据是从2011年1月到2020年4月份6个不同城市的房地产交易数据,由于在网上没有找到对应的基于时序数据来用GBDT算法的博客或者资料,我也去github上面找个,出现最多的是,基于特征数据对标签进行预测,实现如分类或者回归问题,基于此,想写一个关于时序数据处理的简单介绍,后面有代码和数据地址
一 数据介绍
6个城市分别是,重庆,杭州,洛阳,南充,芜湖,对于特征如下图所示: 回归任务为基于历史数据对2020年1-4月的特征数据进行预测,故一共需要预测13个特征值
二 模型训练
简单思路是把年和月作为特征,然后用GBDT学习后面特征的值(即后面13列),当然如果需要模型更鲁棒一点,可以加入其他列特征数据,对目标特征进行拟合,这里只是简单介绍,故而只解释最简单的一种。
def GBDT_train(X,Y):
#print(X.head())
#print(Y.head())
for i in range(num_of_index):#训练16个模型,即输出值
#print(Y.iloc[:200,i].head())
#x_train, x_test, y_train, y_test = train_test_split(X, Y.iloc[:200,i].astype("str").values)
x_train, x_test, y_train, y_test = train_test_split(X, Y.iloc[:,i])# 模型训练,使用GBDT算法 默认75%做训练 , 25%做测试
'''GradientBoostingRegressor参数介绍
@n_estimators: 子模型的数量,默认为100
@max_depth :最大深度 ,默认3
@min_samples_split :分裂最小样本数
@learning_rate :学习率
'''
gbr = GradientBoostingRegressor(n_estimators=200, max_depth=2, min_samples_split=2, learning_rate=0.1)
gbr.fit(x_train, y_train.ravel())
joblib.dump(gbr, name+"train_model_"+ str(i) +"_result.m") # 保存模型y_gbr = gbr.predict(x_train)
y_gbr1 = gbr.predict(x_test)
acc_train = gbr.score(x_train, y_train)
acc_test = gbr.score(x_test, y_test)
print(name+"train_model_"+ str(i) +"_result.m"+'训练准确率',acc_train)
print(name+"train_model_"+ str(i) +"_result.m"+'验证准确率',acc_test)
三 模型预测
用了里面自带的方式,这里没什么好说的
# 加载模型并预测
def GBDT_Predict( ):X_Pred = [2020,4]
print("预测:2020-4")
X_Pred = np.reshape(X_Pred, (1, -1))
for i in range(num_of_index):
gbr = joblib.load(name+"train_model_"+ str(i) +"_result.m") # 加载模型
#test_data = pd.read_csv(r"./data_test.csv")
test_y = gbr.predict(X_Pred)
test_y = np.reshape(test_y, (1, -1))
print(test_y)
四 实验结果
实验结果还是不错的,如果加入其他特征效果和泛化能力可能会更好!
!!!!代码和数据在这里!!!