在python中拟合多变量curve_fit

use*_*865 18 python curve-fitting scipy

我试图在python中将一个简单的函数拟合到两个独立数据数组中.我知道我需要将我的自变量的数据聚集到一个数组中,但是当我尝试进行拟合时,我传递变量的方式似乎仍然存在问题.(之前有几篇与此相关的文章,但它们没有太多帮助.)

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
Run Code Online (Sandbox Code Playgroud)

我得到的错误,

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

什么是M长度?是N长度p0?我在这做错了什么?

cht*_*mon 21

N和M 在函数的帮助中定义.N是数据点的数量,M是参数的数量.因此,您的错误基本上意味着您需要至少与参数一样多的数据点,这非常有意义.

这段代码适合我:

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
Run Code Online (Sandbox Code Playgroud)

我已经包含了更多数据.我还改为fitFunc以一种形式编写,扫描只是一个x的函数 - fitter将处理所有数据点的调用.您发布的代码也被引用x_3d[2,:],这导致了错误.

  • 非常感谢!(我认为M是数据点的数量,N是参数的数量.) (5认同)
  • @Joshua Yup,我提交了[bug报告和修复](https://github.com/scipy/scipy/issues/3172).我想我应该更新这个答案. (2认同)