【问题标题】:Framing the least squares function using fmin_slsqp使用 fmin_slsqp 构建最小二乘函数
【发布时间】:2013-11-08 02:16:11
【问题描述】:

我是优化新手。我正在尝试使用scipy.optimize 中的fmin_slsqp 函数解决线性最小二乘问题。

我的目标函数是 |q0_T*P-q1_T| 平方的 frobenius 范数,其中 q0_TnX1 向量的转置,PnXn 矩阵,q1_T 是 @987654329 的转置@向量。这基本上是一个马尔科夫过程,其中q 向量作为处于某个状态的概率,P 是转移概率矩阵。

目标函数将被最小化 w.r.t P 其中约束是:

1) P 中的所有元素都必须是非负数

2) P 中的所有行的总和必须为 1

我已经定义了这个我不确定是否正确的目标函数:

def func(P, q):
  return (np.linalg.norm(np.dot(transpose(q[0,]),P)-transpose(q[1,])))**2

fmin_slsqp 中的第二个参数要求一个 1D ndarray x0,它是自变量的初始猜测。但是在这里,由于我的自变量是 P,所以我需要一个二维数组来进行初始猜测。我不确定我是否正确地构建了问题,或者我将不得不使用其他功能。谢谢。

【问题讨论】:

    标签: python numpy scipy linear-programming


    【解决方案1】:

    因此存在一个问题,它只接受一维数组作为自变量,一种骇人听闻的解决方案是将其作为一维传递,并在函数中重新整形。

    import numpy as np
    from scipy.optimize import fmin_slsqp
    
    # some fake data
    d = 3 # dimensionality of the problem
    P0 = np.arange(d*d).reshape(d, d)
    P0 /= P0.sum(1, keepdims=True) # so that each row sums to 1
    q = np.random.rand(2, d)       # assuming this is the structure of your q
    q /= q.sum(1, keepdims=True)
    
    # the function to minimize
    def func(P, q):
        n = q.shape[-1] # or n = np.sqrt(P.size)
        P = P.reshape(n, n)
        return np.linalg.norm(np.dot(q[0], P) - q[1])**2  # no changes here, just simplified syntax
    
    def row_sum(P0, q):
        """ row sums - 1 are zero """
        n = np.sqrt(P0.size)
        return P0.reshape(n,n).sum(1) - 1.
    
    def non_neg(P0, q):
        """ all elements >= 0 """
        return P0
    
    P_opt = fmin_slsqp(func, P0.ravel(), args=(q,), f_eqcons=row_sum, f_ieqcons=non_neg).reshape(d, d)
    
    assert np.allclose(P_opt.sum(1), 1)
    assert np.all(P_opt >= 0)
    

    【讨论】:

    • 谢谢askewchan。该代码完美运行。我只是想知道我在 P_opt (~e-32) 中看到了极小的负值。它们只是我可以安全地四舍五入为 0 的数值错误,还是优化过程有问题?
    • 不客气@Nitin!出于所有意图和目的,我会认为0。使用我的随机数据(d=3),P0 的所有值大致在 .1.5 之间
    猜你喜欢
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多