1. 回归分析
1.1. 一元线性回归
一元线性回归可以用来分析一个自变量和因变量之间的关系,通过分散的样本点来得到自变量和因变量之间的线性关系,通过最小二乘法来获得线性回归的系数,计算之后要对获得的回归方程进行检验。
P19 例2.1.1:
import numpy as np
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
def linear_regression(x, y):
plt.figure()
plt.scatter(x, y, alpha=0.5)
plt.title('weight(y) and temperature(x)')
plt.xlabel('temperature')
plt.ylabel('weight')
lrModel = LinearRegression()
# 求解模型
lrModel.fit(x, y)
# 对x进行预测
y0 = lrModel.predict(x)
plt.plot(x, y0)
plt.show()
alpha = lrModel.coef_
# 获得斜率
beta = lrModel.intercept_
# 获得截距
def test():
x = np.array([3.5, 1.8, 2.4, 3.0, 3.5, 3.9, 4.4, 4.8, 5.0])
y = np.array([8.5, 2.57, 3.0, 5.3, 8.9, 11.69, 13.1, 13.6, 13.3])
linear_regression(x.reshape([len(x), 1]), y.reshape([len(y), 1]))
test()
使用了sklearn库中的linear_model,其中需注意在使用fit方法时,传参数需要二维数组。
结果:
R 2 = 0.9448786943846488 R^2 = 0.9448786943846488 R2=0.9448786943846488
y = 3.99 x − 5.43 y=3.99x-5.43 y=3.99x−5.43
1.2. 检验
在获得模型之后要对模型进行检验,我们的模型拟合程度如何(R2)?我们要检验的使整个模型是否能显著预测因变量的变化(F检验)?每个自变量是否能显著预测因变量的变化(t检验)?
1.2.1 R2 - - - 模型拟合程度
通过计算模型对自变量存在的情况下的因变量的和平均值的差异的解释情况,来判断模型的拟合程度,即计算预测值和平均值差值平方之和(SSA)和实际值和平均值差值的平方之和(SST)的比值。SSA表示对实际值和平均值差异的解释情况,SST表示实际值和平均值之间的差异大小。通过比值可以看出模型对差异的解释情况从而判断模型的拟合情况,也就是R2。
1.2.2 F检验 - - - 能否显著预测y值
计算SSA和SSE的比值,所得结果小于5%即线性关系明显。
1.2.3 t检验 - - - 回归系数是否显著
计算Pr要小于0.05即可证明显著。
import numpy as np
import pandas as pd
from statsmodels.formula.api import ols
x = np.array([3.5, 1.8, 2.4, 3.0, 3.5, 3.9, 4.4, 4.8, 5.0])
y = np.array([8.5, 2.57, 3.0, 5.3, 8.9, 11.69, 13.1, 13.6, 13.3])
data = pd.DataFrame({
'x': x, 'y': y})
model = ols('y~x', data).fit()
print(model.summary())
使用statsmodels可以更简便的完成回归以及检验,结果如下:
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.945
Model: OLS Adj. R-squared: 0.937
Method: Least Squares F-statistic: 120.0
Date: Tue, 21 Jan 2020 Prob (F-statistic): 1.17e-05
Time: 23:19:13 Log-Likelihood: -12.533
No. Observations: 9 AIC: 29.07
Df Residuals: 7 BIC: 29.46
Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept -5.4375 1.358 -4.003 0.005 -8.649 -2.226
x 3.9906 0.364 10.954 0.000 3.129 4.852
==============================================================================
Omnibus: 1.239 Durbin-Watson: 1.329
Prob(Omnibus): 0.538 Jarque-Bera (JB): 0.658
Skew: 0.026 Prob(JB): 0.720
Kurtosis: 1.677 Cond. No. 14.7
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
Process finished with exit code 0
可以得到,R2=0.945,说明模型拟合效果显著,F值为120,p值远小于0.05因此通过F检验,自变量和因变量之间存在显著的线性关系,两个参数均通过t检验,所得Pr小于0.05.
参数说明:
coef 为对应的参数所求结果,比如在这个线性回归中-5.4375即为截距,3.9906为自变量对应的斜率
1.3. 一元非线性回归
在实际问题中许多自变量和因变量之间的关系并不成线性关系,无法做线性回归,但是我们可以通过数学处理实现线性回归,下面几组数据进行处理。
》》》P22 例2.1.2
画图观察:
x = [1, 2, 3, 4, 4, 6, 6, 8, 8, 9]
y = [1.85, 1.37, 1.02, 0.75, 0.56, 0.41, 0.31, 0.23, 0.17, 0.10]
plt.figue()
plt.scatter(x, y, alpha=0.5)
plt.show()
由图推测可能为一下关系:
y = a x + b y=ax+b y=ax+b
y = a + b x y=a+\frac{b}{x} y=a+xb
y = a x