在Python中拟合多元curve_fit [英] fitting multivariate curve_fit in python

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

问题描述

我正在尝试将简单函数适合python中两个独立数据数组。我知道我需要将独立变量的数据打包到一个数组中,但是在尝试拟合时,传递变量的方式似乎仍然存在问题。 (以前有几篇与此相关的文章,但并没有太大帮助。)

I'm trying to fit a simple function to two arrays of independent data in python. I understand that I need to bunch the data for my independent variables into one array, but something still seems to be wrong with the way I'm passing variables when I try to do the fit. (There are a couple previous posts related to this one, but they haven't been much help.)

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

def fitFunc(x_3d, a, b, c, d):
    return a + b*x_3d[0,:] + c*x_3d[1,:] + d*x_3d[0,:]*x_3d[1,:]

x_3d = np.array([[1,2,3],[4,5,6]])

p0 = [5.11, 3.9, 5.3, 2]

fitParams, fitCovariances = curve_fit(fitFunc, x_3d[:2,:], x_3d[2,:], p0)
print ' fit coefficients:\n', fitParams

我读取的错误,

raise TypeError('Improper input: N=%s must not exceed M=%s' % (n, m)) 
TypeError: Improper input: N=4 must not exceed M=3

M 的长度是多少? N p0 的长度吗?我在这里做什么错了?

What is M the length of? Is N the length of p0? What am I doing wrong here?

推荐答案

N和M在该功能的帮助。 N是数据点的数量,M是参数的数量。因此,您的错误基本上意味着您至少需要与参数一样多的数据点,这很有意义。

N and M are defined in the help for the function. N is the number of data points and M is the number of parameters. Your error therefore basically means you need at least as many data points as you have parameters, which makes perfect sense.

此代码对我有用:

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

def fitFunc(x, a, b, c, d):
    return a + b*x[0] + c*x[1] + d*x[0]*x[1]

x_3d = np.array([[1,2,3,4,6],[4,5,6,7,8]])

p0 = [5.11, 3.9, 5.3, 2]

fitParams, fitCovariances = curve_fit(fitFunc, x_3d, x_3d[1,:], p0)
print ' fit coefficients:\n', fitParams

我添加了更多数据。我还更改了 fitFunc ,使其以仅作为单个x的函数进行扫描的形式编写-装配工将处理对所有数据点的调用。您发布的代码还引用了 x_3d [2,:] ,这会导致错误。

I have included more data. I have also changed fitFunc to be written in a form that scans as only being a function of a single x - the fitter will handle calling this for all the data points. The code as you posted also referenced x_3d[2,:], which was causing an error.

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

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