简体   繁体   English

在python中拟合多元curve_fit

[英]fitting multivariate curve_fit in python

I'm trying to fit a simple function to two arrays of independent data in python.我正在尝试将一个简单的函数拟合到 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

The error I get reads,我读到的错误,

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

What is M the length of? M的长度是多少? Is N the length of p0 ? Np0的长度吗? What am I doing wrong here?我在这里做错了什么?

N and M are defined in the help for the function. N 和 M 在函数的帮助中定义。 N is the number of data points and M is the number of parameters. N 是数据点的数量,M 是参数的数量。 Your error therefore basically means you need at least as many data points as you have parameters, which makes perfect sense.因此,您的错误基本上意味着您至少需要与参数一样多的数据点,这是完全有道理的。

This code works for me:这段代码对我有用:

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

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.我还将fitFunc更改为以扫描为仅作为单个 x 的函数的形式编写 - fitFunc将处理为所有数据点调用此函数。 The code as you posted also referenced x_3d[2,:] , which was causing an error.您发布的代码还引用了x_3d[2,:] ,这导致了错误。

The default curve_fit method needs you to have fewer parameters for the fitted function fitFunc than data points.默认的curve_fit方法需要拟合函数fitFunc的参数少于数据点。 I had the same problem fitting a function that took 15 parameters in total and I had only 13 data points.我在拟合一个总共有 15 个参数的函数时遇到了同样的问题,我只有 13 个数据点。 The solution is to use another method (eg dogbox or trf ).解决方案是使用另一种方法(例如dogboxtrf )。

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

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