Use of curve_fit to fit data

自古美人都是妖i 提交于 2019-11-28 11:10:54

It seems to me that the problem is indeed in how you import your data. Faking this datafile:

$:~/temp$ cat data.dat
1.0  2.0
2.0  4.2
3.0  8.4
4.0  16.1

and using the pylab's loadtxt function for reading:

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import scipy as sy
import pylab as plb  

data = plb.loadtxt('data.dat')  
x = data[:,0]
y= data[:,1]

def func(x, a, b, c):
  return a*x**b + c

p0 = sy.array([1,1,1])
coeffs, matcov = curve_fit(func, x, y, p0)

yaj = func(x, coeffs[0], coeffs[1], coeffs[2])
print(coeffs)
print(matcov)

plt.plot(x,y,'x',x,yaj,'r-')
plt.show()

works for me. By the way, you can use dtypes to name the columns.

The underlying problem with your load data is that you cast it to float32, but in scipy 0.10.1, curve_fit works with float64 but not float32 (it's a bug, not a feature). Your example works with float64.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!