Least squares in a set of equations with optimize.leastsq() (Python)

陌路散爱 提交于 2021-02-09 15:49:04

问题


I have two functions and a set of data. Both functions have the same x data and the same parameters. I want to obtain the parameters by least squares method that makes the best fit of my data.

The parameters are: ex,ey,ez.

The X data are: RA,DE (like 3000 points).

The Y data are: dRA,dDE.

I tried this but I obtained a wrong solution:

def residuals(p, dRA, dDE, RA, DEC):
    ex,ey,ez = p
    f1 = dRA-(ex*sin(DEC)*cos(RA)+ey*sin(DEC)*sin(RA)-ez*cos(DEC))
    f2 = dDE-(-ex*sin(RA)+ey*cos(RA))
    err = np.concatenate((f1,f2))
    return err

from scipy.optimize import leastsq
p0 = [0, 0., 0.]
plsq_coord = leastsq(residuals, p0, args=(dRA, dDE, RA, DE))
print plsq_coord[0] 

Any kind of help would be very wellcome


回答1:


As shown by this test code code

import numpy as np, numpy.random,scipy.optimize
def residuals(p, dRA, dDE, RA, DEC):
    ex,ey,ez = p
    f1 = dRA-(ex*np.sin(DEC)*np.cos(RA)+ey*np.sin(DEC)*np.sin(RA)-ez*np.cos(DEC))
    f2 = dDE-(-ex*np.sin(RA)+ey*np.cos(RA))
    err = np.concatenate((f1,f2))
    return err    
ex, ey, ez = 0.2, 0.3, 0.4
N = 100
err = 1e-3
ra, dec = np.random.uniform(0,1,N), np.random.uniform(0,.5,N)
dra = (ex*np.sin(dec)*np.cos(ra)+ey*np.sin(dec)*np.sin(ra)-ez*np.cos(dec))+np.random.normal(size=N)*err
ddec = (-ex*np.sin(ra)+ey*np.cos(ra))+np.random.normal(size=N)*err
print scipy.optimize.leastsq(residuals, p0, args=(dra, ddec, ra, dec))

your code should work fine, unless your function is written incorrectly (e.g. your ra,dec are in degrees, not radians) or you have some bad datapoints in the dataset which screw the chisq fit.



来源:https://stackoverflow.com/questions/10664199/least-squares-in-a-set-of-equations-with-optimize-leastsq-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!