gpt4 book ai didi

python - 生成条件随机矩阵

转载 作者:行者123 更新时间:2023-11-28 17:02:20 26 4
gpt4 key购买 nike

我们如何生成一个列和行之和为 1 的矩阵。

import numpy as np
import random
class city:

def __init__(self):
self.distance()

def distance(self):
self.A = np.array([[ 0, 10, 20, 30],[10, 0, 25, 20],[20, 25, 0, 15],[30, 20, 15, 0]])
self.B =(np.random.randint(0, self.A.shape[0], size=self.A.shape[0]) == np.arange(self.A.shape[0]).reshape(-1, 1)).astype(int)
return self.B

最佳答案

据我所知,你想要一个随机生成器 doubly stochastic matrices (帝斯曼)。

如果生成矩阵的分布不需要任何额外的属性,选择的算法似乎仍然是 Sinkhorn-Knopp .在这里,我们交替重新缩放行和列,使值符合求和标准:

def gen_doubly_stochastic(size, max_error=None):
if max_error is None:
max_error = 1024 * np.finfo(float).eps

m = np.matrix(np.random.random((size, size)))
error = float('Inf')
while error > max_error:
m = np.divide(m, m.sum(axis=0), order='C')
m = np.divide(m, m.sum(axis=1), order='K')

error = max(
np.max(np.abs(1 - m.sum(axis=0))),
np.max(np.abs(1 - m.sum(axis=1)))
)
return m

根据原始论文,迭代非常迅速地收敛到一个近似解。

或者,可以利用任何 n x n DSM 都可以表示为 n 随机置换矩阵的线性组合的属性(参见例如 Is there a better way to randomly generate a Doubly Stochastic Matrix ),线性系数之和为 1:

def gen_doubly_stochastic_permute(size):
m = np.zeros((size, size))
I = np.identity(size)

# n random coefficients
coeffs = np.random.random(size)
# enforce coefficient sum == 1
coeffs /= np.sum(coeffs)

# index array for identity permutation
values = np.array(range(0, size))
for c in coeffs:
# generate new random permutation in place
np.random.shuffle(values)
# add scaled permutation matrix
m += c * I[values, :]
return m

关于python - 生成条件随机矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53578621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com