GVKun编程网logo

Python-加权版本的random.choice(python加权随机)

26

在本文中,我们将给您介绍关于Python-加权版本的random.choice的详细内容,并且为您解答python加权随机的相关问题,此外,我们还将为您提供关于#小手一抬学Python#Python之

在本文中,我们将给您介绍关于Python-加权版本的random.choice的详细内容,并且为您解答python加权随机的相关问题,此外,我们还将为您提供关于#小手一抬学Python# Python 之内置 random 模块、C# 有什么等同于 Python 的 random.choices()、numpy.random.choice、numpy.random.rand()/randn()/randint()/normal()/choice()/RandomState()的知识。

本文目录一览:

Python-加权版本的random.choice(python加权随机)

Python-加权版本的random.choice(python加权随机)

我需要写一个加权版本的random.choice(列表中的每个元素都有不同的被选择概率)。这是我想出的:

def weightedChoice(choices):    """Like random.choice, but each element can have a different chance of    being selected.    choices can be any iterable containing iterables with two items each.    Technically, they can have more than two items, the rest will just be    ignored.  The first item is the thing being chosen, the second item is    its weight.  The weights can be any numeric values, what matters is the    relative differences between them.    """    space = {}    current = 0    for choice, weight in choices:        if weight > 0:            space[current] = choice            current += weight    rand = random.uniform(0, current)    for key in sorted(space.keys() + [current]):        if rand < key:            return choice        choice = space[key]    return None

对于我来说,此功能似乎过于复杂且难看。我希望这里的每个人都可以提出一些改进建议或替代方法。对于我来说,效率并不像代码的清洁度和可读性那么重要。

答案1

小编典典

从1.7.0版开始,NumPy具有choice支持概率分布的功能。

from numpy.random import choicedraw = choice(list_of_candidates, number_of_items_to_pick,              p=probability_distribution)

请注意,这probability_distribution是顺序相同的序列list_of_candidates。您还可以使用关键字replace=False来更改行为,以便不替换绘制的项目。

#小手一抬学Python# Python 之内置 random 模块

#小手一抬学Python# Python 之内置 random 模块

Python 内置模块之 random

random 库是 Python 中生成随机数的标准库,包含的函数清单如下:

  • 基本随机函数:seedrandomgetstatesetstate
  • 扩展随机函数:randintgetrandbitsrandrangechoiceshufflesample
  • 分布随机函数:uniformtriangularbetavariateexpovariategammavariategausslognormvariatenormalvariatevonmisesvariateparetovariateweibullvariate
    发现单词 variate 出现频率比较高,该但是是变量的意思。

基本随机函数

seed 与 random 函数

seed 函数初始化一个随机种子,默认是当前系统时间。
random 函数 生成一个 [0.0,1.0) 之间的随机小数 。

具体代码如下:

import random

random.seed(10)

x = random.random()
print(x)

其中需要说明的是 random.seed 函数, 通过 seed 函数 可以每次生成相同的随机数,例如下述代码:

import random

random.seed(10)
x = random.random()
print(x)

random.seed(10)
y = random.random()
print(y)

在不同的代码上获取到的值是不同的,但是 x 与 y 是相同的。

0.5714025946899135
0.5714025946899135

getstate() 和 setstate(state)

getstate 函数用来记录随机数生成器的状态,setstate 函数用来将生成器恢复到上次记录的状态。

# 记录生成器的状态
state_tuple = random.getstate()
for i in range(4):
    print(random.random())
print("*"*10)
# 传入参数后恢复之前状态
random.setstate(state_tuple)
for j in range(4):
    print(random.random())

输出的随机数两次一致。

0.10043296140791758
0.6183668665504062
0.6964328590693109
0.6702494141830372
**********
0.10043296140791758
0.6183668665504062
0.6964328590693109
0.6702494141830372

扩展随机函数

random 扩展随机函数有如下几个:

randint`、`getrandbits`、`randrange`、`choice`、`shuffle`、`sample

randint 和 randrange

randint 生成一个 [x,y] 区间之内的整数。
randrange 生成一个 [m,n) 区间之内以 k 为步长的随机整数。

测试代码如下:

x = random.randint(1,10)
print(x)

y = random.randrange(1,10,2)
print(y)

这两个函数比较简单,randint 函数原型如下:

random.randint(start,stop)

参数 start 表示最小值,参数 stop 表示最大值,两头都是闭区间,也就是 startstop 都能被获取到。

randrange 函数原型如下:

random.randrange(start,stop,step)

如果函数调用时只有一个参数,默认是从 0 到该参数值,该函数与 randint 区别在于,函数是左闭右开,最后一个参数是步长。

查阅效果,可以复制下述代码运行:

for i in range(3):
    print("*"*20)
    print(random.randrange(10))
    print(random.randrange(5,10))
    print(random.randrange(5,100,5))

getrandbits(k) 和 choice(seq)

getrandbits 生成一个 k 比特长的随机整数,实际输出的是 k 位二进制数转换成的十进制数。
choice 从序列中随机选择一个元素。

x =  random.getrandbits(5)
print(x)
# 生成的长度是 00000-11111

getrandbits(k) 函数可以简单描述如下:输出一个 $\[0,2^k-1\]$ 范围内一个随机整数,k 表示的是 2 进制的位数。

choice 就比较简单了,从列表中返回一个随机元素。

import random

my_list = ["a", "b", "c"]

print(random.choice(my_list))

shuffle(seq) 和 sample(pop,k)

shuffle 函数用于将序列中的元素随机排序,并且原序列被修改。
sample 函数用于从序列或者集合中随机选择 k 个选择,原序列不变。

my_list = [1,2,3,4,5,6,7,8,9]
random.shuffle(my_list)

print(my_list)

shuffle 函数只能用于可变序列,不可变序列(如元组)会出现错误。

my_list = ["梦想", "橡皮擦", 1, 2, [3, 4]]
print(my_list)
ls = random.sample(my_list, 4)
print(ls)

分布随机函数

该部分涉及的比较多,重点展示重要和常见的一些函数。

uniform(a,b) 、betavariate 和 triangular 函数

uniform 生成一个 [a,b] 之间的随机小数,采用等概率分布。
betavariate 生成一个 [0,1] 之间的随机小数,采用 beta 分布。
triangular 生成一个 [low,high] 之间的随机小数,采用三角分布。

在使用 uniform 时候需要注意,如果 a<b,那么生成一个 b-a 之间的小数。

for i in range(3):
    print(random.uniform(4, 1))

其它分布随机函数

以下都是生成随机数的方法,只是底层核心算法不同。
、、、、、、、。

  1. expovariate:生成一个 (0,∞) 之间的随机整数,指数分布;
  2. gammavariate:采用 gamma 分布;
  3. gauss:采用高斯(正太)分布;
  4. lognormvariate:对数正太分布;
  5. normalvariate:正太分布;
  6. vonmisesvariate:冯米赛斯分布;
  7. paretovariate:帕累托分布;
  8. weibullvariate:韦伯分布。

这篇博客的总结

本篇博客学习了 Python 中随机数相关的知识点,希望对你有所帮助。

C# 有什么等同于 Python 的 random.choices()

C# 有什么等同于 Python 的 random.choices()

C# 没有像这样内置任何东西,但是,添加扩展方法来重新创建相同的基本行为并不难:

static class RandomUtils
{
    public static string Choice(this Random rnd,IEnumerable<string> choices,IEnumerable<int> weights)
    {
        var cumulativeWeight = new List<int>();
        int last = 0;
        foreach (var cur in weights)
        {
            last += cur;
            cumulativeWeight.Add(last);
        }
        int choice = rnd.Next(last);
        int i = 0;
        foreach (var cur in choices)
        {
            if (choice < cumulativeWeight[i])
            {
                return cur;
            }
            i++;
        }
        return null;
    }
}

然后你可以用类似Python版本的方式调用它:

string[] choices = { "Attack","Heal","Amplify","Defense" };
int[] weights = { 70,15,15 };

Random rnd = new Random();
Console.WriteLine(rnd.Choice(choices,weights));
,

你可以得到random.next(0,100),然后用一个简单的开关盒什么的来选择相关的项目。您的域将是这样的,[0-70,70-85,85-100]。如果您需要完整代码,请告诉我。

    Random ran = new Random();
    int probability = ran.Next(0,100);
    string s;
    if (probability == 0)
        s = "Heal";
    else if (probability <= 70)
        s = "Attack";
    else if (probability <= 85)
        s = "Amplify";
    else if (probability <= 100)
        s = "Defense";

numpy.random.choice

numpy.random.choice

numpy.random.choice(a, size=None, replace=True, p=None)

从给定的一维数组或整数中生成随机样本

a              一维数组或整数   

size         生成样本的大小

replace    bool类型  False表示样本中不允许有重复值 True......

p              给定数组中元素出现的概率

 

例:           np.random.choice(5,3,p=[0,0,0,0,1])       

output:     array([4, 4, 4], dtype=int64)   

结果中生成了三个数,因为p中4的概率为1,所以生成的数都为4。

若改为 np.random.choice(5,3,p=[0,0,0,0,1],replace=False) 

则会报错,因为size为3,而且只能输出4,所以不允许重复的话无法输出结果

 

numpy.random.rand()/randn()/randint()/normal()/choice()/RandomState()

numpy.random.rand()/randn()/randint()/normal()/choice()/RandomState()

这玩意用了很多次,但每次用还是容易混淆,今天来总结mark一下~~~

1. numpy.random.rand(d0,d1,...,dn)

生成一个[0,1)之间的随机数或N维数组

np.random.rand(2) #生成两个[0,1)之间的数
[0.6555729  0.76240372]
np.random.rand(2,2) #生成2行*2列的矩阵
[[0.58360206 0.91619225]
 [0.78203671 0.06754087]]

2. numpy.random.randn(d0,d1,...,dn)

生成一个[0,1)之间的随机浮点数或N维浮点数组
正态分布

np.random.randn(2) #生成两个[0,1)之间的浮点数
[-0.03609815  0.25591596]
np.random.randn(2,2) #生成2行*2列的矩阵
[[-0.3021947  -0.37880516]
 [-1.84794341 -1.27301629]]

3. numpy.random.randint(low,high=None,size=None,dtype=''1'')

生成一个整数或N维整数数组 若high不为None时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数,且high必须大于low;dtype只能是int类型

np.random.randint(2)#1个0~2的整数
1
np.random.randint(1,2)#1个1~2的整数
1
np.random.randint(1,5,size=3) #3个1~5的整数
[3 1 2]

4.numpy.random.normal(low,high,size=(4,4))

生成一个标准正态分布的4*4样本值

numpy.random.normal(loc=0.0, scale=1, size=(2, 3))
array([[ 2.36637254, -0.28686707, -0.5227531 ],
       [ 0.35879566,  0.70202319, -0.84655717]])

5.numpy.random.shuffle() 

随机打乱序列 将序列的所有元素随机排序,传入参数可以是一个序列或者元组

[[-0.15040995 -0.43780718 -0.22292445]
 [-0.89388124 -0.39465164  0.24113838]]

6.numpy.random.choice() 

随机选取序列的一个元素 可以从序列(字符串、列表、元组等)中随机选取,返回一个列表,元组或字符串的随机项

np.random.choice([''a'',''b'',''c'',''d'',''e''])
c
np.random.choice(5, 6)#6个小于5的元素

[2 3 3 3 1 2]
np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])#p:每个条目出现的概率。如果没有,假设样本在A中的所有条目都具有均匀分布。

[0 3 2]

7.numpy.random.RandomState() 

指定种子值 numpy.random.RandomState()指定种子值(指定种子值是为了使同样的条件下每次产生的随机数一样,避免程序调试时由随机数不同而引起的问题) 如不设置种子值时,np.random.randint(8)可能产生0-7内的任意整数,且每次产生的数字可能是任意一种. 而设置种子值后,np.random.RandomState(0).randint(8)可能产生0-7内的任意整数,但种子值不变时每次运行程序产生的数字一样.

np.random.RandomState(0).randint(8)#产生随机整数
4
n1 = numpy.random.RandomState(0).random_sample()
n2 = numpy.random.RandomState(0).random_sample(size=(2,3))
0.548813503927 
[[ 0.5488135   0.71518937  0.60276338]
 [ 0.54488318  0.4236548   0.64589411]]

关于Python-加权版本的random.choicepython加权随机的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于#小手一抬学Python# Python 之内置 random 模块、C# 有什么等同于 Python 的 random.choices()、numpy.random.choice、numpy.random.rand()/randn()/randint()/normal()/choice()/RandomState()等相关知识的信息别忘了在本站进行查找喔。

本文标签: