numpy-随机数

import numpy as np

nr=np.random
nr.seed(0)
np.set_printoptions(precision=2)    # 只显示小数点后2位

print(nr.rand(3,4))     # 产生[0,1]的浮点随机数,括号里面的参数可以指定产生数组的形状
# [[0.55 0.72 0.6  0.54]
#  [0.42 0.65 0.44 0.89]
#  [0.96 0.38 0.79 0.53]]
print(nr.rand())        # 0.568044561094

print(nr.randn(3,4))    # 产生标准正态分布随机数,参数含义与random相同
# [[ 0.76  0.12  0.44  0.33]
#  [ 1.49 -0.21  0.31 -0.85]
#  [-2.55  0.65  0.86 -0.74]]

print(nr.randint(1,10,size=(2,5)))      # 产生指定范围的随机数,最后一个参数是元祖,他确定数组的形状
# [[8 3 1 1 5]
#  [6 6 7 9 5]]
print(nr.randint(1,10))                 # 5

print(nr.normal(100,10,size=(4,2)))     # 正态分布 第一个参数是均值,第二个参数是标准差
# [[108.13  97.71]
#  [121.62  90.43]
#  [100.67 102.06]
#  [ 95.43  89.4 ]]
print(nr.uniform(0,10,size=(3,4)))      # 均匀分布 前两个参数分别是区间的初始值和终值
# [[7.51 6.08 3.25 0.38]
#  [6.34 9.59 6.53 6.35]
#  [9.95 5.82 4.14 4.75]]
print nr.poisson(2.0,size = (3,4))      # 泊松分布 第一个参数为指定的lanbda系数
# [[3 3 5 1]
#  [3 3 5 1]
#  [3 2 1 2]]

# permutation()随机生成一个乱序数组,当参数是n时,返回[0,n)的乱序,他返回一个新数组。
r1 = nr.randint(10,100,size = (3,4))
print nr.permutation(r1)
# [[50 82 29 82]
#  [71 24 14 77]
#  [36 76 62 77]]
print nr.permutation(5)     # [0 3 1 2 4]

# 使用shuffle打乱数组顺序,打乱原数组,不返回新数组
x = np.arange(10)
y = nr.shuffle(x)
print(y)            # None
print(x)            # [2 4 3 7 1 6 5 9 0 8]

# choice()函数从指定数组中随机抽取样本,size参数用于指定输出数组的大小
# replace参数为True时,进行可重复抽取,而False表示进行不可重复的抽取。默认为True
x = np.array(10)
c1 = nr.choice(x,size = (2,3))
print c1
# [[6 5 3]
#  [1 8 0]]
c2 = nr.choice(x,5,replace = False)
print c2        # [2 9 1 3 8]
原文地址:https://www.cnblogs.com/yanshw/p/10714789.html