gpt4 book ai didi

python - 最小化受约束的函数

转载 作者:行者123 更新时间:2023-11-28 18:03:53 26 4
gpt4 key购买 nike

我正在尝试使用以下方法解决约束优化问题cipy.optimize.minimize 但到目前为止没有成功。

具体来说,我想最小化 y1y2 上的目标函数:

f(y1,y2)=(x1(y1,y2)-x1)^2+(x2(y1,y2)-x2)^2

受约束:

y1*y2>0

目标是为不同的 x1x2 对找到 y1y2 的值。

这是我目前的情况

def f(x1,x2):
k=(x1(y1,y2)-x1)^2+(x2(y1,y2)-x2)^2
return k

但我不确定如何设置包含上述约束的函数:

def constraint(x):
....

一旦我有了约束,下面的语法是否正确?

optimize.minimize(f, np.array([0, 0]), method="SLSQP",
constraints={"fun": constraint, "type": "ineq"})

我是 Python 新手,如有任何帮助,我们将不胜感激。

最佳答案

对于约束。来自docs :

Equality constraint means that the constraint function result is to be zero whereas inequality means that it is to be non-negative. Note that COBYLA only supports inequality constraints.

因此,您的约束只是一个必须为非负的函数。在你的情况下:

def constraint(y):
return y[0] * y[1]

注意函数必须输入一个向量。例如:

def f(x):
x1, x2 = x
return x1**2 + x2**2

编辑 使用尝试拟合计算数据与观察数据的函数。

def calculated_x(y):
""" example """
y1, y2 = y
x1 = 0.5 + 0.2 * y1 + 0.3 * y2
x2 = 0.4 + 0.1 * y1 + 0.3 * y2

def f(y, x1, x2):
x1_calc, x2_calc = calculated_x(y)
return (x1- x1_calc)**2 + (x2 - x2_calc)**2

m = minimize(f, [0,0], args=(3,2), constraints=({'fun': lambda y: y[0] * y[1], 'type': 'ineq'},))
print(m)
>> array([3, 1.999999])

您还可以根据您的最小化构建一个函数(上面的示例):

def minimize_y(x1, x2):
# note that x1 and x2 become arguments
m = minimize(f, [0,0], args=(x1,x2), constraints=({'fun': lambda y: y[0] * y[1], 'type': 'ineq'},)
return m.x

关于python - 最小化受约束的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54656237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com