'How to get intercept slope and fit line by using scipy ODR
I am new to python. I want to perform orthogonal distance regression by using Scipy ODR by using the code below. I do not know how can I extract slope and intercept from the output and on what logic we give values to beta0 in "myodr = odr.ODR(mydata, linear, beta0=[0.,1.]"
def f(B, x):
return B[0]*x + B[1]
linear = odr.Model(f)
mydata = odr.Data(x, y, wd=1./xerr, we=1./yerr)
myodr = odr.ODR(mydata, linear, beta0=[0.,1.]) # how to put beta0 values here
myoutput = myodr.run()
myoutput.pprint()
Solution 1:[1]
The fitted parameters are stored in the beta
attribute of the Output
instance returned by the run()
method.
You used the generic Model
, so the meaning of the parameters is determined by how you use them in f
. In your case, you can recover the slope and intercept with
slope, intercept = myoutput.beta
ODR fitting involves solving a nonlinear problem with numerical methods that require a starting "guess" of the solution. The better the guess, the more likely that the numerical method will converge to a solution. Determining a good initial guess for an arbitrary model can be difficult. You model is linear, so there are several methods that might work fine. You could, for example, use the result of a standard least squares fit. Or you could use the equation of the line through two data points, say the points associated with the smallest and largest x values.
Because your model is linear, you might prefer to use the predefined model unilinear
. Then you don't have to define f
, and you don't have to provide beta0
, because the unilinear
model includes its own method for generating an initial guess. The meaning of the parameters in the unilinear
model are the same as in your f
function, so you can continue to use slope, intercept = myoutput.beta
to retrieve the results.
Something like this should work:
mydata = odr.Data(x, y, wd=1./xerr, we=1./yerr)
myodr = odr.ODR(mydata, model=odr.unilinear)
myoutput = myodr.run()
slope, intercept = myoutput.beta
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |