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"