二参数极小化函数

2024-06-12 12:37:28 发布

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

我试图最小化一个有两个参数的函数:

def c_Gamma_gamma_fv(cf, cv):
    return np.abs((4 * eta_gamma * charges**2 * a_q * cf).sum() + 4.* cf *a_tau/3. + a_w * cv)**2/Gamma_gamma

def mu_fv(cf, cv):
    return np.array([cf**4, cf**2 * cv**2, cf**2 * 
c_Gamma_gamma_fv(cf, cv), cv**2 * c_Gamma_gamma_fv(cf, cv), cf**4, cv**2 * cf**2, cf**2 * cv**2,
                 cv**4, cv**2 * cf**2, cv**4])

def chi_square_fv(cf, cv):
    return ((mu_fv(cf, cv) - mu_data) @ inv_cov @ (mu_fv(cf, cv) - mu_data))

x0 = [1., 1.]
res_fv = minimize(chi_square_fv, x0)

但是,我得到了一个错误“TypeError:chi\u square\u fv()缺少一个必需的位置参数:‘cv’”。但是,当我做以下事情时:

print(chi_square_fv(1.,1.))

我得到输出

38.8312698786

我不明白这一点,而且我对这种手术还不熟悉。我该怎么做?OBS:Gamma\u Gamma只是代码的一个常量。你知道吗


Tags: 函数data参数returndefnpcvcf
2条回答

既然你没有给我们提供你代码中所有的变量值,我只能猜测了。你知道吗

我认为问题在于如何传递参数。x0 = [1.,1.]x0指定为具有2个值的列表,这是一个实体。但是,在chi_square_fv中,输入是两个独立的值,而不是一个列表。你知道吗

您可以尝试更改chi_square_fv函数:

def chi_square_fv(clist):
    cf, cv = clist
    return ((mu_fv(cf, cv) - mu_data) @ inv_cov @ (mu_fv(cf, cv) - mu_data))

如果您read docs在minimize上,您将发现可选的args参数(也可以参见@sacha的注释)

所以既然你的函数是两个参数的函数,你想在其中一个参数上最小化它,你就需要给另一个参数传递值

minimize(chi_square_fv, x0, args=(cv,))

它将一些cv值作为第二个参数传递给函数chi_square_fv

相关问题 更多 >