简体   繁体   English

创建具有某些约束的二维 numpy 数组

[英]Creating a 2d numpy array with certain constraints

I would like to create a 2 dimensional numpy array M of size n,n (a square matrix M that is) with the following constraints:我想创建一个大小为n,n的二维 numpy 数组M (即方阵M ),具有以下约束:

  1. The sum of each row equals to one每行之和等于一
  2. The elements of each row are all between 0 and 1每行的元素都在0到1之间
  3. The value of row i that dominates is located at entry M[i,i] .占主导地位的第i行的值位于条目M[i,i]处。

For example, for a square matrix it would be something like M = np.array([[0.88,0.12],[0.13,0.87]])例如,对于方阵,它类似于M = np.array([[0.88,0.12],[0.13,0.87]])

  1. (Bonus) Ideally I want the entries of each row to follow some Gaussian like distribution whose peak, for row i , is located at element M[i,i] . (奖励)理想情况下,我希望每行的条目遵循某种高斯分布,其峰值(对于第i行)位于元素M[i,i]处。

In this SO thread a similar question is asked.这个 SO 线程中,提出了一个类似的问题。 However, playing with the responses there I was not able to find a way to do it.但是,在那里玩响应时,我无法找到解决方法。 This is a search problem, and I do understand it might be formulated as an optimization problem.这是一个搜索问题,我确实理解它可能被表述为一个优化问题。 However, I am wondering if these constraints can satisfied without the need of some specialized solver.但是,我想知道是否可以在不需要一些专门的求解器的情况下满足这些约束。

For 1) and 2):对于 1) 和 2):

M = np.random.rand(n,n)
x = M / M.sum(1, keepdims=True)

I subtract the number of columns from the number of rows per coordinate, and then use them to calculate the value of the Gaussian function, and finally multiply it by a random array and normalize it.我从每个坐标的行数中减去列数,然后用它们计算高斯函数的值,最后乘以一个随机数组并归一化。

It may not be so random, but it has a high probability of meeting your requirements:它可能不是那么随机,但它很有可能满足您的要求:

>>> size = 4
>>> ii, jj = np.indices((size, size))
>>> gaussian = np.exp(-((ii - jj) ** 2) / 2)
>>> result = np.random.normal(1, .1, gaussian.shape) * gaussian
>>> result /= result.sum(1, keepdims=True)
>>> result
array([[0.47556382, 0.38041462, 0.11953135, 0.02449021],
       [0.24805318, 0.4126681 , 0.26168636, 0.07759236],
       [0.10350016, 0.26245839, 0.37168771, 0.26235374],
       [0.02027633, 0.11892695, 0.31971733, 0.54107939]])

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

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