Is there any way to use pvals as an numpy array in numpy.random.multinomial?

Question:

I try to generate the data that follow multinomial distribution by using numpy.random.multinomial but because of my probability values is an numpy array. I keep getting a message says "Object too deep for desired array"

Here is my code:

x1=np.random.normal(loc=0,scale=0.5,size=100)
beta1=2
beta2=0.5
d=1+np.exp(beta1*x1)+np.exp(beta2*x1)
p1=1/d
p2=np.exp(beta1*x1)/d
p3=np.exp(beta2*x1)/d

y=np.random.multinomial(1,np.stack((p1,p2,p3),axis=1),100)
Asked By: Pandora

||

Answers:

Due to some issues in the application of log to random floating point numbers, the stream may change when sampling from multinomial or another functions if 0 is generated in the underlying MT19937 random stream. There is a 10^53 in chance of this occurring. If a 0 is encountered in the underlying generator, then the incorrect value produced (either numpy.inf or numpy.nan) is now dropped.

recent versions of numpy use a instance random.Generator to invoke multinomial method

import numpy as np
x1=np.random.normal(loc=0,scale=0.5,size=100)
beta1=2
beta2=0.5
d=1+np.exp(beta1*x1)+np.exp(beta2*x1)
p1=1/d
p2=np.exp(beta1*x1)/d
p3=np.exp(beta2*x1)/d
y = np.random.default_rng()
y.multinomial(1, np.stack((p1,p2,p3),axis=1), size=100)

output:

array([[0, 0, 1],
       ...
       [0, 1, 0],
       [0, 1, 0],
       [0, 0, 1],
       [0, 1, 0],
       [0, 0, 1],
       [0, 1, 0],
       [1, 0, 0],
       [0, 1, 0],
       [0, 0, 1],
       [0, 1, 0]], dtype=int64)
Answered By: user11717481
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.