简体   繁体   English

使用curve_fit来拟合数据

[英]Use of curve_fit to fit data

I'm new to scipy and matplotlib, and I've been trying to fit functions to data. 我是scipy和matplotlib的新手,我一直在尝试将函数与数据相匹配。 The first example in the Scipy Cookbook works fantastically, but when I am trying it with points read from a file, the initial coefficients I give (p0 below) never seem to actually change, and the covariance matrix is always INF. Scipy Cookbook中的第一个例子非常有效,但是当我尝试从文件中读取点时,我给出的初始系数(下面的p0)似乎从未真正改变,协方差矩阵总是INF。

I've tried to fit even data following a line, to no avail. 我试图在一条线后拟合数据,但无济于事。 Is it a problem with the way I am importing the data? 我导入数据的方式有问题吗? If so, is there a better way to do it? 如果是这样,有没有更好的方法呢?

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

with open('data.dat') as f:
    noms = f.readline().split('\t')

    dtipus = [('x', sy.float32)] + [('y', sy.float32)]

    data = sy.loadtxt(f,delimiter='\t',dtype=dtipus)

    x = data['x']
    y = data['y']

    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()

Thanks! 谢谢!

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: 并使用pylabloadtxt函数进行读取:

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. 顺便说一句,您可以使用dtypes命名列。

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). 加载数据的根本问题是你将它转换为float32,但在scipy 0.10.1中,curve_fit与float64一起工作但不是float32(这是一个bug,而不是一个特性)。 Your example works with float64. 您的示例适用于float64。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM