具有多个自变量的 Python 曲线拟合 [英] Python curve_fit with multiple independent variables

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

问题描述

Python 的 curve_fit 计算具有单个自变量的函数的最佳拟合参数,但是有没有办法使用 curve_fit 或其他方法来拟合具有多个自变量的函数?例如:

Python's curve_fit calculates the best-fit parameters for a function with a single independent variable, but is there a way, using curve_fit or something else, to fit for a function with multiple independent variables? For example:

def func(x, y, a, b, c):
    return log(a) + b*log(x) + c*log(y)

其中 x 和 y 是自变量,我们希望拟合 a、b 和 c.

where x and y are the independent variable and we would like to fit for a, b, and c.

推荐答案

您可以向 curve_fit 传递自变量的多维数组,但是您的 func 必须接受同样的事情.例如,调用这个数组 X 并将其解包为 x, y 为清楚起见:

You can pass curve_fit a multi-dimensional array for the independent variables, but then your func must accept the same thing. For example, calling this array X and unpacking it to x, y for clarity:

import numpy as np
from scipy.optimize import curve_fit

def func(X, a, b, c):
    x,y = X
    return np.log(a) + b*np.log(x) + c*np.log(y)

# some artificially noisy data to fit
x = np.linspace(0.1,1.1,101)
y = np.linspace(1.,2., 101)
a, b, c = 10., 4., 6.
z = func((x,y), a, b, c) * 1 + np.random.random(101) / 100

# initial guesses for a,b,c:
p0 = 8., 2., 7.
print curve_fit(func, (x,y), z, p0)

适合:

(array([ 9.99933937,  3.99710083,  6.00875164]), array([[  1.75295644e-03,   9.34724308e-05,  -2.90150983e-04],
   [  9.34724308e-05,   5.09079478e-06,  -1.53939905e-05],
   [ -2.90150983e-04,  -1.53939905e-05,   4.84935731e-05]]))

这篇关于具有多个自变量的 Python 曲线拟合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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