python scipy leastsq 适合复数 [英] python scipy leastsq fit with complex numbers

查看:112
本文介绍了python scipy leastsq 适合复数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复数数据集,我希望能够找到最适合该数据的参数.你能用python中的scipy实现的leastsq将数据拟合成复数吗?

I have a data set of complex numbers, and I'd like to be able to find parameters that best fit the data. Can you fit data in complex numbers using leastsq as implemented by scipy in python?

例如,我的代码是这样的:

For example, my code is something like this:

 import cmath
 from scipy.optimize import leastsq
 def residuals(p,y,x):
      L,Rs,R1,C=p
      denominator=1+(x**2)*(C**2)*(R1**2)
      sim=complex(Rs+R1/denominator,x*L-(R1**2)*x*C/denominator)
      return(y-sim)

 z=<read in data, store as complex number>
 x0=np.array[1, 2, 3, 4]
 res = leastsq(residuals,x0, args=(z,x))

但是,residuals 不喜欢使用我的复数,我收到错误:

However, residuals doesn't like working with my complex number, I get the error:

File "/tmp/tmp8_rHYR/___code___.py", line 63, in residuals
    sim=complex(Rs+R1/denominator,x*L-(R1**_sage_const_2 )*x*C/denominator)
  File "expression.pyx", line 1071, in sage.symbolic.expression.Expression.__complex__ (sage/symbolic/expression.cpp:7112)
TypeError: unable to simplify to complex approximation

我猜我只需要使用浮点数/双精度数而不是复数.在这种情况下,我如何分别评估实部和复部,然后将它们合并为一个单一的错误度量,以便 residuals 返回?

I'm guessing that I need to work only with floats/doubles rather than complex numbers. In that case, how can I evaluate the real and complex parts separately and then lump them back together into a single error metric for residuals to return?

推荐答案

scipy 中的最小二乘函数需要返回一个实数残差,因为它很难比较复数值(例如 1+2j 是大于还是小于 2+1j?).请记住,残差本质上是对传入参数集质量的度量,它告诉leastsq 它与真实拟合的接近程度.

The least squares function in scipy wants a real residual returned because it is difficult to compare complex values (e.g. is 1+2j greater or less than 2+1j?). Remember the residual is essentially a measure of the quality of the set of parameters passed in, it tells leastsq how close to the true fit it is.

您可以做的是在正交中添加误差 (y-sim),在您的残差函数中计算 'sim' 后附加这些行:

What you can do is add the error (y-sim) in quadrature, appending these lines after you calculate 'sim' in your residuals function:

a = y-sim
return a.real**2 + a.imag**2

只要 y 和 sim 都是复杂的 np.array ,那么这将起作用并且相对有效.

So long as y and sim are both np.array's of complex's then this will work and is relatively efficient.

这篇关于python scipy leastsq 适合复数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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