NumPy基础:随机数生成

import numpy as np

# 确定随机数生成器的种子
# seed()用于指定随机数生成时所用算法开始的整数值,如果使用相同的seed值,则每次生成的随即数都相同
np.random.seed(3)
print(np.random.rand(4)) # [0.5507979  0.70814782 0.29090474 0.51082761]
print(np.random.rand(4)) # 没有使用seed 随机数不同 [0.89294695 0.89629309 0.12558531 0.20724288]
np.random.seed(3)
print(np.random.rand(4)) # 使用相同的seed 随机数相同 [0.5507979  0.70814782 0.29090474 0.51082761]

# 返回一个序列的随机排列,原序列不变
arr1 = np.array([1,2,3,4,5])
print(np.random.permutation(arr1)) # [2 3 4 1 5]
print(arr1) #[1 2 3 4 5]

# 对一个序列就地随机排列,原序列变化
arr2 = np.array([1,2,3,4,5])
np.random.shuffle(arr2)
print(arr2) #[1 5 3 4 2]

# 产生均匀分布的样本值
print(np.random.rand(2,3))
'''
[[0.23418466 0.23814386 0.46806856]
 [0.11568982 0.650459   0.2993208 ]]
'''

# 从给定的上下限范围内随机选取整数
print(np.random.randint(low=1,high=100,size=(2,3)))
'''
[[ 8 64 27]
 [24 94 60]]
'''
# 产生生态分布(平均值为0,标准差为1)的样本值
print(np.random.randn(2,3))
'''
[[ 0.18292511 -0.48627444  0.41030827]
 [ 0.51549312  0.26381845  1.89847068]]
'''
# 产生二项分布的样本值
print(np.random.binomial(n=100,p=0.5,size=(2,3)))
'''
[[48 46 50]
 [52 49 44]]
'''

# 产生正态(高斯)分布的样本值
# 参数loc(float):正态分布的均值,对应着这个分布的中心。loc=0说明这一个以Y轴为对称轴的正态分布
# 参数scale(float):正态分布的标准差,对应分布的宽度,scale越大,正态分布的曲线越矮胖,scale越小,曲线越高瘦。
# 参数size(int 或者整数元组):输出的值赋在shape里,默认为None
print(np.random.normal(loc=0,scale=0.5,size=(2,3)))
'''
[[ 1.12148353  0.82205912 -0.22225523]
 [ 0.64261443 -0.30223166 -0.69175258]]
'''

# 产生beta分布的样本值
print(np.random.beta(a=1,b=1,size=(2,3)))
'''
[[0.5114256  0.57097198 0.78919234]
 [0.64527071 0.27655094 0.44112513]]
'''

# 产生卡方分布的样本值
# df设定自由度,size设定生成数据的形状
print(np.random.chisquare(df=7,size=(2,3)))
'''
[[2.56477918 8.54322715 4.38206938]
 [6.23697907 4.32467322 1.81769223]]
'''

# 产生Gamma分布的样本值
# shape设定分布的形状参数,scale设定分布的尺度参数,size设定生成数据的形状
print(np.random.gamma(shape=1,scale=1,size=(2,3)))
'''
[[0.49257743 2.59203526 1.8430738 ]
 [0.44222905 0.04457012 0.36350978]]
'''

# 产生在[low,high)中均匀分布的样本值
# low默认0,high默认1
print(np.random.uniform(low=1,high=10,size=(2,3)))
'''
[[4.58367114 7.34462947 9.95822634]
 [4.20323379 7.86293032 6.33859225]]
'''

猜你喜欢

转载自www.cnblogs.com/nicole-zhang/p/12931201.html