np中的随机函数

 

numpy.random.uniform介绍:

1. 函数原型:  numpy.random.uniform(low,high,size)  ==》也即其他函数是对该函数的进一步封装

功能:从一个均匀分布[low,high)中随机采样,注意定义域是左闭右开,即包含low,不包含high.

参数介绍:
    
    low: 采样下界,float类型,默认值为0;
    high: 采样上界,float类型,默认值为1;
    size: 输出样本数目,为int或元组(tuple)类型,例如,size=(m,n,k), 则输出m*n*k个样本,缺省时输出1个值。

返回值:ndarray类型,其形状和参数size中描述一致。

这里顺便说下ndarray类型,表示一个N维数组对象,其有一个shape(表维度大小)和dtype(说明数组数据类型的对象),使用zeros和ones函数可以创建数据全0或全1的数组,原型:

    numpy.ones(shape,dtype=None,order='C'),
其中,shape表数组形状(m*n),dtype表类型,order表是以C还是fortran形式存放数据。

numpy.random.uniform(low=0.0, high=1.0, size=None)

2. 类似uniform,还有以下随机数产生函数:

    a. randint: 原型:numpy.random.randint(low, high=None, size=None, dtype='l'),产生随机整数;
    b. random_integers: 原型: numpy.random.random_integers(low, high=None, size=None),在闭区间上产生随机整数;
    c. random_sample: 原型: numpy.random.random_sample(size=None),在[0.0,1.0)上随机采样;
    d. random: 原型: numpy.random.random(size=None),和random_sample一样,是random_sample的别名;
    e. rand: 原型: numpy.random.rand(d0, d1, ..., dn),产生d0 - d1 - ... - dn形状的在[0,1)上均匀分布的float型数。
    f. randn: 原型:numpy.random.randn(d0,d1,...,dn),产生d0 - d1 - ... - dn形状的标准正态分布的float型数。

3. numpy.random.RandomState:

    “Container for the Mersenne Twister pseudo-random number generator.” 翻译过来为:

              它是一个容器,用来存储采用梅森旋转产生伪随机数的算法。

   输入参数:seed,可选项{None, int, array_like},没有给定的话,函数随机选一个起始点,
             这样深度学习的结果可能接近,但不完全相同,如果给定一个seed,则结果是deterministic,
             是确定的,但给定不给定seed对输出随机数并没有影响,只是相当于给定了一个初始点,后面
             的数也是基于这个seed而产生。

4.np.random.choice

RandomState.choice(a, size=None, replace=True, p=None)
  a : 1-D array-like or int    If an ndarray, a random sample is generated from its elements. 
      如果是ndarray数组,随机样本在该数组获取(取数据元素),    If an int, the random sample is generated as if a was np.arange(n)
      如果是整型数据随机样本生成类似np.arange(n)    
  size : int or tuple of ints, optional 
      大小:整型或整型元组中元素个数,可选
  replace : boolean, optional
      替换:布尔型,可选    Whether the sample is with or without replacement
      样本是否有重复值(False,没有;True,有;默认:True)
  见例子3
  p : 1-D array-like, optional
      1维数组,可选
      The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.
   和a里的每个输入联系,如果没有该参数,默认假设a里的每个输入等概率出现。(和a中元素一一对应,表示该元素出现的概率,概率大的,出现较多)

p=3
Z=np.zeros((5,5))
z=np.copy(Z)

choice=np.random.choice(range(5*5), p, replace=False)
print(choice)
np.put(Z,choice,1)
print(Z)

np.put(z,np.random.choice(range(3*3),p,replace=False),1)
Z
[12 24  8]
[[0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1.]]
Out[103]:
array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1.]])



原文地址:https://www.cnblogs.com/wqbin/p/10212427.html