Python

# NumPy Np.Random.Multinomial()

In this post, we will explore the random.multinomial() function in the NumPy package.

The multinomial() function generates an array of the multinomial distribution.

A multinomial distribution is a multivariate generalization of the binomial distribution in probability theory.

https://en.wikipedia.org/wiki/Multinomial_distribution

## NumPy np.random.multinomial() Function Syntax

sky

 1 random.multinomial(n, pvals, size=None)

## Function Parameters

The function parameters as discussed below:

1. n – defines the number of experiments.
2. pvals – sets the probabilities of each of the different p outcomes.
3. size – sets the output shape of the resulting array.

## Return Value

The function returns an array of multinomial distributions of the shape specified by the size parameter. If the size is not defined, the function will return a scalar value.

## Example #1

Consider the example code shown below:

 1234 # import numpy import numpy as np arr = np.random.multinomial(6, [1/2.]*2, 2) print(arr)

The code above generates an array of shapes (2,2) as defined by the size parameter.

NOTE: The total of the pvals MUST add to one.

The resulting value is as shown:

 12 [[2 4] [5 1]]

## Example #2

Another example is demonstrated in the code below:

 123 arr = np.random.multinomial(8, [0.02064637,0.04639968,0.07105934,0.19605029,0.00845342,0.2492401 ,0.1561038,0.02840649,0.09912076,0.12451974], 3) print(arr)

The code above should return an array as shown:

 123 [[0 0 0 1 0 2 2 0 1 2] [0 0 0 1 0 3 0 0 3 1] [0 1 1 2 0 2 1 0 1 0]]

## Closing

In this article, we demonstrated how to use the random.multinomial() function in NumPy to generate an array of a multinomial distribution.

Happy coding!!