python中的多元曲线拟合

2024-09-27 07:31:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一个简单的函数与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

我得到的错误是

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

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


Tags: 数据importinputasnpnot数组fit
1条回答
网友
1楼 · 发布于 2024-09-27 07:31:20

N和M在the help中为函数定义。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

我包括了更多的数据。我还将fitFunc改为只作为单个x的一个函数进行扫描的形式-装配工将处理所有数据点的调用。您发布的代码还引用了x_3d[2,:],这导致了一个错误。

相关问题 更多 >

    热门问题