000

对数据选择合适的时序模型和合适的预测方法

import numpy as np
import pandas as pd

inputfile = 'C:/Users/Administrator/Desktop/data/data.csv' 
data = pd.read_csv(inputfile)

# 描述性统计分析
description = [data.min(), data.max(), data.mean(), data.std()]
description = pd.DataFrame(description, index = ['Min', 'Max', 'Mean', 'STD']).T
print('描述性统计结果:\n',np.round(description, 2))

# 相关性分析
corr = data.corr(method = 'pearson')
print('相关系数矩阵为:\n',np.round(corr, 2))

# 绘制热力图
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
plt.subplots(figsize=(10, 10))
sns.heatmap(corr, annot=True, vmax=1, square=True, cmap="Greens")
plt.title('相关性热力图')
plt.show()
plt.close

  结果

 

 

 

 

 

 

灰色预测算法+SVR算法与AERIMA预测财政

灰色预测算法+SVR算法

#lasso
import numpy as np
import pandas as pd
from sklearn.linear_model import Lasso

inputfile ='C:/Users/Administrator/Desktop/data/data.csv' # 输入的数据文件
data = pd.read_csv(inputfile) # 读取数据
lasso = Lasso(1000) # 调用Lasso()函数,设置λ的值为1000
lasso.fit(data.iloc[:,0:14],data['y'])
print('相关系数为:',np.round(lasso.coef_,5)) # 输出结果,保留五位小数

print('相关系数非零个数为:',np.sum(lasso.coef_ != 0)) # 计算相关系数非零的个数

mask = lasso.coef_ != 0 # 返回一个相关系数是否为零的布尔数组
print('相关系数是否为零:',mask)

outputfile ='C:/Users/Administrator/Desktop/new_reg_data.csv' # 输出的数据文件
new_reg_data = data.iloc[:, mask] # 返回相关系数非零的数据
new_reg_data.to_csv(outputfile) # 存储数据
print('输出数据的维度为:',new_reg_data.shape) # 查看输出数据的维度
#GM11
def GM11(x0): #自定义灰色预测函数
import numpy as np
x1 = x0.cumsum() #1-AGO序列
z1 = (x1[:len(x1)-1] + x1[1:])/2.0 #紧邻均值(MEAN)生成序列
z1 = z1.reshape((len(z1),1))
B = np.append(-z1, np.ones_like(z1), axis = 1)
Yn = x0[1:].reshape((len(x0)-1, 1))
[[a],[b]] = np.dot(np.dot(np.linalg.inv(np.dot(B.T, B)), B.T), Yn) #计算参数
f = lambda k: (x0[0]-b/a)*np.exp(-a*(k-1))-(x0[0]-b/a)*np.exp(-a*(k-2)) #还原值
delta = np.abs(x0 - np.array([f(i) for i in range(1,len(x0)+1)]))
C = delta.std()/x0.std()
P = 1.0*(np.abs(delta - delta.mean()) < 0.6745*x0.std()).sum()/len(x0)
return f, a, b, x0[0], C, P #返回灰色预测函数、a、b、首项、方差比、小残差概率

#灰色预测
import sys
sys.path.append('code') # 设置路径
import numpy as np
import pandas as pd
from GM11 import GM11 # 引入自编的灰色预测函数

inputfile1 = 'C:/Users/Administrator/Desktop/new_reg_data.csv' # 输入的数据文件
inputfile2 = 'C:/Users/Administrator/Desktop/data/data.csv' # 输入的数据文件
new_reg_data = pd.read_csv(inputfile1) # 读取经过特征选择后的数据
data = pd.read_csv(inputfile2) # 读取总的数据
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']
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) # 保留两位小数
outputfile = 'C:/Users/Administrator/Desktop/new_reg_data_GM11.xls' # 灰色预测后保存的路径
y = list(data['y'].values) # 提取财政收入列,合并至新数据框中
y.extend([np.nan,np.nan])
new_reg_data['y'] = y
new_reg_data.to_excel(outputfile) # 结果输出
print('预测结果为:\n',new_reg_data.loc[2014:2015,:]) # 预测结果展示

#预测模型
import matplotlib.pyplot as plt
from sklearn.svm import LinearSVR
import pandas as pd

inputfile = 'C:/Users/Administrator/Desktop/new_reg_data_GM11.xls' # 灰色预测后保存的路径
data = pd.read_excel(inputfile) # 读取数据
feature = ['x1', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x13'] # 属性所在列
data_train = data.iloc[0:20].copy() # 取2014年前的数据建模
data_mean = data_train.mean()
data_std = data_train.std()
data_train = (data_train - data_mean)/data_std # 数据标准化
x_train = data_train[feature].values # 属性数据
y_train = data_train['y'].values # 标签数据

linearsvr = LinearSVR() # 调用LinearSVR()函数
linearsvr.fit(x_train,y_train)
x = ((data[feature] - data_mean[feature])/data_std[feature]).values # 预测,并还原结果。
data['y_pred'] = linearsvr.predict(x) * data_std['y'] + data_mean['y']
outputfile = 'C:/Users/Administrator/Desktop/new_reg_data_GM11_revenue.xls' # SVR预测后保存的结果
data.to_excel(outputfile)

print('真实值与预测值分别为:\n',data[['y','y_pred']])

fig = data[['y','y_pred']].plot(subplots = True, style=['b-o','r-*']) # 画出预测结果图
plt.show()

结果

 

 

 

 

ARIMA

import pandas as pd
# 参数初始化
discfile = 'C:/Users/Administrator/Desktop/data/data.csv' 
# 读取数据
data = pd.read_csv(discfile)
# 时序图
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
data.plot()
plt.show()
# 自相关图
from statsmodels.graphics.tsaplots import plot_acf
plot_acf(data['y']).show()
# 平稳性检测
from statsmodels.tsa.stattools import adfuller as ADF
print('原始序列的ADF检验结果为:', ADF(data['y']))
# 返回值依次为adf、pvalue、usedlag、nobs、critical values、icbest、regresults、resstore
# 差分后的结果
D_data = data.diff().dropna()
feature = ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10', 'x11', 'x12', 'x13', 'y']  # 属性所在列
D_data.columns = feature
D_data.plot()  # 时序图
plt.show()
plot_acf(D_data['y']).show()  # 自相关图
from statsmodels.graphics.tsaplots import plot_pacf
plot_pacf(D_data['y']).show()  # 偏自相关图
print('差分序列的ADF检验结果为:', ADF(D_data['y']))  # 平稳性检测
# 白噪声检验
from statsmodels.stats.diagnostic import acorr_ljungbox
print('差分序列的白噪声检验结果为:', acorr_ljungbox(D_data['y'], lags=1))  # 返回统计量和p值
from statsmodels.tsa.arima_model import ARIMA
# 定阶
data['y'] = data['y'].astype(float)
pmax = int(len(D_data)/10)  # 一般阶数不超过length/10
qmax = int(len(D_data)/10)  # 一般阶数不超过length/10
bic_matrix = []  # BIC矩阵
for p in range(pmax+1):
  tmp = []
  for q in range(qmax+1):
    try:  # 存在部分报错,所以用try来跳过报错。
      tmp.append(ARIMA(data['y'], (p,1,q)).fit().bic)
    except:
      tmp.append(None)
  bic_matrix.append(tmp)

bic_matrix = pd.DataFrame(bic_matrix)  # 从中可以找出最小值

p,q = bic_matrix.stack().idxmin()  # 先用stack展平,然后用idxmin找出最小值位置。
print('BIC最小的p值和q值为:%s、%s' %(p,q))
model = ARIMA(data['y'], (p,1,q)).fit()  # 建立ARIMA(0, 1, 1)模型
print('模型报告为:\n', model.summary2())
print('预测未来2年,其预测结果、标准误差、置信区间如下:\n', model.forecast(2))

  结果

 

 

 

 

 

 

 

posted @ 2022-04-05 02:02  youto有病  阅读(109)  评论(0编辑  收藏  举报