【问题标题】:How to minimize function like this如何最小化这样的功能
【发布时间】:2020-05-05 17:54:18
【问题描述】:

功能:

def Phi(u, X):
    return -(1+u[0]*X[0]+u[1]*X[1]+u[2]*X[2]+u[3]*X[3])

而且我知道X[0]...X[3][-0.08,0.08]u[0],u[1],u[2],u[3] >= 0u[0]+u[1]+u[2]+u[3] = 1 中,我也知道我的函数的梯度。然后我定义了约束:

def constraint1(u):
    return u[0]+u[1]+u[2]+u[3]-1.0
def constraint2(u):
    return u[0]-1.0
def constraint3(u):
    return u[1]-1.0
def constraint4(u):
    return u[2]-1.0
def constraint5(u):
    return u[3]-1.0

和界限

bnds = Bounds ([-0.08, -0.08, -0.08], [0.08, 0.08, 0.08])
cons = [{'type': 'eq', 'fun': constraint1},
               {'type': 'ineq', 'fun': constraint2},
               {'type': 'ineq', 'fun': constraint3},
               {'type': 'ineq', 'fun': constraint4},
               {'type': 'ineq', 'fun': constraint5},]
print(minimize(Phi, method='BFGS', jac=grad, constraints=cons, bounds=bnds))

但我有“TypeError: minimize() missing 1 required positional argument: 'x0'”。我还没有关于x0 的信息。是正确地最小化带有约束的函数还是不可能做到这一点?

更新

结果是

def Phi2(params):
    u0,u1,u2,u3,x0,x1,x2,x3 = params
    return -(1+u0*x0+u1*x1+u2*x2+u3*x3)


x0 = np.asarray([0,0,0,0,0,0,0,0])

def constraint1(params):
    u0,u1,u2,u3,x0,x1,x2,x3 = params
    return u0+u1+u2+u3-1.0


bnds = Bounds ([0,0,0,0,-0.08,-0.08,-0.08,-0.08,], [1,1,1,1,0.08, 0.08, 0.08])

cons = [{'type': 'eq', 'fun': constraint1}]
print(minimize(Phi2,x0, method='BFGS', constraints=cons, bounds=bnds))

但是有一些问题。我在numpy数组'grad'中有u0,u1,u2,u3的渐变。如何正确使用?如果我在最小化参数中执行 jac=grad 那么结果是

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

【问题讨论】:

  • 另外:BFGS 不支持约束。查阅文档。

标签: python scipy linear-programming minimize


【解决方案1】:

scipy documentation 表示 x0 它是一个位置参数,因此它是必需的。

关于 x0 是这样说的:

初步猜测。大小为 (n,) 的实数元素数组,其中“n”是自变量的数量。

您似乎至少必须提供最初的猜测。你试过提供一个空数组吗?

【讨论】:

  • 当我添加 x0 (x0 = np.zeros(shape=(1,4))) 以最小化时,我有“TypeError: Phi() missing 1 required positional argument: 'X'”
  • 失败的原因是 scipy 期望 Phi 是这样的函数:fun(x, *args) 其中*args 是一个常量列表,但在你有Phi(u, X) 其中X 是不是恒定的。
  • 这样的功能不能最小化我理解正确吗?
  • 应该有可能,这篇文章给出了一些线索:stackoverflow.com/questions/13670333/…我看看我能理解它。
猜你喜欢
  • 1970-01-01
  • 2012-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-04
  • 2020-05-14
  • 1970-01-01
相关资源
最近更新 更多