0

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?

Donbeo
  • 17,067
  • 37
  • 114
  • 188

3 Answers3

2

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)

dlwh
  • 2,257
  • 11
  • 23
  • @9codeMan9 that's not true. it accepts a breeze.stats.distributions.Rand generator. – dlwh Dec 07 '15 at 00:47
  • You are correct @dlwh I just realized I was using a "breeze.jar" in my library that wasn't allowing for syntax. I have appropriately redacted my incorrect comment :-) – 9codeMan9 Dec 08 '15 at 02:56
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.

  • FWIW, I prefer to keep the (int, int, array) constructor requiring "new", because I want "advanced" constructors (i.e. those that require knowledge of how the data structure is laid out) to be distinct from the normal way of creating them. – dlwh Aug 16 '15 at 22:11
  • @dlwh I think this example was reported in the linear algebra worksheet. It should probably updated. – Donbeo Aug 17 '15 at 01:30
0

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)