使用线性回归模型预测国民GDP
数据准备
1. import numpy as np 2. import pandas as pd 3. import matplotlib.pyplot as plt 4. 5. plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 6. plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 7. 8. df = pd.read_excel('./tax.xlsx', index_col='年份') 9. df.head(10)
tax | GDP | |
年份 | ||
1978 | 519.28 | 3645.22 |
1979 | 537.82 | 4062.58 |
1980 | 571.70 | 4545.62 |
1981 | 629.89 | 4889.46 |
1982 | 700.02 | 5330.45 |
1983 | 775.59 | 5985.55 |
1984 | 947.35 | 7243.75 |
1985 | 2040.79 | 9040.74 |
1986 | 2090.73 | 10274.38 |
1987 | 2140.36 | 12050.62 |
数据处理
1. df.describe() 2. # 对数据进行描述分析
1. plt.figure(figsize=(10.,6)) # 设置图框大小尺寸 2. 3. plt.scatter(df.iloc[:,1], df.iloc[:,0], c='r', marker='o') 4. 5. plt.xlabel('国民生产总值') 6. plt.ylabel('税收') 7. plt.title('税收与国民生产总值') 8. 9. plt.show()
数据建模
1. np.array(df.iloc[:,1]).reshape([-1,1])#GDP 2. np.array(df.iloc[:,0]).reshape([-1,1])#tax
1. # 计算 2. 3. x = np.array(df.iloc[:, 1]).reshape([-1, 1]) # 国民生产总值 4. y = np.array(df.iloc[:, 0]).reshape([-1,1]) # 税收 5. 6. b = ((x - x.mean()) * (y - y.mean())).sum() / np.power(x - x.mean(), 2).sum() 7. a = y.mean() - b * x.mean() 8. 9. print("手工计算的公式的斜率为{} 截距为{}".format(str(b)[:8], str(a)[:8]))
1. x = np.array(df.iloc[:, 1]) # 国民生产总值 2. y = np.array(df.iloc[:, 0]) # 税收 3. cols = ['GDP'] 4. x = pd.DataFrame(x, columns=cols) 5. x
1. #利用第三方sklearn计算 2. from sklearn.linear_model import LinearRegression 3. 4. model = LinearRegression() 5. reg = model.fit(x, y) 6. #回归系数 回归截距项 7. [reg.coef_.round(4), reg.intercept_.round(4)]
绘制拟合曲线
1. #利用sklearn库函数计算拟合度R2 2. from sklearn.metrics import r2_score 3. 4. y_pred=reg.predict(x) 5. r2=r2_score(y,y_pred).round(6) 6. r2
1. #3绘制拟合曲线 2. plt.figure() 3. 4. x = np.array(df.iloc[:, 1]) # 国民生产总值 5. y = np.array(df.iloc[:, 0]) # 税收 6. 7. plt.scatter(x, y, label='actual', c='r', marker='o') 8. 9. plt.plot(x, y_pred) 10. 11. plt.xlabel('国民生产总值') 12. plt.ylabel('税收') 13. plt.title('税收与国民生产总值') 14. 15. plt.show()
回归分析是确定预测属性(数值型)与其他变量间相互依赖的定量。关系的最常用的统计学方法。包括线性回归、非线性回归、Logistic回归、岭回归、主成分回归、偏最小二乘回归等模型。