将元组作为scipy.optimize.curve_fit的输入参数 [英] Pass tuple as input argument for scipy.optimize.curve_fit

查看:64
本文介绍了将元组作为scipy.optimize.curve_fit的输入参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

import numpy as np
from scipy.optimize import curve_fit


def func(x, p): return p[0] + p[1] + x


popt, pcov = curve_fit(func, np.arange(10), np.arange(10), p0=(0, 0)) 

它将引发 TypeError:func()恰好接受2个参数(给定3个参数).好吧,这听起来很合理-curve_fit将(0,0)取消协定为两个标量输入.所以我尝试了这个:

It will raise TypeError: func() takes exactly 2 arguments (3 given). Well, that sounds fair - curve_fit unpact the (0, 0) to be two scalar inputs. So I tried this:

popt, pcov = curve_fit(func, np.arange(10), np.arange(10), p0=((0, 0),))

再次,它说: ValueError:对象太深,无法放入所需的数组

如果我将其保留为默认值(未指定p0):

If I left it as default (not specifying p0):

popt, pcov = curve_fit(func, np.arange(10), np.arange(10))  

它将引发 IndexError:标量变量的无效索引.显然,它仅为该函数提供了p的标量.

It will raise IndexError: invalid index to scalar variable. Obviously, it only gave the function a scalar for p.

我可以使def func(x,p1,p2):返回p1 + p2 + x使其正常工作,但是在更复杂的情况下,代码看起来显得冗长而混乱.如果有一个更干净的解决方案,我真的会喜欢它.

I can make def func(x, p1, p2): return p1 + p2 + x to get it working, but with more complicated situations the code is going to look verbose and messy. I'd really love it if there's a cleaner solution to this problem.

谢谢!

推荐答案

不确定这是否更干净,但至少现在可以更轻松地向拟合函数添加更多参数.也许甚至可以从中得出更好的解决方案.

Not sure if this is cleaner, but at least it is easier now to add more parameters to the fitting function. Maybe one could even make an even better solution out of this.

import numpy as np
from scipy.optimize import curve_fit


def func(x, p): return p[0] + p[1] * x

def func2(*args):
    return func(args[0],args[1:])

popt, pcov = curve_fit(func2, np.arange(10), np.arange(10), p0=(0, 0))
print popt,pcov

这对我有用

import numpy as np
from scipy.optimize import curve_fit

def func(x, *p): return p[0] + p[1] * x

popt, pcov = curve_fit(func, np.arange(10), np.arange(10), p0=(0, 0))
print popt,pcov

这篇关于将元组作为scipy.optimize.curve_fit的输入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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