numpy学习笔记之随机采样函数

本文详细介绍了numpy库中的随机采样函数np.random.choice的使用方法,包括从指定数组或整数范围内生成随机样本,以及如何设定概率分布进行加权随机采样。同时,对比了random模块的sample函数,并解释了np.random.choice的参数含义及其与其他随机函数如randint、shuffle、permutation的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

numpy的随机采样函数
  • np.random.choice(a, size=None,replace=None, p=None)

    • 功能:Generates a random sample from a given 1-D array

    • 常见的随机采样用法如下:

      import random 
      # 从0到99的列表中随机生成10个样本
      out1 = random.sample(range(100),10) # 方法1
      
      # If a is an int, the random sample is generated as if a was np.arange(n)
      out2 = np.random.choice(100,10) # 方法2 
      # 结果可能会出现相同的数,通过set()进行去重,
      out = set(out2)
      
      # 从input数组或者列表中随机生成一个样本
      input = [1,3,6,8]
      output = np.random.choice(input)
      
      # 从input数组或列表中以一定的概率生成样本
      # 选择元素8的概率最大为0.4
      input = [1,3,6,8]
      output = np.random.choice(input,p=[0.1,0.2,0.3,0.4])
      
      aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
      np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
       #array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], dtype='|S11')
      
    • np.random.choiceAPI 如下:

      choice(a, size=None, replace=True, p=None)
          Parameters
          -----------
          a : 1-D array-like or int
              If an ndarray, a random sample is generated from its elements.
              If an int, the random sample is generated as if a was np.arange(n)
          size : int or tuple of ints, optional
              Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
              ``m * n * k`` samples are drawn.  Default is None, in which case a
              single value is returned.
          replace : boolean, optional
              Whether the sample is with or without replacement
          p : 1-D array-like, optional
              The probabilities associated with each entry in a.
              If not given the sample assumes a uniform distribution over all
              entries in a.
      
          Returns
        	  samples : 1-D ndarray, shape (size,)
        	      The generated random samples
      

    See Also

    randint, shuffle, permutation

    • np.random.randint(0,10)

      • 功能:随机从0到10之间选取一个数

      • randint(low, high=None, size=None, dtype='l')

      • Return random integers from low (inclusive) to high (exclusive)

    • np.random.shuffle (array)

      • 功能:随机对给定数组或者列表乱序,默认是axis=0
      • 返回的结果就是给定数组本身,只不过顺序被打乱
    • np.random.permutation(array)

      • 功能:重新对给定数组或者列表排序,如何是多维数组,则沿着first axis重新排列,
      • 返回的重新排列后的数组
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值