在這種情況下,通常最好從一個能夠再現錯誤的小玩具問題開始。
此特定錯誤可能來自this line。雖然神祕,但它試圖將函數的輸入轉換爲浮點數組(NPY_DOUBLE),並在失敗時拋出錯誤。
OK,這裏是如何引發的錯誤:
In [3]: import numpy as np
In [4]: from scipy.optimize import curve_fit
In [5]: x = np.array([1.0, 2., 3, 4.])
In [6]: y = x
In [7]: def f(x, a): # try a nan
...: return np.nan
...:
In [9]: curve_fit(f, x, y, 2.0)
/home/br/virtualenvs/scipy-dev/local/lib/python2.7/site-packages/scipy/optimize/minpack.py:604: OptimizeWarning: Covariance of the parameters could not be estimated
category=OptimizeWarning)
Out[9]: (array([ 2.]), array([[ inf]]))
不,nan
我國農產品一些不同的輸出。讓我們嘗試一個字符串:
In [10]: def g(x, a):
....: return 'nonsense'
....:
In [11]: curve_fit(g, x, y, 2.0)
<snip>
TypeError: unsupported operand type(s) for -: 'str' and 'numpy.ndarray'
另外不同的錯誤。好吧,讓我們試一下複數:
In [12]: def h(x, a):
....: return 1j
....:
In [13]: curve_fit(h, x, y, 2.0)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
TypeError: Cannot cast array data from dtype('complex128') to dtype('float64') according to the rule 'safe'
<snip>
error: Result from function call is not a proper array of floats.
賓果。現在我開始檢查你的函數是否在一些輸入中進入複雜平面。
我發現[lmfit](http://lmfit.github.io/lmfit-py/)對於擬合輸入的某些值的模型非常有用 - 它比scipy模塊強大得多。另外,如果您有單獨的分子和分母,則還應該使用雙參數[arctan2](http://docs.scipy.org/doc/numpy/reference/generated/numpy.arctan2.html)。 – chthonicdaemon