简体   繁体   中英

scala breeze matrix of random normal values

I want the same result that is obtained in python with

x=np.random.normal(0, 1, (n_samples, n_features))

I have tried:

import breeze.linalg._

object HelloWorld {
  def main(args: Array[String]) {
    println("Start")

    val n_samples = 5
    val n_features = 3

    val normal01 = breeze.stats.distributions.Gaussian(0, 1)
    val samples = normal01.sample(n_features*n_features)

    val X = DenseMatrix(n_samples, n_features,  samples) // return an error



    //print(X)
  }
}

Where is the error?

A simple alternative implementation:

val normal01 = breeze.stats.distributions.Gaussian(0, 1)
DenseMatrix.rand(n_samples, n_features, normal01)

The .rand constructor accepts an optional random generator, which defaults to Uniform(0, 1)

Replace the matrix creation line with:

val X = new DenseMatrix[Double](n_samples, n_features, samples.toArray)

and then fix the typo on the previous line.

For some reason this constructor doesn't seem to be in the companion object, so you have to use the "new" keyword (this is probably a bug in Breeze, so you could file it as an issue). Also, you need to coerce "samples" into a regular Scala Array.

This is a solution for np.random.normal in Python with a seed (same seed generates same ramdoms)

implicit val randBasis: RandBasis = new RandBasis(new ThreadLocalRandomGenerator(new MersenneTwister(seed)))
val Gausian = breeze.stats.distributions.Gaussian(0.0, 1.0)
val R: DenseMatrix[Double] = DenseMatrix.rand(numRows, numColumns, Gausian)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM