jmquintana79
2/23/2018 - 8:46 AM

linear regression with perpendicular offsets

Linear regression with perpendicular offsets. It is interesting be used specially for inference and not for prediction.

article: http://blog.rtwilson.com/orthogonal-distance-regression-in-python/comment-page-1/ github source: https://gist.github.com/robintw/d94eb527c44966fbc8b9#file-orthoregress-py

from scipy.odr import Model, Data, ODR
from scipy.stats import linregress
import numpy as np

def orthoregress(x, y):
    """Perform an Orthogonal Distance Regression on the given data,
    using the same interface as the standard scipy.stats.linregress function.
    Arguments:
    x: x data
    y: y data
    Returns:
    [m, c, nan, nan, nan]
    Uses standard ordinary least squares to estimate the starting parameters
    then uses the scipy.odr interface to the ODRPACK Fortran code to do the
    orthogonal distance calculations.
    """
    linreg = linregress(x, y) 
    
    mod = Model(f)
    dat = Data(x, y)
    od = ODR(dat, mod, beta0=linreg[0:2])
    out = od.run()

    return list(out.beta) + [np.nan, np.nan, np.nan]


def f(p, x):
    """Basic linear regression 'model' for use with ODR"""
    return (p[0] * x) + p[1]