gpt4 book ai didi

python - 使用 scipy 进行曲线拟合 - 我收到类型错误

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:49 25 4
gpt4 key购买 nike

我从文件中读取一些 x 和 y 数据,转换为 float 并放入单独的数组中,然后从 scipy 调用曲线拟合函数。

它根据我使用的方程式(在定义的函数中)给我不同的错误消息。我在我想使用的方程式之后对代码进行了注释,它是最上面的、未注释的方程式(第 9 行)。

我能理解为什么它可能需要一个 float 而不是一个字符串,但我在类型转换方面的尝试似乎没有奏效。我最常见的错误是 TypeError: a float is required

如果我尝试传递值而不是通过读取我的文件,而是使用 np.linspace 作为我在 scipy 网站上找到的示例,它会给我一个不同的错误。

我已经对代码中的错误进行了注释,希望您发现它没有歧义。我还粘贴了我正在使用的输入文本文件。

import sys
import numpy as np
import math as m
from scipy.optimize import curve_fit


def func( x, a, b ):
return a*m.pow( x, 2 )*np.exp( -b*x ); #the function I want!: line 9 in funcTypeError: a float is required
#return a*m.exp(-b*x) #line 10 in func TypeError: a float is required
#return a*np.exp(-b*x) #Example equation. line 444 in _general_function
#ValueError:operands could not be broadcast together with shapes
#return a*b*m.pow( x, 2 ); #line 10 in func TypeError: a float is required

#end def

file = sys.argv[1];

f = open( file );
y_array = [];
x_array = [];

for line in f:
words = line.split();
x = words[0].rstrip('\r\n');
y = words[1].rstrip('\r\n');
x_array.append( float( x ) );
y_array.append( float( y ) );
#end for
#data = f.read();

popt, pcov = curve_fit( func, x_array, y_array );

或者我从他们在 scipy 网站上给出的例子中尝试这个,用我上面的,未注释的,期望的等式

x = np.linspace(0,4,50)
y = func(x, 2.5, 1.3 )
yn = y + 0.2*np.random.normal(size=len(x))
popt, pcov = curve_fit(func, x, yn)

#TypeError: only length-1 arrays can be converted to Python scalars.

输入文件(只有几行,还有更多)。两列数字

352 28
423 30
494 32
565 3
636 0
707 0

最佳答案

您的 x 是一个列表,您正在对其调用 math.powmath.pow 只知道如何提高 float 或可转换为 float 的东西。因此,TypeError:需要一个 float 。这就是我们拥有 numpy 的原因之一。 :^)

我们可以通过在整个过程中使用 numpy 来简化这件事。然后我们可以简单地使用 ** 来获取整个数组的权力。

def func( x, a, b ):
return a * x**2 * np.exp( -b*x )

file = sys.argv[1]
x,y = np.loadtxt(file, unpack=True)
popt, pcov = curve_fit( func, x, y)

给我

>>> popt
array([ 1., 1.])
>>> pcov
inf

使用您的数据,该函数不太适合。该示例效果更好:

>>> x = np.linspace(0,4,50)
>>> y = func(x, 2.5, 1.3 )
>>> yn = y + 0.2*np.random.normal(size=len(x))
>>> popt, pcov = curve_fit(func, x, yn)
>>> popt
array([ 3.15537828, 1.43218611])
>>> pcov
array([[ 0.08045745, 0.01257863],
[ 0.01257863, 0.00232191]])

关于python - 使用 scipy 进行曲线拟合 - 我收到类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20149877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com