一组方程中的最小二乘法,带有 optimize.leastsq() (Python) [英] Least squares in a set of equations with optimize.leastsq() (Python)

查看:57
本文介绍了一组方程中的最小二乘法,带有 optimize.leastsq() (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数和一组数据.这两个函数具有相同的 x 数据和相同的参数.我想通过最小二乘法获得参数,使我的数据最适合.

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.

参数为:ex,ey,ez.

The parameters are: ex,ey,ez.

X 数据为:RA、DE(如 3000 点).

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

Y 数据为:dRA、dDE.

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

推荐答案

如本测试代码所示

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))

您的代码应该可以正常工作,除非您的函数编写不正确(例如,您的 ra、dec 以度为单位,而不是弧度),或者您的数据集中有一些错误的数据点导致 chisq 拟合.

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.

这篇关于一组方程中的最小二乘法,带有 optimize.leastsq() (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆