微信扫一扫打赏支持

python机器学习库numpy---7.3、生成随机数-随机种子

python机器学习库numpy---7.3、生成随机数-随机种子

一、总结

一句话总结:

设置随机数种子主要是两个方法,一个是RandomState方法,一个是seed方法
随机种子方法

RandomState:定义种子类:RandomState是一个种子类,提供了各种种子方法,最常用seed
seed([seed]):定义全局种子:参数为整数或者矩阵

代码示例:

import numpy as np
rs = np.random.RandomState(1)  
data = rs.rand(30)
print(data)


import numpy as np
np.random.seed(1) #设置随机种子为1
print(np.random.rand(30))

 

 

 

二、7.3、生成随机数-随机种子

博客对应课程的视频位置:7.3、生成随机数-随机种子-范仁义-读书编程笔记
https://www.fanrenyi.com/video/38/349

 

7、生成随机数

(1)、均匀分布

a、服从[0, 1)之间的均匀分布:
numpy.random.rand(d0, d1, ..., dn)

b、[0, 1)之间均匀抽样:
numpy.random.random(size=None)
和rand函数功能一样,参数不同而已

c、在区间[low, high)中均匀分布:
numpy.random.uniform(low=0.0, high=1.0, size=None)

d、随机整数:在区间[low, high)中离散均匀抽样:
numpy.random.randint(low, high=None, size=None, dtype='l')


python中,random.random( )和random.rand( )功能完全一样,numpy为什么要留两个表示0-1均匀分布的函数?

历史原因,可能是为了使 Matlab 用户更容易学习 python+numpy 的组合。如果把其中一个函数去掉,所带来的麻烦远大于好处,因为有很多现存的代码分别使用了这两个函数。

(2)、正态分布

a、标准正态分布(均值为0,标准差为1):
numpy.random.randn(d0, d1, ..., dn)

b、服从μ=loc,σ=scale 的正态分布:
numpy.random.normal(loc=0.0, scale=1.0, size=None)


(3)、随机种子

RandomState:定义种子类:RandomState是一个种子类,提供了各种种子方法,最常用seed

seed([seed]):定义全局种子:参数为整数或者矩阵

代码示例:

np.random.seed(1234) #设置随机种子为1234

(1)、均匀分布

(a)、服从[0, 1)之间的均匀分布:numpy.random.rand(d0, d1, ..., dn)

作用:

产生一个给定形状的数组(其实应该是ndarray对象或者是一个单值),数组中的值服从[0, 1)之间的均匀分布。

参数:

d0, d, ..., dn : int,可选。如果没有参数则返回一个float型的随机数,该随机数服从[0, 1)之间的均匀分布。

返回值:

ndarray对象或者一个float型的值
In [2]:
import numpy as np
print(np.random.rand())
0.5453255015277448
In [3]:
print(np.random.rand(3))
[0.90757678 0.03145185 0.95313326]
In [4]:
print(np.random.rand(3,4))
[[0.97597192 0.28732266 0.17960605 0.85840045]
 [0.8457097  0.11786519 0.59764586 0.5142609 ]
 [0.68330079 0.44224353 0.36096329 0.32893185]]
In [5]:
import matplotlib.pyplot as plt  # 导入matplotlib模块,用于图表辅助分析
%matplotlib inline

# 解决中文乱码
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["font.family"]="sans-serif"
# 解决负号无法显示的问题
plt.rcParams['axes.unicode_minus'] =False

data_x = np.random.rand(1000)
data_y = np.random.rand(1000)
plt.scatter(data_x,data_y)
Out[5]:
<matplotlib.collections.PathCollection at 0x21cf86ec448>
(b)、[0, 1)之间均匀抽样:numpy.random.random(size=None)

作用:

返回从[0, 1)之间均匀抽样的数组,size指定形状。

参数:

size:

int型或int型的元组,如果不提供则返回一个服从该分布的随机数

返回值:

float型或者float型的ndarray对象
In [6]:
# 无参数
print(np.random.random())
0.25733366399724056
In [8]:
print(np.random.random(size=(3,)))
[0.87588153 0.41083416 0.92811127]
In [9]:
# 元组做参数
print(np.random.random((4,3)))
[[0.03027158 0.09068682 0.08516664]
 [0.88818931 0.7542361  0.97077598]
 [0.58459742 0.66082839 0.51209488]
 [0.52616617 0.99295998 0.9026425 ]]
In [10]:
import matplotlib.pyplot as plt  # 导入matplotlib模块,用于图表辅助分析
%matplotlib inline

# 解决中文乱码
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["font.family"]="sans-serif"
# 解决负号无法显示的问题
plt.rcParams['axes.unicode_minus'] =False

data_x = np.random.random((1000,))
data_y = np.random.random((1000,))
plt.scatter(data_x,data_y)
Out[10]:
<matplotlib.collections.PathCollection at 0x21cf877de88>
(c)、在区间[low, high)中均匀分布:numpy.random.uniform(low=0.0, high=1.0, size=None)

作用:

返回一个在区间[low, high)中均匀分布的数组,size指定形状。

参数:

low, high:float型或者float型的类数组对象。指定抽样区间为[low, high),low的默认值为0.0,hign的默认值为1.0

size:

int型或int型元组。指定形状,如果不提供size,则返回一个服从该分布的随机数。
In [11]:
print(np.random.uniform())
0.8464163023853011
In [12]:
print(np.random.uniform(10,100,(4,5)))
[[86.86036611 82.50530283 51.3847694  14.54433224 85.78924098]
 [88.45675899 80.67287362 88.57930721 79.2433418  95.33601246]
 [97.38877669 97.10142936 75.48331286 47.14349932 50.931656  ]
 [57.54116023 34.31330871 39.62217741 79.27942515 34.2372894 ]]
In [13]:
import matplotlib.pyplot as plt  # 导入matplotlib模块,用于图表辅助分析
%matplotlib inline

# 解决中文乱码
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["font.family"]="sans-serif"
# 解决负号无法显示的问题
plt.rcParams['axes.unicode_minus'] =False

data_x = np.random.uniform(10,100,(1000,))
data_y = np.random.uniform(10,100,(1000,))
plt.scatter(data_x,data_y)
Out[13]:
<matplotlib.collections.PathCollection at 0x21cf8812ac8>
(d)、随机整数:在区间[low, high)中离散均匀抽样:numpy.random.randint(low, high=None, size=None, dtype='l')

作用:

返回一个在区间[low, high)中离散均匀抽样的数组,size指定形状,dtype指定数据类型。

参数:

low, high:int型,指定抽样区间[low, high)
size:int型或int型的元组,指定形状
dypte:可选参数,指定数据类型,比如int,int64等,默认是np.int

返回值:

如果指定了size,则返回一个int型的ndarray对象,否则返回一个服从该分布的int型随机数。
In [16]:
print(np.random.randint(10))
7
In [ ]:
# 只有一个参数的时候表示最大值
print(np.random.randint(10))
In [17]:
help(np.random.randint)
Help on built-in function randint:

randint(...) method of numpy.random.mtrand.RandomState instance
    randint(low, high=None, size=None, dtype='l')
    
    Return random integers from `low` (inclusive) to `high` (exclusive).
    
    Return random integers from the "discrete uniform" distribution of
    the specified dtype in the "half-open" interval [`low`, `high`). If
    `high` is None (the default), then results are from [0, `low`).
    
    .. note::
        New code should use the ``integers`` method of a ``default_rng()``
        instance instead; see `random-quick-start`.
    
    Parameters
    ----------
    low : int or array-like of ints
        Lowest (signed) integers to be drawn from the distribution (unless
        ``high=None``, in which case this parameter is one above the
        *highest* such integer).
    high : int or array-like of ints, optional
        If provided, one above the largest (signed) integer to be drawn
        from the distribution (see above for behavior if ``high=None``).
        If array-like, must contain integer values
    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.
    dtype : dtype, optional
        Desired dtype of the result. All dtypes are determined by their
        name, i.e., 'int64', 'int', etc, so byteorder is not available
        and a specific precision may have different C types depending
        on the platform. The default value is `np.int_`.
    
        .. versionadded:: 1.11.0
    
    Returns
    -------
    out : int or ndarray of ints
        `size`-shaped array of random integers from the appropriate
        distribution, or a single such random int if `size` not provided.
    
    See Also
    --------
    random_integers : similar to `randint`, only for the closed
        interval [`low`, `high`], and 1 is the lowest value if `high` is
        omitted.
    Generator.integers: which should be used for new code.
    
    Examples
    --------
    >>> np.random.randint(2, size=10)
    array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) # random
    >>> np.random.randint(1, size=10)
    array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    
    Generate a 2 x 4 array of ints between 0 and 4, inclusive:
    
    >>> np.random.randint(5, size=(2, 4))
    array([[4, 0, 2, 1], # random
           [3, 2, 2, 0]])
    
    Generate a 1 x 3 array with 3 different upper bounds
    
    >>> np.random.randint(1, [3, 5, 10])
    array([2, 2, 9]) # random
    
    Generate a 1 by 3 array with 3 different lower bounds
    
    >>> np.random.randint([1, 5, 7], 10)
    array([9, 8, 7]) # random
    
    Generate a 2 by 4 array using broadcasting with dtype of uint8
    
    >>> np.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
    array([[ 8,  6,  9,  7], # random
           [ 1, 16,  9, 12]], dtype=uint8)

In [20]:
print(np.random.randint(low=10,size=(3,4),high=100))
[[60 19 81 87]
 [49 67 85 46]
 [69 25 92 44]]
In [21]:
import matplotlib.pyplot as plt  # 导入matplotlib模块,用于图表辅助分析
%matplotlib inline

# 解决中文乱码
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["font.family"]="sans-serif"
# 解决负号无法显示的问题
plt.rcParams['axes.unicode_minus'] =False

data_x = np.random.randint(10,100,(1000,))
data_y = np.random.randint(10,100,(1000,))
plt.scatter(data_x,data_y)
Out[21]:
<matplotlib.collections.PathCollection at 0x21cf8922348>

(2)、正态分布

(a)、标准正态分布(均值为0,标准差为1):numpy.random.randn(d0, d1, ..., dn)

作用:

返回一个指定形状的数组,数组中的值服从标准正态分布(均值为0,标准差为1)。

参数:

d0, d, ..., dn : int,可选。如果没有参数,则返回一个服从标准正态分布的float型随机数。

返回值:

ndarray对象或者float
In [5]:
# 无参数
import numpy as np
print(np.random.randn())
0.13376456884878418
In [6]:
print(np.random.randn(3))
[ 0.00692413  1.7347139  -0.98832561]
In [7]:
# 3行4列 的正态分布
print(np.random.randn(3,4))
# 正态分布,所以我们可以看到结果有正有负
[[ 0.46288376 -0.9402719  -1.3791829   0.12095743]
 [ 1.47022746 -0.77955805 -0.38801507  0.52498791]
 [ 0.12182416  1.74959633  1.20357299 -1.10387593]]
In [8]:
import matplotlib.pyplot as plt  # 导入matplotlib模块,用于图表辅助分析
%matplotlib inline

# 解决中文乱码
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["font.family"]="sans-serif"
# 解决负号无法显示的问题
plt.rcParams['axes.unicode_minus'] =False

data_x = np.random.randn(1000)
data_y = np.random.randn(1000)
plt.scatter(data_x,data_y)
Out[8]:
<matplotlib.collections.PathCollection at 0x264250a59c8>
(b)、服从μ=loc,σ=scale 的正态分布:numpy.random.normal(loc=0.0, scale=1.0, size=None)

作用:

返回一个由size指定形状的数组,数组中的值服从 μ=loc,σ=scale 的正态分布。

参数:

loc : float型或者float型的类数组对象,指定均值 μ
scale : float型或者float型的类数组对象,指定标准差 σ
size : int型或者int型的元组,指定了数组的形状。如果不提供size,且loc和scale为标量(不是类数组对象),则返回一个服从该分布的随机数。

输出:

ndarray对象或者一个标量
In [9]:
# 无参数
print(np.random.normal())
1.3048521009886291
In [10]:
# 3行4列 的正态分布
print(np.random.normal(10,2,(3,4)))
[[ 6.64607268 14.28870815 11.04433027 12.77813207]
 [ 8.38923977 11.63867271 11.28538438 12.20541604]
 [10.08465579  8.88528815 12.41447794  7.58024792]]
In [11]:
import matplotlib.pyplot as plt  # 导入matplotlib模块,用于图表辅助分析
%matplotlib inline

# 解决中文乱码
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["font.family"]="sans-serif"
# 解决负号无法显示的问题
plt.rcParams['axes.unicode_minus'] =False

data_x = np.random.normal(10,2,(1000))
data_y = np.random.normal(10,2,(1000))
plt.scatter(data_x,data_y)
Out[11]:
<matplotlib.collections.PathCollection at 0x26425174688>

(3)、随机种子

计算机实现的随机数生成通常为伪随机数生成器,为了使得具备随机性的代码最终的结果可复现,需要设置相同的种子值


电脑产生随机数需要明白以下几点:

(1)随机数是由随机种子根据一定的计算方法计算出来的数值。所以,只要计算方法一定,随机种子一定,那么产生的随机数就不会变。 
(2)只要用户不设置随机种子,那么在默认情况下随机种子来自系统时钟(即定时/计数器的值) 
(3)随机数产生的算法与系统有关,Windows和Linux是不同的,也就是说,即便是随机种子一样,不同系统产生的随机数也不一样。 



随机种子方法

RandomState:定义种子类:RandomState是一个种子类,提供了各种种子方法,最常用seed

seed([seed]):定义全局种子:参数为整数或者矩阵

代码示例:

np.random.seed(1234) #设置随机种子为1234

In [3]:
#1为种子,种子不一样,生成的随机数也不一样,但是对每个种子来说,每次运行所生成的随机数是相同的
import numpy as np
rs = np.random.RandomState(1)  
data = rs.rand(30)
print(data)
[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01
 1.46755891e-01 9.23385948e-02 1.86260211e-01 3.45560727e-01
 3.96767474e-01 5.38816734e-01 4.19194514e-01 6.85219500e-01
 2.04452250e-01 8.78117436e-01 2.73875932e-02 6.70467510e-01
 4.17304802e-01 5.58689828e-01 1.40386939e-01 1.98101489e-01
 8.00744569e-01 9.68261576e-01 3.13424178e-01 6.92322616e-01
 8.76389152e-01 8.94606664e-01 8.50442114e-02 3.90547832e-02
 1.69830420e-01 8.78142503e-01]
In [3]:
# 如果没设置随机数
import numpy as np
print(np.random.rand(30))
[0.91197644 0.6504751  0.54849346 0.1408817  0.79662447 0.7657173
 0.88059378 0.28970806 0.04421655 0.8258623  0.77949267 0.21584071
 0.54239107 0.84065671 0.98545231 0.93971736 0.94389124 0.4268576
 0.24076141 0.79165343 0.35609388 0.29818106 0.0966155  0.27966646
 0.11785404 0.485944   0.89728192 0.25347008 0.81296457 0.63926957]
In [4]:
import numpy as np
np.random.seed(1) #设置随机种子为1
print(np.random.rand(30))
[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01
 1.46755891e-01 9.23385948e-02 1.86260211e-01 3.45560727e-01
 3.96767474e-01 5.38816734e-01 4.19194514e-01 6.85219500e-01
 2.04452250e-01 8.78117436e-01 2.73875932e-02 6.70467510e-01
 4.17304802e-01 5.58689828e-01 1.40386939e-01 1.98101489e-01
 8.00744569e-01 9.68261576e-01 3.13424178e-01 6.92322616e-01
 8.76389152e-01 8.94606664e-01 8.50442114e-02 3.90547832e-02
 1.69830420e-01 8.78142503e-01]
In [ ]:
 

 

 
posted @ 2020-08-28 07:15  范仁义  阅读(4157)  评论(0编辑  收藏  举报