Search code examples
scalarandommultinomialscala-breezescala-nlp

Using Multinomial Distribution with Scala and Breeze package


I'm using the breeze package with Scala 2.10.3, and I'd like to sample from a multinomial distribution.

I.e. I'd like to sample values of a random variable Y, where

Y ~ Multinomial(Y1 = 0, Y2 = 1, Y3 = 3; p1 = 0.2, p2 = 0.5, p3 = 0.3)

I'm having trouble instantiating an instance of the Multinomial class because I can't discern from the documentation how I'm supposed to supply the parameters.

I'd imagine it's something like

import breeze.stats.distributions._

var x = new Multinomial(0.2,0.5,0.3)
x.draw()

But when I try to supply the arguments in this way, I get the following error:

scala> var x = new Multinomial(0.2,0.5,0.3)
<console>:10: error: No implicit view available from (Double, Double, Double) => breeze.linalg.QuasiTensor[I,Double].

The documentation for the Multinomial class say that the parameters of the distribution should be passed to the constructor as a type T, but I can't find much information about that type.

Does anybody know how to instantiate a Multinomial in breeze?


Solution

  • You have to wrap it in a DenseVector.

    scala> import breeze.linalg._
    import breeze.linalg._
    
    scala> val mult = Multinomial(DenseVector(0.2,0.5,0.3))
    mult: breeze.stats.distributions.Multinomial[breeze.linalg.DenseVector[Double],Int] = Multinomial{(0,0.2),(1,0.5),(2,0.3)}
    
    scala> mult.sample(100)
    res1: IndexedSeq[Int] = Vector(0, 1, 1, 2, 1, 1, 1, 1, 0, 2, 0, 0, 0, 2, 2, 1, 2, 2, 0, 1, 2, 1, 0, 1, 1, 2, 1, 1, 1, 2, 2, 2, 0, 0, 2, 1, 1, 1, 0, 1, 1, 2, 0, 0, 1, 1, 1, 1, 1, 1, 2, 0, 2, 2, 0, 2, 0, 1, 0, 1, 2, 1, 1, 1, 2, 2, 2, 2, 2, 0, 1, 1, 1, 2, 0, 2, 1, 0, 1, 1, 1, 0, 0, 0, 2, 1, 2, 0, 0, 1, 2, 2, 0, 2, 1, 1, 0, 1, 2, 2)
    

    I should add support for the way you're trying to use it.