Donbeo
Donbeo

Reputation: 17617

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?

Upvotes: 1

Views: 2479

Answers (3)

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)

Upvotes: 0

dlwh
dlwh

Reputation: 2293

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)

Upvotes: 2

Darren Wilkinson
Darren Wilkinson

Reputation: 321

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.

Upvotes: 1

Related Questions