我正在插入Math.net进行一些采样,我只是不知道应该如何工作......我在这里缺少什么?
let mm = Double.DenseMatrix.Identity(2)
let ida = Double.DenseMatrix.Identity(2)
let idb = Double.DenseMatrix.Identity(2)
let generator = MatrixNormal(mm, ida, idb)
generator.Density(mm)
我得到了
System.ArgumentOutOfRangeException: Matrix dimensions must agree.
Parameter name: x
at MathNet.Numerics.Distributions.MatrixNormal.Density(Matrix`1 x) in c:\TeamCity\buildAgent\work\392bcd0e1411b00f\src\Numerics\Distributions\Multivariate\MatrixNormal.cs:line 241
at <StartupCode$FSI_0079>.$FSI_0079.main@()
Stopped due to error
当我查看github源
时,这里有多么奇怪 public double Density(Matrix<double> x) {
if (x.RowCount != _m.RowCount || x.ColumnCount != _m.ColumnCount)
{
throw Matrix.DimensionsDontMatch<ArgumentOutOfRangeException>(x, _m, "x");
}
修改
重新启动它所有工作后的2 * 2矩阵均值,但不是2 * 1(调整列方差后)。非常奇怪的是,在定义上有一些维度检查。然而,错误消息是在调用时。可能是检查错误行方差和列方差,并在调用时使用正确的一个。 所有这些都强调了丰富类型检查的强大优势。
对于好奇,这是一个多变量实现。 虽然没有检查..
let sampleNormal =
let rnd = new MersenneTwister()
fun () ->
let rec randomNormal () =
let u1, u2 = rnd.NextDouble(),rnd.NextDouble()
let r = sqrt (-2. * (log u1))
let theta = 2. * System.Math.PI * u2
seq { yield r * sin theta
yield r * cos theta
yield! randomNormal() }
randomNormal ()
let generate covar =
let chol = Double.Factorization.DenseCholesky(covar)
let a = chol.Factor
fun () -> let v = vector ( sampleNormal() |> Seq.take(covar.ColumnCount) |> List.ofSeq )
a * v
//generate covar
let generatecovar = generate covar
let generaten n covar = Seq.init n (fun _ -> generatecovar ())
修改
Cholesky因完全相关的输入而失败,这没关系
let mapply (m:Generic.Matrix<float>) f = m.IndexedEnumerator() |> Seq.iter(fun (i,j,v) -> m.[i,j] <- f v ); m
let generate (covar:Generic.Matrix<float>) =
let R = if covar.Determinant() = 0. then // we want covar = R.RT // C = U D1/2.D1/2 U' = (RT.QT) Q.R = RT.RTT
let u, d, vt = let t = covar.Svd(true) in t.U(), t.W(), t.VT()
let A = (mapply d sqrt) * u.Transpose()
let qr = A.QR() in qr.R.Transpose()
else
let chol = covar.Cholesky()
chol.Factor
fun () -> let v = vector ( sampleNormal() |> Seq.take(covar.ColumnCount) |> List.ofSeq )
R * v
答案 0 :(得分:1)
我发现你的代码没有任何问题。您确定要运行正确的代码吗?也许错误版本的库代码,甚至是你自己的?尝试重新启动FSI,甚至重新编译库。