Python 曲线拟合无限求和

问题描述 投票:0回答:3

我正在尝试在Python中进行曲线拟合,其中包括无限求和。

我总是遇到错误。

from mpmath import nsum, exp, inf
import numpy as np
import pylab
from scipy.optimize import curve_fit

# get the data
y=[]
x=[]
for t in range(0,100,10):
    x += [t]
    y += [round(float((nsum(lambda n: exp(-(0.0002)*(n)*t),[0, inf]))),3)]
print(y)

# curve fitting
def test(t,D):
    return  [round(float((nsum(lambda n: exp(-(D)*(n)*t),[0, inf]))),3)]

                 
parameters, params_covariance=curve_fit(test, x, y)

print(parameters)

我希望可以从曲线拟合函数中得到估计的 D,但我总是得到错误:

TypeError: cannot create mpf from array([mpf('0.0'), mpf('0.0'), mpf('0.0'), mpf('0.0'), mpf('0.0'),
       mpf('0.0'), mpf('0.0'), mpf('0.0'), mpf('0.0'), mpf('0.0')],
      dtype=object)

谢谢!

python python-3.x curve-fitting
3个回答
1
投票

您需要将 test() 的输入和输出设为列表

def test(x,D):
    return  [float((nsum(lambda n: exp(-(D)*(n)*t),[0, inf]))) for t in x]

0
投票

使用您显示的代码,我无法重现该错误。

(我使用列表推导式来创建

x
y
,但它们等同于您的代码。)

In [1]: from mpmath import nsum, exp, inf

In [2]: x = [t for t in range(0, 100, 10)]
Out[2]: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

In [3]: y = [round(float((nsum(lambda n: exp(-(0.0002)*(n)*t),[0, inf]))),3) for t in range(0, 100, 10)]
Out[3]: [150.0, 500.5, 250.5, 167.167, 125.501, 100.501, 83.834, 71.93, 63.001, 56.057]

In [4]: [type(t) for t in y]
Out[4]: [float, float, float, float, float, float, float, float, float, float]

In [5]: [type(t) for t in x]
Out[5]: [int, int, int, int, int, int, int, int, int, int]

可以看出,

x
是整数列表,
y
是浮点数列表。所以看不到
mpf
...

唯一的是

test
返回一个列表:

In [6]: def test(t,D):
   ...:     return  [round(float((nsum(lambda n: exp(-(D)*(n)*t),[0, inf]))),3)]
   ...:

In [7]: test(30, 0.002)
Out[7]: [17.172]

curve_fit
的文档对此没有明确说明,但我希望该函数只返回这样的数字:

In [8]: def test(t,D):
   ...:     return  round(float((nsum(lambda n: exp(-(D)*(n)*t),[0, inf]))),3) 
   ...:

In [9]: test(30, 0.002)
Out[9]: 17.172

我没有安装scipi,但是

curve_fit
应该不会有
x
y
的问题。我不知道
test
返回列表是否会出现问题,但这肯定不会重现此特定错误。

编辑: 由于数据中和提交给

mpf
的函数中都没有
curve_fit
对象,因此
curve_fit
不可能引发此异常。

编辑2: 根据回溯,似乎从

test()
返回列表确实是问题所在。当 mpmath 看到返回的列表 并且 您正在使用 numpy 时,它会尝试将列表转换为
mpf
。这似乎就是出错的地方。更改
test()
以返回数字而不是列表,如上面所示。这应该可以解决它。


0
投票

您可以通过使用交互式曲线拟合工具来避免额外的复杂性。在使用 Python 的情况下,我建议查看 SplineCloud - 它有一个用于曲线拟合的免费多功能交互式工具,并且您可以在 Python 客户端库的帮助下在代码中重用曲线。

这篇文章中有更详细的描述。

© www.soinside.com 2019 - 2024. All rights reserved.