【问题标题】:Scipy optimize is just not dealing with the boundScipy优化只是不处理界限
【发布时间】:2020-02-29 09:36:27
【问题描述】:

我正在尝试为许多不同的 K 值解决以下问题:

我正在尝试使用 scipy 优化以获得更大的通用性(在某个阶段我希望能够更改功能)。

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from scipy import optimize

n=10

p1 = 0.2
p2 = 0.3
orig = (0,0)
endw = (1,1)

def U1(x):
    return p1*(x[0])**0.5 + (1-p1)*(x[1])**0.5
def U2(x):
    return p2*(1-x[0])**0.5 + (1-p2)*(1-x[1])**0.5


itervals = np.linspace(endw, orig, n)
utvals = np.array([U2(vec) for vec in itervals])
parvals = np.zeros((2, len(utvals)))

for it in range(len(utvals)):
    def obj(x):
        return -U1(x)
    def constr(x):
        return -U2(x)+utvals[it]
    con = {'type': 'eq', 'fun': constr}
    res = optimize.minimize(obj, itervals[it], method='SLSQP', constraints=con)
    parvals[:, it] = res['x']
    print(constr(parvals[:,it]), utvals[it])

但是,当我检查是否遵守约束时,我会在上面的代码中得到 constr(parvals[:,it]) 的负值,如果我将约束转为

    def constr(x):
        return U2(x)-utvals[it]

我得到constr(parvals[:,it]) 的正值。怎么会?

我的意思是,我最初的猜测(包含在 itervals 中)总是为约束返回 0。所以总有可能达到0,为什么有时为正有时为负?

【问题讨论】:

  • 附带说明,如果K >= 0x1 = x2 = 1 似乎是最佳的,否则问题似乎不可行。
  • @hilberts_drinking_problem,你是对的。我已经纠正了这个问题。但是您仍然可以看到,它没有给出正确的答案。
  • 在查看级别之前始终检查结果的状态。

标签: python optimization scipy constraints


【解决方案1】:

改变 K 我们会发现不同的解对 (x1, x2)。使用拉格朗日乘数(施加一阶条件)解决最大化问题很容易看出 x2 必须是 x1 的函数,即,此代码给出了所需的关系:

Psi = (p1/p2*(1-p2)/(1-p1))**2
def realline(x1):
    return x1/(Psi+(1-Psi)*x1)

很容易看出,用正确的符号定义约束,解几乎处处重合:

    def constr(x):
        return U2(x)-utvals[it]
    con = {'type': 'ineq', 'fun': constr}

【讨论】:

    猜你喜欢
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 2016-10-11
    • 2013-08-15
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多