使用SciPy或NumPy生成具有指定权重的离散随机变量 [英] Generating Discrete random variables with specified weights using SciPy or NumPy

查看:98
本文介绍了使用SciPy或NumPy生成具有指定权重的离散随机变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个简单的函数,该函数可以根据相应的(也指定的)概率生成指定的随机值数组.我只需要它来生成浮点值,但我不明白为什么它不应该能够生成任何标量.我可以想到许多通过现有函数构建此函数的方法,但是我想我可能只是错过了明显的SciPy或NumPy函数.

I am looking for a simple function that can generate an array of specified random values based on their corresponding (also specified) probabilities. I only need it to generate float values, but I don't see why it shouldn't be able to generate any scalar. I can think of many ways of building this from existing functions, but I think I probably just missed an obvious SciPy or NumPy function.

例如:

>>> values = [1.1, 2.2, 3.3]
>>> probabilities = [0.2, 0.5, 0.3]
>>> print some_function(values, probabilities, size=10)
(2.2, 1.1, 3.3, 3.3, 2.2, 2.2, 1.1, 2.2, 3.3, 2.2)

注意:我发现 scipy. stats.rv_discrete ,但我不知道它是如何工作的.具体来说,我不明白这(下面)的含义,也不知道它应该做什么:

Note: I found scipy.stats.rv_discrete but I don't understand how it works. Specifically, I do not understand what this (below) means nor what it should do:

numargs = generic.numargs
[ <shape(s)> ] = ['Replace with resonable value', ]*numargs

如果我应该使用rv_discrete,能否请您提供一个简单的示例并解释上述"shape"语句?

If rv_discrete is what I should be using, could you please provide me with a simple example and an explanation of the above "shape" statement?

推荐答案

从离散分布绘制的图形直接内置在numpy中. 该函数称为 random.choice (很难在numpy文档中查找没有任何离散分布的引用).

Drawing from a discrete distribution is directly built into numpy. The function is called random.choice (difficult to find without any reference to discrete distributions in the numpy docs).

elements = [1.1, 2.2, 3.3]
probabilities = [0.2, 0.5, 0.3]
np.random.choice(elements, 10, p=probabilities)

这篇关于使用SciPy或NumPy生成具有指定权重的离散随机变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆