1

The hessian function in Diffsharp returns something called System.Double[,]. Or if you hover on the variable it shows as a float[,]. This object seems a bit difficult to parse, I'm not sure why. This question is related but the answer doesn't seem general enough as it only deals with a specific size of matrix.

I'm wondering if anyone has any cleaner way than the following to massage this object into a DenseMatrix. The matrices returned will always be square.

I want to change this:

System.Double[,]
[[-1.008660933; 9.992007222e-06]
 [9.992007222e-06; 0.4999911596]]

to this but cleanly:

MathNet.Numerics.LinearAlgebra.Double.DenseMatrix
DenseMatrix 2x2-Double
   -1.00866  9.99201E-06
9.99201E-06     0.499991

Here is my code. This just looks a bit awkward amid the rest of the F# code.

let hessianToMatrix (h: float[,]) = 
    let v = h |> Seq.cast<float> |> Seq.toArray |> DenseVector
    let dim = float v.Count |> sqrt |> int    
    let m = DenseMatrix.init dim dim (fun i j -> 0.)
    for r in 0 .. dim-1 do
        for c in 0 .. dim-1 do
            m.[r, c] <- v.[r*dim + c]
    m

let hess = hessian llNormal [|5.; 1.|] |> hessianToMatrix
hess.GetType() |> printfn "\n\n\n%A"
hess |> printfn "%A"
4

1 回答 1

2

F# 中的 float 是 .Net 中 double 的同义词。而 float [,] 是一个二维数组。您可以将其转换为 Densematrix:

let rnd = System.Random()
let x2d = Array2D.init 2 2 (fun i j -> rnd.NextDouble()) 
x2d |> DenseMatrix.ofArray2

我得到:

val it : Matrix<float> =
  DenseMatrix 2x2-Double
0.438629  0.462749
0.386625  0.740308

{ColumnCount = 2;
 Item = ?;
 RowCount = 2;
 Storage = MathNet.Numerics.LinearAlgebra.Storage.DenseColumnMajorMatrixStorage`1[System.Double];
 Values = [|0.4386289918; 0.3866254107; 0.4627486283; 0.7403077645|];}
于 2016-07-13T01:41:53.193 回答