You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tzc1/代码/任务8.4 使用灰色预测和SVR构建财政收入预测模型.py

93 lines
4.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# -*- coding: utf-8 -*-
###############################################################################
####################### 任务实现 ########################
###############################################################################
# 代码 8-3这段代码的主要功能是使用灰色预测模型对时间序列数据进行预测并将结果保存到 Excel 文件中。以下是代码的逐步解析:
import numpy as np
import pandas as pd
from GM11 import GM11 # 引入自编的灰色预测函数
# 输入的数据文件
inputfile = './new_reg_data.csv'
inputfile1 = './data.csv'
new_reg_data = pd.read_csv(inputfile) # 读取经过特征选择后的数据
data = pd.read_csv(inputfile1) # 读取总的数据
# 设置索引
new_reg_data.index = range(1994, 2014)
new_reg_data.loc[2014] = None
new_reg_data.loc[2015] = None
# 需要预测的列
l = ['x1', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x13']
outputfile = './new_reg_data_GM11.xlsx'
y = list(data['y'].values) # 提取财政收入列,合并至新数据框中
y.extend([np.nan, np.nan]) # 添加2014和2015年对应的NaN值
for i in l:
f = GM11(new_reg_data.loc[range(1994, 2014), i].values)[0]
new_reg_data.loc[2014, i] = f(len(new_reg_data) - 1) # 2014年预测结果
new_reg_data.loc[2015, i] = f(len(new_reg_data)) # 2015年预测结果
new_reg_data[i] = new_reg_data[i].round(2) # 保留两位小数
# 使用 .xls 扩展名
new_reg_data['y'] = y # 添加财政收入列到new_reg_data
new_reg_data.to_excel(outputfile, index=True) # 结果输出,索引列也写入
# 显示预测结果
print('预测结果为:', new_reg_data.loc[2014:2015, :]) # 预测结果展示
# 代码 8-4
# 利用灰色预测的输出,进一步应用 SVR 模型进行建模与预测,并将结果进行保存
import pandas as pd
import numpy as np
from sklearn.svm import LinearSVR
import matplotlib.pyplot as plt
from sklearn.metrics import explained_variance_score,\
mean_absolute_error,mean_squared_error,\
median_absolute_error,r2_score
# inputfile = '../tmp/new_reg_data_GM11.xls' #灰色预测后保存的路径
inputfile = './new_reg_data_GM11.xlsx' #灰色预测后保存的路径
data = pd.read_excel(inputfile,index_col=0) #读取数据
feature = ['x1', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x13']
data_train = data.loc[range(1994,2014)].copy()#取2014年前的数据建模
data_mean = data_train.mean()
data_std = data_train.std()
data_train = (data_train - data_mean)/data_std #数据标准化
# 计算数据的均值和标准差然后对数据进行标准化处理使其均值为0标准差为1。
# 特征数据和标签数据
x_train = data_train[feature].values # 使用 .values 替代 .as_matrix()
y_train = data_train['y'].values # 使用 .values 替代 .as_matrix()
# 创建 SVR 模型实例,并使用训练数据进行拟合。
linearsvr = LinearSVR() #调用LinearSVR()函数
linearsvr.fit(x_train,y_train)
# 将数据再次进行标准化,然后用模型进行预测,并将预测值还原到原始尺度上(解标准化)。
x = ((data[feature] - data_mean[feature])/ \
# data_std[feature]).as_matrix() #预测,并还原结果。
data_std[feature]).values #预测,并还原结果。
data[u'y_pred'] = linearsvr.predict(x) * \
data_std['y'] + data_mean['y']
## SVR预测后保存的结果
# outputfile = '../tmp/new_reg_data_GM11_revenue.xls'
outputfile = './new_reg_data_GM11_revenue.xlsx'
data.to_excel(outputfile)
print('真实值与预测值分别为:',data[['y','y_pred']])
print('预测图为:',data[['y','y_pred']].plot(subplots = True,
style=['b-o','r-*']))
# 绘制真实值与预测值在同一个图形中
# 为确保中文标题能正常显示
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # 替换为可以显示中文的字体
plt.rcParams['axes.unicode_minus'] = False # 确保负号显示正常
ax = data[['y', 'y_pred']].plot(style=['r-o', 'b-*'], figsize=(10, 5))
plt.title('真实值与预测值对比') # 添加标题
plt.xlabel('时间') # 添加x轴标签
plt.ylabel('') # 添加y轴标签
# 添加图例,明确哪条线是哪个
plt.legend(['真实值', '预测值']) # 添加图例
plt.show() # 显示图形