使用curve_fit拟合数据 [英] Use of curve_fit to fit data

查看:240
本文介绍了使用curve_fit拟合数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是scipy和matplotlib的新手,我一直在尝试使函数适合数据。 Scipy Cookbook 中的第一个示例工作得非常好,但是当我尝试从文件中读取点后,我给出的初始系数(下面的p0)似乎从未发生实际变化,并且协方差矩阵始终为INF。

I'm new to scipy and matplotlib, and I've been trying to fit functions to data. 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.

我试图将一行数据连进去,但无济于事。我导入数据的方式是否有问题?如果是这样,还有更好的方法吗?

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

谢谢!

推荐答案

在我看来,问题确实出在如何导入数据上。伪造此数据文件:

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

并使用 pylab loadtxt 函数用于读取:

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

为我工作。顺便说一句,您可以使用 dtypes 来命名列。

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

这篇关于使用curve_fit拟合数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆