[英]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
),具有以下约束:
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]])
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.