1. 描述性统计分析
# 对各属性进行描述性统计分析 def statisticAnalysis(): inputfile = '../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)) # 保留两位
2.相关系数矩阵和热力图
# 求解原始数据的Pearson相关系数矩阵 def correlationCoefficientMatrix(data): inputfile = '../data/data.csv' # 输出的数据文件 data = pd.read_csv(inputfile) # 读数据 corr = data.corr(method='pearson') # 计算相关系数矩阵 print("相关系数矩阵为:\n", np.round(corr, 2)) # 保留两位 return corr # 绘制相关性热力图 def thermodynamic(corr): plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签 plt.rcParams['axes.unicode_minus']=False plt.subplots(figsize=(10, 10)) sns.heatmap(corr, annot=True, vmax=1, square=True, cmap="Blues_r") plt.title("相关性热力图 3105") plt.show() plt.close()
3.构建模型并预测
# 构建灰色预测模型并预测 def grey(): sys.path.append("D:/作业/数据挖掘/tmp") inputfile1 = "../data/new_reg_data.csv" inputfile2 = "../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 cols = ['x1', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x13'] for i in cols: 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 = '../tmp/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,:]) # 构建支持向量回归预测模型 def SVR(): from sklearn.svm import LinearSVR inputfile = '../tmp/new_reg_data_GM11.xls' data = pd.read_excel(inputfile) feature = ['x1', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x13'] data.index = range(1994, 2016) data_train = data.loc[range(1994, 2014)].copy() data_mean = data_train.mean() data_std = data_train.std() data_train = (data_train - data_mean)/data_std x_train = data_train[feature].to_numpy() y_train = data_train['y'].to_numpy() linearsvr = LinearSVR() linearsvr.fit(x_train, y_train) x = ((data[feature] - data_mean[feature])/data_std[feature]).to_numpy() data[u'y_pred'] = linearsvr.predict(x) * data_std['y'] + data_mean['y'] # outputfile = '../tmp/new_reg_data_GM11_revenue.xls' # data.to_excel(outputfile) print("真实值与预测值分别为:\n",data[['y', 'y_pred']]) plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签 plt.rcParams['axes.unicode_minus'] = False fig = data[['y', 'y_pred']].plot(subplots = True,style=['b-o', 'r-*']) plt.title("3105") plt.show()
GM(1,1)
1 def GM11(x0): # 自定义灰色预测函数 2 import numpy as np 3 x1 = x0.cumsum() # 1-AGO序列 4 z1 = (x1[:len(x1)-1] + x1[1:])/2.0 # 紧邻均值(MEAN)生成序列 5 z1 = z1.reshape((len(z1),1)) 6 B = np.append(-z1, np.ones_like(z1), axis = 1) 7 Yn = x0[1:].reshape((len(x0)-1, 1)) 8 [[a],[b]] = np.dot(np.dot(np.linalg.inv(np.dot(B.T, B)), B.T), Yn) # 计算参数 9 f = lambda k: (x0[0]-b/a)*np.exp(-a*(k-1))-(x0[0]-b/a)*np.exp(-a*(k-2)) # 还原值 10 delta = np.abs(x0 - np.array([f(i) for i in range(1,len(x0)+1)])) 11 C = delta.std()/x0.std() 12 P = 1.0*(np.abs(delta - delta.mean()) < 0.6745*x0.std()).sum()/len(x0) 13 return f, a, b, x0[0], C, P # 返回灰色预测函数、a、b、首项、方差比、小残差概率
完整代码:
1 import pandas as pd 2 import numpy as np 3 import matplotlib.pyplot as plt 4 import seaborn as sns 5 import sys 6 from GM11 import GM11 7 8 9 inputfile = '../data/data.csv' # 输出的数据文件 10 data = pd.read_csv(inputfile) # 读数据 11 12 13 # 对各属性进行描述性统计分析 14 def statisticAnalysis(data): 15 # 最小值、最大值、均值、标准差 16 description = [data.min(), data.max(), data.mean(), data.std()] 17 18 # 将结果存入数据框 19 description = pd.DataFrame(description, index=["Min", "Max", "Mean", "STD"]).T 20 print("描述性统计结果:\n", np.round(description, 2)) # 保留两位 21 22 23 # 求解原始数据的Pearson相关系数矩阵 24 def correlationCoefficientMatrix(data): 25 corr = data.corr(method='pearson') # 计算相关系数矩阵 26 print("相关系数矩阵为:\n", np.round(corr, 2)) # 保留两位 27 return corr 28 29 30 # 绘制相关性热力图 31 def thermodynamic(corr): 32 plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签 33 plt.rcParams['axes.unicode_minus']=False 34 plt.subplots(figsize=(10, 10)) 35 sns.heatmap(corr, annot=True, vmax=1, square=True, cmap="Blues_r") 36 plt.title("相关性热力图 3105") 37 plt.show() 38 plt.close() 39 40 41 # 构建灰色预测模型并预测 42 def grey(): 43 sys.path.append("D:/作业/数据挖掘/tmp") 44 45 inputfile1 = "../data/new_reg_data.csv" 46 inputfile2 = "../data/data.csv" 47 new_reg_data = pd.read_csv(inputfile1) 48 data = pd.read_csv(inputfile2) 49 new_reg_data.index = range(1994, 2014) 50 new_reg_data.loc[2014] = None 51 new_reg_data.loc[2015] = None 52 cols = ['x1', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x13'] 53 for i in cols: 54 f = GM11(new_reg_data.loc[range(1994, 2014), i].values)[0] 55 new_reg_data.loc[2014, i] = f(len(new_reg_data)-1) # 2014年预测结果 56 new_reg_data.loc[2015, i] = f(len(new_reg_data)) # 2015年预测结果 57 new_reg_data[i] = new_reg_data[i].round(2) 58 59 outputfile = '../tmp/new_reg_data_GM11.xls' # 灰色预测后保存路径 60 y = list(data['y'].values) 61 y.extend([np.nan, np.nan]) 62 new_reg_data['y'] = y 63 new_reg_data.to_excel(outputfile) 64 print("预测结果为:\n",new_reg_data.loc[2014:2015,:]) 65 66 # 构建支持向量回归预测模型 67 def SVR(): 68 from sklearn.svm import LinearSVR 69 70 inputfile = '../tmp/new_reg_data_GM11.xls' 71 data = pd.read_excel(inputfile) 72 feature = ['x1', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x13'] 73 data.index = range(1994, 2016) 74 data_train = data.loc[range(1994, 2014)].copy() 75 data_mean = data_train.mean() 76 data_std = data_train.std() 77 data_train = (data_train - data_mean)/data_std 78 x_train = data_train[feature].to_numpy() 79 y_train = data_train['y'].to_numpy() 80 81 linearsvr = LinearSVR() 82 linearsvr.fit(x_train, y_train) 83 x = ((data[feature] - data_mean[feature])/data_std[feature]).to_numpy() 84 85 data[u'y_pred'] = linearsvr.predict(x) * data_std['y'] + data_mean['y'] 86 # outputfile = '../tmp/new_reg_data_GM11_revenue.xls' 87 # data.to_excel(outputfile) 88 89 print("真实值与预测值分别为:\n",data[['y', 'y_pred']]) 90 91 plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签 92 plt.rcParams['axes.unicode_minus'] = False 93 94 fig = data[['y', 'y_pred']].plot(subplots = True,style=['b-o', 'r-*']) 95 plt.title("3105") 96 plt.show() 97 98 99 statisticAnalysis(data) 100 corr = correlationCoefficientMatrix(data) 101 thermodynamic(corr) 102 103 grey() 104 105 SVR()
标签:plt,预测,因数,train,财政收入,np,new,data,reg From: https://www.cnblogs.com/lwqbk/p/17182150.html