How to shuffle a “DenseMatrix” in F#

前端 未结 3 1584
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 09:24

In Matlab we can write the following code to shuffle a matrix:

data = data(:, randperm(size(data,2)));

there is what I write with Math.NET:

3条回答
  •  旧巷少年郎
    2021-01-19 10:06

    With Neural Networks I had to shuffle an array of Matrices and used the following code. Note the base data structure is an array ([]) and each item in the array is a Matrix. This is not shuffling a matrix, but an array. It should give you some idea of how to proceed for your problem.

    type Random() = 
        static member Shuffle (a : 'a[]) =
            let rand = new System.Random()
            let swap (a: _[]) x y =
                let tmp = a.[x]
                a.[x] <- a.[y]
                a.[y] <- tmp
            Array.iteri (fun i _ -> swap a i (rand.Next(i, Array.length a))) a
    

    and called it like

    Random.Shuffle trainingData
    

    Addendum

    Here is the code to convert a byte[] to a DenseMatrix of double

    let byteArrayToMatrix (bytes : byte[]) : Matrix =
        let (x : Vector) = Vector.Build.DenseOfArray bytes
        let (y : Vector) = x.Map(fun x -> double x)
        let (z : Matrix) = Matrix.Build.DenseOfRowVectors y
        z
    

提交回复
热议问题