简体   繁体   English

使用 Numpy 生成 N 维矩阵

[英]Generate an N-dimensional matrix using Numpy

For a certain assignment, I have to create a multivariate discrete probability mass function over N random variables.对于某个任务,我必须在N随机变量上创建一个多元离散概率质量函数。 I want to do this by creating an array A filled with random numbers where each element denotes the joint probability over the random variables.我想通过创建一个填充随机数的数组A来做到这一点,其中每个元素表示随机变量的联合概率。 In case of 2 random variables, having i and j possible values respectively, this can be done by creating an (i*j) Numpy array filled with random numbers where the total sum = 1.在 2 个随机变量的情况下,分别具有ij可能值,这可以通过创建一个(i*j) Numpy 数组来完成,其中填充随机数,其中总和 = 1。

It becomes more difficult however, when an additional random variable with k possible values is introduced.然而,当引入具有k可能值的附加随机变量时,它变得更加困难。 In this case, I need to have an i*j*k Numpy array, again filled with random numbers where the total sum equals 1.在这种情况下,我需要一个i*j*k Numpy 数组,再次填充总和等于 1 的随机数。

Say I am given the structure (number of possible values for each random variable) as a list [n1,n2,...,nN] , how can I from here create such an N dimensional Numpy array?假设我得到了结构(每个随机变量的可能值的数量)作为列表[n1,n2,...,nN] ,我如何从这里创建这样一个N维 Numpy 数组?

If l is your list of dimensions, you could let如果l是你的维度列表,你可以让

a = np.random.random(size=l)
a = a/a.sum()

I found the following solution:我找到了以下解决方案:

def randomArray(structure):
    rand_array = np.random.randint(0, 100, size=(structure))
    my_sum = np.sum(rand_array)
    return rand_array/my_sum

where structure is a list as defined in the question above.其中structure是上面问题中定义的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM