- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用以下方法解决约束优化问题cipy.optimize.minimize
但到目前为止没有成功。
具体来说,我想最小化 y1
和 y2
上的目标函数:
f(y1,y2)=(x1(y1,y2)-x1)^2+(x2(y1,y2)-x2)^2
受约束:
y1*y2>0
目标是为不同的 x1
和 x2
对找到 y1
和 y2
的值。
这是我目前的情况
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/
考虑一个相关矩阵 r,表示变量 1 到 10 之间的相关性: r thr)) NA else sum(score[x]) }) min(summed_score, na.rm=T) ## [1] 1
我在 firebase 中有一个值需要增加,它受竞争条件的影响,所以我更愿意一次完成所有这些。 node: { clicks: 3 } 我需要设置 clicks = cli
我是一名优秀的程序员,十分优秀!