函数返回一个向量,如何通过NumPy最小化

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

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

我试着最小化函数,它返回一个向量值, 这里有一个错误:

setting an array element with a sequence

代码:

P = np.matrix([[0.3, 0.1, 0.2], [0.01, 0.4, 0.2], [0.0001, 0.3, 0.5]])  
Ps = np.array([10,14,5])

def objective(x):   
    x = np.array([x])
    res = np.square(Ps - np.dot(x, P)) 
    return res 

def main():
    x = np.array([10, 11, 15])
    print minimize(objective, x, method='Nelder-Mead')

对于这些p,Ps,x函数返回[[47.45143225 16.81 44.89]]

谢谢你的建议

UPD(完全回溯)

^{pr2}$

UPD2:函数应最小化(Ps是一个向量)

enter image description here


Tags: 函数代码andef错误withnpres
2条回答

目标函数需要返回标量值,而不是向量。您可能希望返回平方误差的,而不是平方误差的向量:

def objective(x):
    res = ((Ps - np.dot(x, P)) ** 2).sum()
    return res 

如果希望得到的向量是只包含0s的向量,可以使用fsolve来实现。为此,需要稍微修改一下目标函数,以使输入和输出的形状相同:

import scipy.optimize as so
P = np.matrix([[0.3, 0.1, 0.2], [0.01, 0.4, 0.2], [0.0001, 0.3, 0.5]])  
Ps = np.array([10,14,5])

def objective(x):   
    x = np.array([x])
    res = np.square(Ps - np.dot(x, P)) 
    return np.array(res).ravel() 
Root = so.fsolve(objective, x0=np.array([10, 11, 15]))
objective(Root)
#[  5.04870979e-29   1.13595970e-28   1.26217745e-29]

结果:溶液为np.array([ 31.95419775, 41.56815698, -19.40894189])

相关问题 更多 >

    热门问题