numpy或sympy执行非线性优化

numpy或sympy执行非线性优化

本文介绍了如何使用scipy/numpy或sympy执行非线性优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到Python中方程的跟随系统的最佳解决方案:

I am trying to find the optimal solution to the follow system of equations in Python:

(x-x1)^2 + (y-y1)^2 - r1^2 = 0
(x-x2)^2 + (y-y2)^2 - r2^2 = 0
(x-x3)^2 + (y-y3)^2 - r3^2 = 0

给出值一个点(x,y)和一个半径(r):

Given the values a point(x,y) and a radius (r):

x1, y1, r1 = (0, 0, 0.88)
x2, y2, r2 = (2, 0, 1)
x3, y3, r3 = (0, 2, 0.75)

找到针对点(x,y)的最佳解决方案的最佳方法是什么使用上面的示例将是:
〜(1,1)

What is the best way to find the optimal solution for the point (x,y)Using the above example it would be:
~ (1, 1)

推荐答案

如果我正确理解了您的问题,我认为这就是您所追求的:

If I understand your question correctly, I think this is what you're after:

from scipy.optimize import minimize
import numpy as np

def f(coord,x,y,r):
    return np.sum( ((coord[0] - x)**2) + ((coord[1] - y)**2) - (r**2) )

x = np.array([0,   2,  0])
y = np.array([0,   0,  2])
r = np.array([.88, 1, .75])

# initial (bad) guess at (x,y) values
initial_guess = np.array([100,100])

res = minimize(f,initial_guess,args = [x,y,r])

哪个产量:

>>> print res.x
[ 0.66666666  0.66666666]

您也可以尝试使用最小二乘法,该方法期望返回矢量的目标函数.它希望最小化此向量的平方和.使用最小二乘法,您的目标函数应如下所示:

You might also try the least squares method which expects an objective function that returns a vector. It wants to minimize the sum of the squares of this vector. Using least squares, your objective function would look like this:

def f2(coord,args):
    x,y,r = args
    # notice that we're returning a vector of dimension 3
    return ((coord[0]-x)**2) + ((coord[1] - y)**2) - (r**2)

您将像这样将其最小化:

And you'd minimize it like so:

from scipy.optimize import leastsq
res = leastsq(f2,initial_guess,args = [x,y,r])

哪个产量:

>>> print res[0]
>>> [ 0.77961518  0.85811473]

这基本上与使用minimize相同,并将原始目标函数重写为:

This is basically the same as using minimize and re-writing the original objective function as:

def f(coord,x,y,r):
    vec = ((coord[0]-x)**2) + ((coord[1] - y)**2) - (r**2)
    # return the sum of the squares of the vector
    return np.sum(vec**2)

这将产生:

>>> print res.x
>>> [ 0.77958326  0.8580965 ]

请注意,argsleastsq的处理方式略有不同,并且两个函数返回的数据结构也不同.请参阅 scipy.optimize.minimize的文档. 以获得更多详细信息.

Note that args are handled a bit differently with leastsq, and that the data structures returned by the two functions are also different. See the documentation for scipy.optimize.minimize and scipy.optimize.leastsq for more details.

有关更多优化选项,请参见 scipy.optimize 文档.

See the scipy.optimize documentation for more optimization options.

这篇关于如何使用scipy/numpy或sympy执行非线性优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 17:08