玩转大数据大数据大数据,机器学习,人工智能

range()、np.arange()和np.random相关总

2018-12-04  本文已影响31人  他与理想国

range()和xrange()函数

range()和np.arange()函数

python random模块

random.random()
random.randint(a,b)
random.randrange([start], stop[, step])
random.uniform(a,b)
random.choice(sequence)
random.shuffle(x[, random])
random.sample(sequence, k)

numpy random模块

numpy.random.rand(d0,d1,…,dn)
np.random.rand(4,2)
array([[ 0.02173903,  0.44376568],
       [ 0.25309942,  0.85259262],
       [ 0.56465709,  0.95135013],
       [ 0.14145746,  0.55389458]])

np.random.rand(4,3,2) # shape: 4*3*2
array([[[ 0.08256277,  0.11408276],
        [ 0.11182496,  0.51452019],
        [ 0.09731856,  0.18279204]],
 
       [[ 0.74637005,  0.76065562],
        [ 0.32060311,  0.69410458],
        [ 0.28890543,  0.68532579]],
 
       [[ 0.72110169,  0.52517524],
        [ 0.32876607,  0.66632414],
        [ 0.45762399,  0.49176764]],
 
       [[ 0.73886671,  0.81877121],
        [ 0.03984658,  0.99454548],
        [ 0.18205926,  0.99637823]]])
除此之外生成[0,1)之间的浮点数的方法还有:
numpy.random.randn(d0,d1,…,dn)
np.random.randn() # 当没有参数时,返回单个数据
-1.1241580894939212

np.random.randn(2,4)
array([[ 0.27795239, -2.57882503,  0.3817649 ,  1.42367345],
       [-1.16724625, -0.22408299,  0.63006614, -0.41714538]])

np.random.randn(4,3,2)
array([[[ 1.27820764,  0.92479163],
        [-0.15151257,  1.3428253 ],
        [-1.30948998,  0.15493686]],
 
       [[-1.49645411, -0.27724089],
        [ 0.71590275,  0.81377671],
        [-0.71833341,  1.61637676]],
 
       [[ 0.52486563, -1.7345101 ],
        [ 1.24456943, -0.10902915],
        [ 1.27292735, -0.00926068]],
 
       [[ 0.88303   ,  0.46116413],
        [ 0.13305507,  2.44968809],
        [-0.73132153, -0.88586716]]])
标准正态分布介绍
numpy.random.randint(low, high=None, size=None, dtype=’l’)
numpy.random.choice(a, size=None, replace=True, p=None)
np.random.choice(5,3)
[0 3 1]

np.random.choice(5, 3, replace=False) # 当replace为False时,生成的随机数不能有重复的数值

demo_list = ['lenovo', 'sansumg','moto','xiaomi', 'iphone']
np.random.choice(demo_list,size=(3,3))
array([['moto', 'iphone', 'xiaomi'],
       ['lenovo', 'xiaomi', 'xiaomi'],
       ['xiaomi', 'lenovo', 'iphone']],
      dtype='<U7')

demo_list = ['lenovo', 'sansumg','moto','xiaomi', 'iphone']
np.random.choice(demo_list,size=(3,3), p=[0.1,0.6,0.1,0.1,0.1])
array([['sansumg', 'sansumg', 'sansumg'],
       ['sansumg', 'sansumg', 'sansumg'],
       ['sansumg', 'xiaomi', 'iphone']],
      dtype='<U7')
numpy.random.seed()
np.random.seed(0)
np.random.rand(5)
array([ 0.5488135 ,  0.71518937,  0.60276338,  0.54488318,  0.4236548 ])

np.random.seed(1676)
np.random.rand(5)
array([ 0.39983389,  0.29426895,  0.89541728,  0.71807369,  0.3531823 ])

np.random.seed(1676)
np.random.rand(5)
array([ 0.39983389,  0.29426895,  0.89541728,  0.71807369,  0.3531823 ])    
上一篇下一篇

猜你喜欢

热点阅读