Python 传递给scipy.optimize.curve_fit的函数需要满足哪些特定要求才能运行?

Python 传递给scipy.optimize.curve_fit的函数需要满足哪些特定要求才能运行?,python,numpy,scipy,mathematical-optimization,curve-fitting,Python,Numpy,Scipy,Mathematical Optimization,Curve Fitting,我正在使用matplotlib的hist函数将统计模型拟合到分布中。例如,我的代码使用以下代码拟合指数分布: try: def expDist(x, a, x0): return a*(exp(-(x/x0))/x0) self.n, self.bins, patches = plt.hist(self.getDataSet(), self.getDatasetSize()/10, normed=1, facecolor='bl

我正在使用matplotlib的
hist
函数将统计模型拟合到分布中。例如,我的代码使用以下代码拟合指数分布:

    try:

        def expDist(x, a, x0):
            return a*(exp(-(x/x0))/x0)

        self.n, self.bins, patches = plt.hist(self.getDataSet(), self.getDatasetSize()/10, normed=1, facecolor='blue', alpha = 0.55)
        popt,pcov = curve_fit(expDist,self.bins[:-1], self.n, p0=[1,mean])
        print "Fitted gaussian curve to data with params a %f, x0 %f" % (popt[0], popt[1])
        self.a = popt[0]
        self.x0 = popt[1]

        self.fitted = True
    except RuntimeError:
        print "Unable to fit data to exponential curve"
它运行得很好,但是当我修改它以在
a
b
之间实现统一分布时

    def uniDist(x, a, b):
        if((x >= a)and(x <= b)):
            return float(1.0/float(b-a))
        else:
            return 0.000

    try:



        self.n, self.bins, patches = plt.hist(self.getDataSet(), self.getDatasetSize()/10, normed=1, facecolor='blue', alpha = 0.55)
        popt,pcov = curve_fit(uniDist,self.bins[:-1], self.n, p0=[a, b])
        print "Fitted uniform distribution curve to data with params a %f, b %f" % (popt[0], popt[1])
        self.a = popt[0]
        self.b = popt[1]

        self.fitted = True
    except RuntimeError:
        print "Unable to fit data to uniform distribution pdf curve"
def uniDist(x、a、b):

如果((x>=a)和(x你的怀疑部分是正确的。
曲线拟合
确实向函数传递了一个iterable,但不仅仅是任何iterable:a
numpy.ndarray
。这些恰好具有向量化算术运算符,因此

a*(exp(-(x/x0))/x0)
只需在输入数组上按元素运行,无任何错误(且输出正确)。甚至不需要太多魔法:对于函数的每次求值,参数
a
x0
都是标量,只有
x
是数组

现在,
uniDist
的问题在于它不仅包含算术运算符:它还包含比较运算符。只要将单个数组与标量进行比较,这些运算符就可以正常工作:

>>> import numpy as np
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> a>2
array([False, False, False,  True,  True], dtype=bool)
上面演示了在数组和标量上使用比较运算符将再次生成元素结果。当您尝试将逻辑运算符应用于其中两个布尔数组时,会出现错误:

>>> a>2
array([False, False, False,  True,  True], dtype=bool)
>>> a<4
array([ True,  True,  True,  True, False], dtype=bool)
>>> (a>2) and (a<4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
请注意,对于
&
情况,您必须始终将比较插入括号,因为同样
a>2&a
>>> (a>2) & (a<4)
array([False, False, False,  True, False], dtype=bool)
>>> np.logical_and(a>2,a<4)
array([False, False, False,  True, False], dtype=bool)
import scipy as sp
def uniDist(x, a, b):
    return sp.where((a<=x) & (x<=b), 1.0/(b-a), 0.0)