创建概率为 python 的二进制随机矩阵
create binary random matrix with probability in python
我是 python 的新手。我想编写一个函数,它生成一个随机 nxm
二进制矩阵,每个矩阵的概率 p.
的值为 0
我做了什么
def randbin(M,N,P): # function to generate random binary matrix
mat = (np.random.rand(M,N)>=P).astype(int)
return mat
y = randbin(5,4,0.3)
每次我打印输出,我都没有按照估计的概率得到结果。我不知道我做错了什么。
我看不出你的方法有问题...生成概率 P 为 0 的 0 和 1 的随机矩阵的更好方法是使用 random.choice
:
def randbin(M,N,P):
return np.random.choice([0, 1], size=(M,N), p=[P, 1-P])
为了更好地理解,请查看 random.choice
文档。
我是 python 的新手。我想编写一个函数,它生成一个随机 nxm
二进制矩阵,每个矩阵的概率 p.
我做了什么
def randbin(M,N,P): # function to generate random binary matrix
mat = (np.random.rand(M,N)>=P).astype(int)
return mat
y = randbin(5,4,0.3)
每次我打印输出,我都没有按照估计的概率得到结果。我不知道我做错了什么。
我看不出你的方法有问题...生成概率 P 为 0 的 0 和 1 的随机矩阵的更好方法是使用 random.choice
:
def randbin(M,N,P):
return np.random.choice([0, 1], size=(M,N), p=[P, 1-P])
为了更好地理解,请查看 random.choice
文档。