numpy中的随机数模块

numpy.random模块中提供啦大量的随机数相关的函数。

1 numpy中产生随机数的方法

  1)rand()   产生[0,1]的浮点随机数,括号里面的参数可以指定产生数组的形状

  2)randn()  产生标准正太分布随机数,参数含义与random相同

  3)randint()  产生指定范围的随机数,最后一个参数是元祖,他确定数组的形状

import numpy as np
from numpy import random as nr

#只显示小数点后两位
np.set_printoptions(precision = 2)
r1 = nr.rand(3,4)
r2 = nr.randn(5,4)
r3 = nr.randint(0,10,size = (4,3))

print r1
print r2
print r3

 

[[ 0.34  0.51  0.65  0.57]
 [ 0.97  0.16  0.62  0.37]
 [ 0.23  0.78  0.77  0.46]]
[[-0.69 -1.24 -0.32  1.07]
 [ 0.05 -1.97  1.01 -1.59]
 [ 1.51 -1.21  1.02 -0.19]
 [ 1.49 -0.42  0.64  0.07]
 [-0.1   1.11  0.24 -0.18]]
[[9 6 7]
 [1 9 7]
 [4 9 6]
 [3 9 0]]
(Pdb) 

 2 常用分布

  1)normal()  正太分布

  2)uniform()  均匀分布

  3)poisson()  泊松分布

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
import numpy as np
from numpy import random as nr

#只显示小数点后两位
np.set_printoptions(precision = 2)

#第一个参数是均值,第二个参数是标准差
r1 = nr.normal(100,10,size = (3,4))
print r1

#前两个参数分别是区间的初始值和终值
r2 = nr.uniform(0,10,size = (3,4))
print r2

#第一个参数为指定的lanbda系数
r3 = nr.poisson(2.0,size = (3,4))
print r3

 

[[ 100.67   98.39   99.36  103.37]
 [  98.23   95.11  107.57  111.23]
 [  97.26   75.21  110.4   112.53]]
[[ 2.42  6.81  9.96  3.15]
 [ 9.28  4.4   7.87  5.19]
 [ 3.47  2.92  4.5   2.58]]
[[3 1 5 0]
 [1 0 4 3]
 [3 1 2 1]]
(Pdb) 

 

3 乱序和随机抽取

  permutation()随机生成一个乱序数组,当参数是n时,返回[0,n)的乱序,他返回一个新数组。而shuffle()则直接将原数组打乱。choice()是从指定的样本中随机抽取。

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
import numpy as np
from numpy import random as nr

#只显示小数点后两位
np.set_printoptions(precision = 2)

#返回打乱数组,原数组不变
r1 = nr.randint(10,100,size = (3,4))
print r1
print nr.permutation(r1)
print r1

print nr.permutation(5)

# 使用shuffle打乱数组顺序
x = np.arange(10)
nr.shuffle(x)
print x

#xhoice()函数从指定数组中随机抽取样本
#size参数用于指定输出数组的大小
#replace参数为True时,进行可重复抽取,而False表示进行不可重复的抽取。默认为True
x = np.array(10)
c1 = nr.choice(x,size = (2,3))
print c1

c2 = nr.choice(x,5,replace = False)
print c2

 

[[78 22 43 70]
 [46 87 12 32]
 [11 56 89 79]]
[[11 56 89 79]
 [78 22 43 70]
 [46 87 12 32]]
[[78 22 43 70]
 [46 87 12 32]
 [11 56 89 79]]
[4 1 2 0 3]
[3 4 9 5 8 2 7 0 6 1]
[[4 7 9]
 [9 1 7]]
[5 3 2 8 4]
(Pdb) 

 

posted @ 2016-12-19 16:42  曹孟德  阅读(15721)  评论(0编辑  收藏  举报