函数返回一个向量,如何通过NumPy最小化 [英] Function returns a vector, how to minimize in via NumPy

查看:53
本文介绍了函数返回一个向量,如何通过NumPy最小化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试最小化函数,该函数返回值的向量,这是一个错误:

I'm trying to minimize function, that returns a vector of values, and here is an error:

设置具有序列的数组元素

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]]

At these values of P, Ps, x function returns [[ 47.45143225 16.81 44.89 ]]

谢谢您的任何建议

UPD(完整追溯)

    Traceback (most recent call last):

  File "<ipython-input-125-9649a65940b0>", line 1, in <module>
    runfile('C:/Users/Roark/Documents/Python Scripts/optimize.py', wdir='C:/Users/Roark/Documents/Python Scripts')

  File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 585, in runfile
    execfile(filename, namespace)

  File "C:/Users/Roark/Documents/Python Scripts/optimize.py", line 28, in <module>
    main()

  File "C:/Users/Roark/Documents/Python Scripts/optimize.py", line 24, in main
    print minimize(objective, x, method='Nelder-Mead')

  File "C:\Anaconda\lib\site-packages\scipy\optimize\_minimize.py", line 413, in minimize
    return _minimize_neldermead(fun, x0, args, callback, **options)

  File "C:\Anaconda\lib\site-packages\scipy\optimize\optimize.py", line 438, in _minimize_neldermead
    fsim[0] = func(x0)

ValueError: setting an array element with a sequence.

UPD2:功能应最小化(PS是向量)

推荐答案

如果您希望结果向量成为仅包含 0 s的向量,则可以使用 fsolve 这样做.为此,需要稍微修改目标函数,以使输入和输出具有相同的形状:

If you want you resulting vector to be a vector containing only 0s, you can use fsolve to do so. To do that will require modifying your objective function a little bit to get the input and output into the same shape:

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])

这篇关于函数返回一个向量,如何通过NumPy最小化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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