使用Curve_fit的Python非线性回归错误

时间:2018-12-11 19:54:56

标签: python scipy non-linear-regression

我正在尝试使用scipy.optimize.curve_fit获得一个函数的3个未知参数。我从此处的Scipy文档中获取了示例代码:https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html

我使用简单的数据进行绘制:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

xdata = np.array([4.2, 8.5, 10.3, 17.2, 20.7, 38.2, 75.6, 850, 1550])     
ydata = np.array([83.3, 53.3, 44.8, 32.6, 28.1, 19.5, 11.5, 5.7, 5.3]) 

plt.plot(xdata, ydata, 'b-', label='data')

这是函数和其余代码:

def func(x, a, b, c):
    return x*(a*(1-m.exp(-b/x))+c*m.exp(-b/x))-x*c

popt, pcov = curve_fit(func, xdata, ydata)
popt

plt.plot(xdata, func(xdata, *popt), 'r-',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5]))
popt

plt.plot(xdata, func(xdata, *popt), 'g--',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))

plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()

我收到以下错误。

TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'

以及所有错误详细信息之后:

error: Result from function call is not a proper array of floats.

我尝试了xdata = np.array( ... , dtype='float64'),并尝试了在该线程上提出的所有解决方案,但均未成功:Cannot cast array data from dtype('O') to dtype('float64')

有什么建议和想法可以使回归有效?

1 个答案:

答案 0 :(得分:1)

此代码对我来说没有任何错误(注意:我将m.exp更改为np.exp):

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

xdata = np.array([4.2, 8.5, 10.3, 17.2, 20.7, 38.2, 75.6, 850, 1550])     
ydata = np.array([83.3, 53.3, 44.8, 32.6, 28.1, 19.5, 11.5, 5.7, 5.3]) 
fig, ax = plt.subplots()
ax.plot(xdata, ydata, 'b-', label='data')
def func(x, a, b, c):
    return x*(a*(1-np.exp(-b/x))+c*np.exp(-b/x))-x*c

popt, pcov = curve_fit(func, xdata, ydata)

plt.plot(xdata, func(xdata, *popt), 'r-',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))

popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5]))

ax.plot(xdata, func(xdata, *popt), 'g--',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
plt.show()

尽管合身性很差:

Bad fit

我正在使用python 3.5.4:

matplotlib                2.2.0
numpy                     1.14.2
scipy                     1.0.0