浅析Python中的随机采样和概率分布

作者:Orion's 时间:2023-12-11 14:51:11 

 Python(包括其包Numpy)中包含了了许多概率算法,包括基础的随机采样以及许多经典的概率分布生成。我们这个系列介绍几个在机器学习中常用的概率函数。先来看最基础的功能——随机采样。

1. random.choice

如果我们只需要从序列里采一个样本(所有样本等概率被采),只需要使用random.choice即可:


import random
res1 = random.choice([0, 1, 2, 3, 4])
print(res1) # 3

2. random.choices(有放回)

当然,很多时候我们不只需要采一个数,而且我们需要设定序列中每一项被采的概率不同。此时我们可以采用random.random.choices函数, 该函数用于有放回的(即一个数据项可以被重复采多次)对一个序列进行采样。其函数原型如下:


random.choices(population, weights=None, *, cum_weights=None, k=1)

population: 欲采样的序列

weights: 每个样本被赋予的权重(又称相对权重),决定每个样本被采的概率,如[10, 0, 30, 60, 0]

cum_weights: 累积权重,相对权重[10, 0, 30, 60, 0]相当于累积权重[10, 10, 40, 100, 100]

我们从[0, 1, 2, 3, 4]中按照相对权重采样3个样本如下:


res2 = random.choices([0, 1, 2, 3, 4], weights=[10, 0, 30, 60, 0], k=3)
# 注意population不是关键字参数,在函数调用时不能写成population=[0,1,2,3,4]来传参
# 关于关键字参数和位置参数,可以参看我的博客《Python技法2:函数参数的进阶用法》https://www.cnblogs.com/orion-orion/p/15647408.html
print(res2) # [3, 3, 2]

从[0, 1, 2, 3, 4]中按照累积权重采样3和样本如下:


res3 = random.choices([0, 1, 2, 3, 4], cum_weights=[10, 10, 40, 100, 100], k=3)
print(res3) # [0, 3, 3]

注意,相对权重weights和累计权重cum_weights不能同时传入,否则会报TypeError异常'Cannot specify both weights and cumulative weights'

3. numpy.sample(无放回)

random.sample是无放回,如果我们需要无放回采样(即每一项只能采一次),那我们需要使用random.sample。需要注意的是,如果使用该函数,将无法定义样本权重。该函数原型如下:


random.sample(population, k, *, counts=None)¶

population: 欲采样的序列

k: 采样元素个数

counts: 用于population是可重复集合的情况,定义集合元素的重复次数。sample(['red', 'blue'], counts=[4, 2], k=5)等价于sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)

我们无放回地对序列[0, 1, 2, 3, 4]采样3次如下:


res3 = random.sample([0, 1, 2, 3, 4], k=3)
print(res3) # [3, 2, 1]

无放回地对可重复集合[0, 1, 1, 2, 2, 3, 3, 4]采样3次如下:


res4 = random.sample([0, 1, 2, 3, 4], k=3, counts=[1, 2, 2, 2, 1])
print(res4) # [3, 2, 2]

如果counts长度和population序列长度不一致,会抛出异常ValueError:"The number of counts does not match the population"

4.rng.choices 和 rng.sample

还有一种有放回采样实现方法是我在论文[1]的代码[2]中学习到的。即先定义一个随机数生成器,再调用随机数生成器的choices方法或sample方法,其使用方法和random.choice/random.sample函数相同。


rng_seed = 1234
rng = random.Random(rng_seed)
res5 = rng.choices(
    population=[0,1,2,3,4],
    weights=[0.1, 0, 0.3, 0.6, 0],
    k=3,
)
print(res5) # [3, 3, 0]

res6 = rng.sample(
    population=[0, 1, 2, 3, 4],
    k=3,
)
print(res6) # [4, 0, 2]

这两个函数在论文[1]的实现代码[2]中用来随机选择任务节点client:


def sample_clients(self):
       """
       sample a list of clients without repetition

"""
       rng_seed = (seed if (seed is not None and seed >= 0) else int(time.time()))
       self.rng = random.Random(rng_seed)

if self.sample_with_replacement:
           self.sampled_clients = \
               self.rng.choices(
                   population=self.clients,
                   weights=self.clients_weights,
                   k=self.n_clients_per_round,
               )
       else:
           self.sampled_clients = self.rng.sample(self.clients, k=self.n_clients_per_round)

5. numpy.random.choices

从序列中按照权重分布采样也可以采用numpy.random.choice实现。其函数原型如下:


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

a: 1-D array-like or int   如果是1-D array-like,那么样本会从其元素中抽取。如果是int,那么样本会从np.arange(a)中抽取;

size: int or tuple of ints, optional   为输出形状大小,如果给定形状为(m,n,k),那么m×n×k的样本会从中抽取。默认为None,即返回一个单一标量。

replace: boolean, optional   表示采样是又放回的还是无放回的。若replace=True,则为又放回采样(一个值可以被采多次),否则是无放回的(一个值只能被采一次)。

p: 1-D array-like, optional   表示a中每一项被采的概率。如果没有给定,则我们假定a中各项被采的概率服从均匀分布(即每一项被采的概率相同)。

从[0,1,2,3,4,5]中重复/不重复采样3次如下:


import numpy as np
res1 = np.random.choice(5, 3, replace=True)
print(res1) # [1 1 4]

res2 = np.random.choice(5, 3, replace=False)
print(res2) # [2 1 4]

同样是[0,1,2,3,4,5]中重复/不重复采样3次,现在来看我们为每个样本设定不同概率的情况:


res3 = np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
print(res3)  # [2 3 3]

res4 = np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
print(res4) # [3 2 0]

参考文献

https://github.com/omarfoq/FedEM

https://www.python.org/

https://numpy.org/

来源:https://www.cnblogs.com/orion-orion/p/15647408.html

标签:Python,随机采样,概率分布
0
投稿

猜你喜欢

  • 如何使用python写截屏小工具

    2021-04-04 23:51:14
  • mysql使用LOAD语句批量录入数据方法

    2010-03-09 16:31:00
  • 谈谈网页一屏有多大?

    2007-12-21 12:28:00
  • python基于tkinter点击按钮实现图片的切换

    2022-03-18 10:22:31
  • python虚拟环境的安装和配置(virtualenv,virtualenvwrapper)

    2021-05-13 17:40:35
  • MySQL字段类型说明

    2007-09-27 19:22:00
  • GO语言基础之数组

    2024-03-11 21:44:03
  • Python编程实现数学运算求一元二次方程的实根算法示例

    2023-08-08 05:38:40
  • python开发入门——set的使用

    2023-09-21 09:39:56
  • python通过加号运算符操作列表的方法

    2023-11-12 13:44:04
  • Python注释、分支结构、循环结构、伪“选择结构”用法实例分析

    2021-01-15 14:45:25
  • python实现三次密码验证的示例

    2022-01-24 16:34:25
  • 使用python进行拆分大文件的方法

    2022-06-23 17:54:04
  • Python time时间格式化和设置时区实现代码详解

    2023-05-17 00:09:17
  • sql查看所有表大小的方法

    2024-01-24 04:42:13
  • 在Python程序和Flask框架中使用SQLAlchemy的教程

    2021-10-28 06:14:21
  • php部分常见问题总结

    2023-07-02 17:10:41
  • 最小asp后门程序

    2011-04-03 10:35:00
  • Python写的贪吃蛇游戏例子

    2023-06-26 15:50:55
  • 一个奇怪的CSS现象

    2010-02-10 12:28:00
  • asp之家 网络编程 m.aspxhome.com