# SciPy正交距离回归(ODR)介绍和用法

ODR是正交距离回归的缩写形式。它用于回归研究。基本线性回归用于通过在图中绘制最佳拟合线来估计两个变量y和x之间的关系。那么问题来了, 为什么需要正交距离回归(ODR)？有时, 测量误差发生在自变量(x)而非因变量(y)中。

``````import numpy as np
import matplotlib.pyplot as plt
from scipy.odr import *
import random
# Initiate some data, and generate the random number using random.random().
a = np.array([0, 1, 2, 3, 4, 5, 6, 7])
b = np.array([i**2 + random.random() for i in x])
# Define a quadratic function ( in this case) to fit the data with.
def linear_func(z, a):
m, p = z
return m*a + p
# Creating a model for fitting.
linear_model_fit = Model(linear_func)
# Creating a RealData object using our initiated data from above.
data = RealData(x, y)
# Fixed up ODR with the model and data.
odr = ODR(data, linear_model_fit, beta0=[0., 1.])
# Here we run the regression using the run().
out = odr.run()
# Use the in-built pprint method to give us results.
out.pprint()``````

``````Beta: [ 7.62787497 -8.53630181]
Beta Std Error: [0.89306061 3.69444539]
Beta Covariance: [[ 1.52116591 -5.32408057]
[-5.32408057 26.0323407 ]]
Residual Variance: 0.5243065494144553
Inverse Condition #: 0.18510252155770376
Reason(s) for Halting:
Sum of squares convergence``````

• 回顶