【问题标题】:Function which returns the least-squares solution to a linear matrix equation返回线性矩阵方程的最小二乘解的函数
【发布时间】:2016-06-15 13:04:46
【问题描述】:

我一直在尝试将代码从 Python 重写为 Swift,但我被困在应该返回线性矩阵方程的最小二乘解的函数上。有谁知道用 Swift 编写的库,它具有与 numpy.linalg.lstsq 等效的方法?非常感谢您的帮助。

Python 代码:

a = numpy.array([[p2.x-p1.x,p2.y-p1.y],[p4.x-p3.x,p4.y-p3.y],[p4.x-p2.x,p4.y-p2.y],[p3.x-p1.x,p3.y-p1.y]])
b = numpy.array([number1,number2,number3,number4])
res = numpy.linalg.lstsq(a,b) 
result = [float(res[0][0]),float(res[0][1])]
return result

到目前为止的 Swift 代码:

var matrix1 = [[p2.x-p1.x, p2.y-p1.y],[p4.x-p3.x, p4.y-p3.y], [p4.x-p2.x, p4.y-p2.y], [p3.x-p1.x, p3.y-p1.y]]
var matrix2 = [number1, number2, number3, number4]

【问题讨论】:

  • 在此处添加代码!没有代码就帮不上忙。
  • Accelerate framework 包括具有Linear Least Squares Problems 功能的BLAS library。不过,在 Swift 中使用这些函数需要一些工作:)
  • 很遗憾,没有解决 LLS 问题的方法。
  • DGELS(或其变体之一)不是您需要的吗?
  • 有一些注意事项,但如果你有一个超定系统的 n 方程在 2 个变量中,即如果你的问题可以写成 A * x = bA 具有形状 (n, 2)x 形状(2,)b 形状(n,),那么最小二乘解与等价A.T * A * x = A.T * b 的解相同,并且由于A.T * A 具有形状(2, 2)A.T * b 具有形状(2,),您有一个非常简单的系统,可以轻松解决,例如使用Cramer's rule。从头开始编写应该非常简单。

标签: python swift numpy math matrix


【解决方案1】:

Accelerate 框架包括LAPACK 线性代数包, 它有一个DGELS 函数来解决欠定或超定线性系统。来自文档:

DGELS 求解超定或欠定实线性系统 涉及 M×N 矩阵 A 或其转置,使用 QR 或 LQ A的因式分解。假设A有满秩。

这是一个如何在 Swift 中使用该函数的示例。 本质上是this C sample code的翻译。

func solveLeastSquare(A A: [[Double]], B: [Double]) -> [Double]? {
    precondition(A.count == B.count, "Non-matching dimensions")

    var mode = Int8(bitPattern: UInt8(ascii: "N")) // "Normal" mode
    var nrows = CInt(A.count)
    var ncols = CInt(A[0].count)
    var nrhs = CInt(1)
    var ldb = max(nrows, ncols)

    // Flattened columns of matrix A
    var localA = (0 ..< nrows * ncols).map {
        A[Int($0 % nrows)][Int($0 / nrows)]
    }

    // Vector B, expanded by zeros if ncols > nrows
    var localB = B
    if ldb > nrows {
        localB.appendContentsOf([Double](count: ldb - nrows, repeatedValue: 0.0))
    }

    var wkopt = 0.0
    var lwork: CInt = -1
    var info: CInt = 0

    // First call to determine optimal workspace size
    dgels_(&mode, &nrows, &ncols, &nrhs, &localA, &nrows, &localB, &ldb, &wkopt, &lwork, &info)
    lwork = Int32(wkopt)

    // Allocate workspace and do actual calculation
    var work = [Double](count: Int(lwork), repeatedValue: 0.0)
    dgels_(&mode, &nrows, &ncols, &nrhs, &localA, &nrows, &localB, &ldb, &work, &lwork, &info)

    if info != 0 {
        print("A does not have full rank; the least squares solution could not be computed.")
        return nil
    }
    return Array(localB.prefix(Int(ncols)))
}

一些注意事项:

  • dgels_() 修改传入的矩阵和向量数据,期望 矩阵为“平面”数组,包含A 的列。 右侧也应为长度为max(M, N) 的数组。 为此,首先将输入数据复制到局部变量中。
  • 所有参数都必须通过引用dgels_() 来传递,这就是为什么 它们都存储在vars 中。
  • C 整数是一个 32 位整数,它在 IntCInt 必要。

示例 1: 超定系统,来自http://www.seas.ucla.edu/~vandenbe/103/lectures/ls.pdf

let A = [[ 2.0, 0.0 ],
         [ -1.0, 1.0 ],
         [ 0.0, 2.0 ]]
let B = [ 1.0, 0.0, -1.0 ]
if let x = solveLeastSquare(A: A, B: B) {
    print(x) // [0.33333333333333326, -0.33333333333333343]
}

示例 2: 欠定系统,最小范数 x_1 + x_2 + x_3 = 1.0的解决方案。

let A = [[ 1.0, 1.0, 1.0 ]]
let B = [ 1.0 ]
if let x = solveLeastSquare(A: A, B: B) {
    print(x) // [0.33333333333333337, 0.33333333333333337, 0.33333333333333337]
}

Swift 3Swift 4 更新:

func solveLeastSquare(A: [[Double]], B: [Double]) -> [Double]? {
    precondition(A.count == B.count, "Non-matching dimensions")

    var mode = Int8(bitPattern: UInt8(ascii: "N")) // "Normal" mode
    var nrows = CInt(A.count)
    var ncols = CInt(A[0].count)
    var nrhs = CInt(1)
    var ldb = max(nrows, ncols)

    // Flattened columns of matrix A
    var localA = (0 ..< nrows * ncols).map { (i) -> Double in
        A[Int(i % nrows)][Int(i / nrows)]
    }

    // Vector B, expanded by zeros if ncols > nrows
    var localB = B
    if ldb > nrows {
        localB.append(contentsOf: [Double](repeating: 0.0, count: Int(ldb - nrows)))
    }

    var wkopt = 0.0
    var lwork: CInt = -1
    var info: CInt = 0

    // First call to determine optimal workspace size
    var nrows_copy = nrows // Workaround for SE-0176
    dgels_(&mode, &nrows, &ncols, &nrhs, &localA, &nrows_copy, &localB, &ldb, &wkopt, &lwork, &info)
    lwork = Int32(wkopt)

    // Allocate workspace and do actual calculation
    var work = [Double](repeating: 0.0, count: Int(lwork))
    dgels_(&mode, &nrows, &ncols, &nrhs, &localA, &nrows_copy, &localB, &ldb, &work, &lwork, &info)

    if info != 0 {
        print("A does not have full rank; the least squares solution could not be computed.")
        return nil
    }
    return Array(localB.prefix(Int(ncols)))
}

【讨论】:

  • 这太棒了!谢谢!
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 2022-11-15
  • 1970-01-01
相关资源
最近更新 更多