gpt4 book ai didi

python - 生成具有特定比例的 0 和 1 的随机数组

转载 作者:太空狗 更新时间:2023-10-29 17:39:40 25 4
gpt4 key购买 nike

我想生成一个大小为 N 的随机数组,它只包含 0 和 1,我希望我的数组具有 0 和 1 之间的某个比率。例如,数组的 90% 为 1,其余 10% 为 0 (我希望这 90% 与整个数组一起是随机的)。

现在我有:

randomLabel = np.random.randint(2, size=numbers)

但我无法控制 0 和 1 之间的比例。

最佳答案

如果您想要精确的 1:9 比例:

nums = numpy.ones(1000)
nums[:100] = 0
numpy.random.shuffle(nums)

如果您想要独立的 10% 概率:

nums = numpy.random.choice([0, 1], size=1000, p=[.1, .9])

nums = (numpy.random.rand(1000) > 0.1).astype(int)

关于python - 生成具有特定比例的 0 和 1 的随机数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21566744/

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