简体   繁体   English

如何将2个矩阵放入scipy.optimize.minimize?

[英]How Do I put 2 matrix into scipy.optimize.minimize?

I work with the scipy.optimize.minimize function. 我使用scipy.optimize.minimize函数。 My purpose is get w,z which minimize f(w,z) 我的目的是得到w,z最小化f(w,z)

Both w and z are n by m matrices: wz都是n × m矩阵:

[[1,1,1,1],
 [2,2,2,2]]

f(w,z) is receive parameter w and z. f(w,z)是接收参数w和z。

I already tried the form given below: 我已经尝试过以下表格:

def f(x):
   w = x[0]
   z = x[1]
   ...

minimize(f, [w,z])

but, minimize does not work well. 但是,最小化不起作用。

What is the valid form to put two matrices ( n by m ) into scipy.optimize.minimize ? 将两个矩阵( nm )放入scipy.optimize.minimize的有效形式是什么?

Optimize needs a 1D vector to optimize. 优化需要1D向量来优化。 You are on the right track. 你走在正确的轨道上。 You need to flatten your argument to minimize and then in f , start with x = np.reshape(x, (2, m, n)) then pull out w and z and you should be in business. 您需要将您的参数展平为minimize ,然后在f ,从x = np.reshape(x, (2, m, n))然后拉出wz ,您应该开展业务。

I've run into this issue before. 我之前遇到过这个问题。 For example, optimizing parts of vectors in multiple different classes at the same time. 例如,同时优化多个不同类中的向量部分。 I typically wind up with a function that maps things to a 1D vector and then another function that pulls the data back out into the objects so I can evaluate the cost function. 我通常最终得到一个函数,它将事物映射到一维矢量,然后另一个函数将数据拉回到对象中,这样我就可以评估成本函数。 As in: 如:

def toVector(w, z):
    assert w.shape == (2, 4)
    assert z.shape == (2, 4)
    return np.hstack([w.flatten(), z.flatten()])

def toWZ(vec):
    assert vec.shape == (2*2*4,)
    return vec[:2*4].reshape(2,4), vec[2*4:].reshape(2,4)

def doOptimization(f_of_w_z, w0, z0):
    def f(x): 
        w, z = toWZ(x)
        return f_of_w_z(w, z)

    result = minimize(f, toVec(w0, z0))
    # Different optimize functions return their
    # vector result differently. In this case it's result.x:
    result.x = toWZ(result.x) 
    return result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM