📜  使用 SciPy 的正交距离回归

📅  最后修改于: 2022-05-13 01:54:37.126000             🧑  作者: Mango

使用 SciPy 的正交距离回归

回归基本上涉及确定因变量与一个或多个自变量之间的关系。它通常涉及找到使每个点的误差平方和最小化的最佳拟合线。根据实现过程,回归算法分为线性回归、岭回归、套索回归、多项式回归等。在本文中,让我们讨论正交距离回归并查看 Scipy 中正交距离回归的实际实现。

正交回归

与相对于拟合线垂直测量误差的正常回归问题不同,正交距离回归涉及计算点相对于拟合线的正交距离,这允许考虑自变量和因变量的测量误差沿 x 和 y 轴,如图所示。这种计算垂直距离的方式增加了模型的鲁棒性。与最小平方距离之和不同,正交距离回归最小化平方垂直距离之和。

当 Y 和 X 都容易出错时,通常应用正交回归,也可以应用于可变换的非线性模型。正交回归假设因变量和自变量的真实值之间存在线性关系。 Y 和 X 的观测值添加了一个小误差。给定 n 对测量值,正交回归涉及找到一条最小化以下方程的线。

这里,ε,μ是测量值的误差,σ表示误差的方差。

正交距离回归是使用 ODRPACK 实现的,ODRPACK 是一个基于 FORTRAN – 77 的库。 scipy.odr 包为 ODRPACK 提供了一个 OOPS 接口。

方法

  • 导入必要的Python包,如 numpy、matplotlib 和 random。
  • 从 scipy 导入 ODR函数。使用 numpy 创建一个样本特征和一个目标数组。
  • 基于特征变量的分布,我们可以通过 odr函数。在这里,我们使用一个简单的线性方程作为 odr函数用来拟合模型的目标函数。
  • 将定义的自定义目标函数传递给 odr.Model()函数。这里模型已拟合。
  • 现在,通过 odr.Data()函数传递特征和目标变量来转换它们。
  • 然后,将转换后的特征和目标变量以及拟合模型与超参数 beta(一个小值)一起传递。
  • 在最终的 odr 模型上使用 run()函数计算并打印结果

代码:

Python3
# import the necessary python packages
import numpy as np
import matplotlib.pyplot as plt
 
# odr function from scipy package
# is used to perform ODR regression
from scipy import odr 
import random as r
 
# Create a sample feature array and a target array
feature = np.array(np.arange(1, 11))
# shuffle the created array
np.random.shuffle(feature)
# create a target array of random numbers
target = np.array([0.65, -.75, 0.90, -0.5, 0.14,
                   0.84, 0.99, -0.95, 0.41, -0.28])
 
# Define a function (quadratic in our case)
# to fit the data with.
# odr initially assumes a linear function
def target_function(p, x):
    m, c = p
    return m*x + c
 
#  model fitting.
odr_model = odr.Model(target_function)
 
# Create a Data object using sample data created.
data = odr.Data(feature, target)
 
# Set ODR with the model and data.
ordinal_distance_reg = odr.ODR(data, odr_model,
                               beta0=[0.2, 1.])
 
# Run the regression.
out = ordinal_distance_reg.run()
 
# print the results
out.pprint()


输出:

Beta:                    [-0.01059931  0.2032962 ]

Beta Std Error:        [0.08421527 0.52254163]

Beta Covariance:       [[ 0.01212265 -0.06667458]

                        [-0.06667458  0.46672142]]

Residual Variance:      0.5850379776588954

Inverse Condition #:    0.06924525890982118

Reason(s) for Halting:
  Sum of squares convergence

odr 算法将返回可用于拟合回归线的 beta 值、std 误差和 beta 值的协方差。