scipy ValueError:用户提供的目标函数必须返回标量值

yqhsw0fo  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(298)

我已经阅读了文档并试图理解如何使用scipy.optimize.minimize(),但我的代码就是不工作,它一直显示“ValueError:用户提供的目标函数必须返回标量值。”
下面是我的代码:

PH = np.linspace(0, 14, 71)
ni_total = 0.1
citrate_total = 0.9
ammonia_total = 0.3

def concs(citrate_total,ni_total, ammonia_total, PH):
    h = 10**(-PH)
    def equations(p):
        cit3, nio2, nh4 = p
        Hcit = h*cit3*k4
        H2cit = h*Hcit*k3
        H3cit = h*H2cit*k2
        ni2pfree = (nio2*k1*(h**2))/(1+((nio2*k1*(h**2))/ni_total))
        NiH2cit = k7*ni2pfree*H2cit
        NiHcit = k6*ni2pfree*Hcit
        Nicit = k5*ni2pfree*cit3
        nh3 = k8*nh4/h
        nin4p2 = k9*(nh4**4)/(h**2)
        nin6p2 = k10*(nh4**6) /(h**4)
        return (citrate_total - Hcit - H2cit - H3cit - Nicit - NiHcit - NiH2cit - cit3,
                ni_total - Nicit - NiHcit - NiH2cit - ni2pfree - nin4p2- nin6p2- nio2,
                ammonia_total-nh3-4*nin4p2-6*nin6p2-nh4)
    initial_guess=[0.1,0.1,0.1]
    res = minimize(equations,initial_guess)
    cit3 = res.x[0]
    nio2 = res.x[1]
    nh4 = res.x[2]
    ni2pfree = (nio2 * k1 * (h**2)) / (1 + ((nio2 * k1 * (h**2)) / ni_total))
    Hcit = h * cit3 *k4
    H2cit = h * Hcit * k3
    H3cit = h * H2cit * k2
    NiH2cit = k7 * ni2pfree * H2cit
    NiHcit = k6 * ni2pfree * Hcit
    Nicit = k5 * ni2pfree * cit3
    nh3 = k8 * nh4 / h
    nin4p2 = k9 * (nh4**4) / (h**2)
    nin6p2 = k10 * (nh4**6) / (h**4)
    return [cit3, nio2, nh4, ni2pfree, Hcit, H2cit, H3cit, NiH2cit, NiHcit, Nicit,nh3,nin4p2,nin6p2]
q43xntqr

q43xntqr1#

函数scipy.optimize.minimize()(其中)将目标fun和初始值x0作为自变量。fun必须返回单个真实的(也称为标量);而不是列表或元组。
相反,您的函数返回

def equations(p):
     # code 
     return (..., ..., ...)

更改为

def equations(p):
     # code 
     return x

equations()的函数值x进行比较,您实际上想要最小化equations()

相关问题