python - 使用curve_fit的Python非线性回归误差
问题描述
我正在尝试使用scipy.optimize.curve_fit
. 我从此处找到的 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')
了,并尝试了在此线程上提出的所有解决方案,但均未成功:无法将数组数据从 dtype('O') 转换为 dtype('float64')
有什么建议和想法可以使这种回归起作用吗?
解决方案
这段代码对我来说执行没有错误(注意:我改为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()
尽管合身性很差:
我正在使用 python 3.5.4:
matplotlib 2.2.0
numpy 1.14.2
scipy 1.0.0
推荐阅读
- android - Android Studio 预览版不显示布局
- wpf - WPF 按钮样式不适用于第二个按钮
- typescript - 返回实际类型 Typescript
- powershell - 从文本文件加载变量,如果哈希表中存在键,则使用键值
- javascript - Javascript无法重置模块中的对象
- javascript - 使用 css 更改颜色的链接无法正常工作
- python - 什么是“python优先库”?
- java - 用于分配对象属性的 OnWindowFocusChanged 与 OnCreate
- macos - XAMPP - Apache 未在 Mac OS 上启动
- javascript - 从 javascript 导出图形