GIS之时空数据分析

Python 线性回归-普通最小二乘回归法

2019-12-16  本文已影响0人  王叽叽的小心情

Python 中可以进行线性回归的包有很多个,包括numpy, sklearn, scipy 和stats,下面对这几个包中进行普通最小二乘回归做简单对比。

  1. 使用numpy:
# 简单回归,只获取斜率和截距
import numpy as np
a, b = np.polyfit(x, y, 1)  # a, b为斜率和截距,1为一次项,即线性回归。

# 如果想要获取更多的统计信息,设置polyfit参数full=True,即
a, b, residuals, rank, singular_values, rcond = np.polyfit(x, y, full=True)
此外还可以通过设置参数cov获取协方差矩阵。

参考文档:https://numpy.org/devdocs/reference/generated/numpy.polyfit.html?highlight=polyfit#numpy.polyfit

  1. 使用机器学习包sklearn:
from sklearn.linear_model import LinearRegression

def linear_model(x, y):
    lm_model = LinearRegression()
    lm_model.fit( x[:,np.newaxis], y)
    y_predicted = lm_model.predict(np.reshape(x, (-1,1)))
    r2 = lm_model.score(np.reshape(x, (-1,1)), y)
    a = lm_model.coef_
    b = lm_model.intercept_
    return a, b, r2

# 假设输入是pandas的DataFrame
a, b, r2 = linear_model(df['x'], df['y'])

参考文档:https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression

  1. 使用statsmodels可以输出较多的统计量
import statsmodels.api as sm

# print the ols summary
x = sm.add_constant(x)
results = sm.OLS(y, x).fit()
print(results.summary())

参考文档:https://www.statsmodels.org/devel/regression.html

  1. 使用scipy中的optimize模块可以对任何形式的函数进行拟合
from scipy.optimize import curve_fit

# 比如简单的二次函数
def func(x, a, b, c):
        return a * (x * x) + b * x + c
# 参数和协方差矩阵
popt, pcov = curve_fit(func, x, y)
# 计算各个参数的标准差  standard deviation errors on the parameters
perr = np.sqrt(np.diag(pcov)) 

或者是使用其中的stats模块

from scipy import stats
import numpy as np
x = np.random.random(10)
y = np.random.random(10)
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)

参考文档:https://docs.scipy.org/doc/scipy-1.3.3/reference/generated/scipy.optimize.curve_fit.html#scipy.optimize.curve_fit

接下来再去看看几种不同的回归方法。

上一篇 下一篇

猜你喜欢

热点阅读