簡體   English   中英

在Python中以概率創建二進制隨機矩陣

[英]create binary random matrix with probability in python

我是python的新手。 我想編寫一個函數,為概率p生成一個隨機nxm二進制矩陣,每個值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為0s的0s和1s隨機矩陣的更好方法是使用random.choice

def randbin(M,N,P):  
    return np.random.choice([0, 1], size=(M,N), p=[P, 1-P])

為了更好地理解,請查看random.choice文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM