创建具有某些约束的2D Numpy数组

发布于 2025-02-04 02:25:56 字数 639 浏览 2 评论 0原文

我想创建一个大小n,n的2维数数组 m (Square Matrix m是),以及以下约束:

  1. 每行的总和等于
  2. 一个元素均在0到1之间。
  3. 每行元素的 。

例如,对于正方形矩阵 m = np.Array([[[[0.88,0.12],[0.13,0.87]]))

  1. (奖励)我希望每行的条目都遵循一些高斯类似的分布,这些发行版的峰值,对于行<代码> i ,位于元素m [i,i]

因此,线程提出了类似的问题。但是,在那里进行回答,我无法找到一种方法。这是一个搜索问题,我确实知道它可能被称为优化问题。但是,我想知道这些约束是否可以满足而无需一些专门的求解器。

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:

  1. The sum of each row equals to one
  2. The elements of each row are all between 0 and 1
  3. The value of row i that dominates is located at entry 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]])

  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].

In this SO thread a similar question is asked. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我很坚强 2025-02-11 02:25:56

1)和2):

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

For 1) and 2):

M = np.random.rand(n,n)
x = M / M.sum(1, keepdims=True)
倚栏听风 2025-02-11 02:25:56

我从每个坐标的行数中减去列数,然后使用它们来计算高斯函数的值,最后将其乘以随机数组并归一化。

它可能不是那么随机,但是很有可能满足您的要求:

>>> 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]])

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]])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文