# 机器学习储备（10）：numpy之RandomState() 和 axis

1 RandomState

RandomState是一个伪随机数发生器，这是一个numpy的类，其中包括的方法有：rand，randint，uniform 等。

#导入numpy

import numpy as np

#实例化RandomState，种子数设置为1 。

rng = np.random.RandomState(1)

#引用rand生成0~1的2行5列的二维数组

rng.rand(2,5)

array([[ 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]])

#引用uniform生成取值范围在0~3的100行2列的均匀分布的二维数组

a = rng.uniform(0,3,(100,2))

2 axis

numpy中许多API的参数都带有：axis，它的作用是什么呢？ 请看下面例子：

np.sum(a,axis=0)

array([ 134.70958663, 156.50550662])

np.sum(a,axis=1)

array([ 3.41203949, 0.90734084, 0.71728346, 1.59546282, 2.80675262,

3.31324204, 3.24770906, 2.09356531, 2.92798389, 1.01546528,

5.30701843, 3.01724038, 5.31298745, 0.37229698, 3.14391877,

1.55836338, 4.47316445, 3.02217823, 4.5633798 , 2.30529778,

5.21108023, 3.20916996, 1.6533586 , 3.60662895, 1.25341173,

2.09460747, 1.43152433, 1.63480711, 2.16253854, 3.86719169,

1.54917125, 3.32573828, 1.75754959, 3.53605127, 4.59344939,

3.12262986, 2.84000291, 1.6890931 , 3.82582332, 4.43043027,

4.52093489, 3.29952233, 3.49744233, 4.17879371, 3.85541165,

3.19270569, 3.08490524, 1.93549135, 4.43117702, 1.86004572,

2.56110901, 3.72963558, 4.5956858 , 2.83577543, 5.0646593 ,

0.92842877, 4.88824087, 2.46438968, 5.03070217, 2.50738716,

0.13827336, 0.82355267, 4.19657704, 4.18455861, 1.21007098,

4.66606506, 1.73903253, 3.10082084, 3.58489752, 4.83199049,

2.07808638, 0.54378344, 0.45613802, 2.81609496, 1.71681889,

3.11775183, 2.31418109, 2.9884548 , 2.33036523, 5.45054637,

2.20085242, 4.34680985, 0.52610279, 1.66910176, 3.5255427 ,

3.91793569, 2.87965918, 3.88884795, 2.80245735, 1.3092571 ,

2.51967455, 2.45787611, 3.19520899, 2.49868549, 4.34843484,

0.98777358, 4.52173198, 5.51936377, 0.74494098, 4.69738403])

axis = 0后，即对第一维求和，结果中看不到这一维；

axis = 1后，即对第二维求和，结果中看不到这一维；

testX = np.array([[1,9,7],[-10,20,4]])

array([[ 1, 9, 7],

[-10, 20, 4]])

array([[-10, 9, 4],

[ 1, 20, 7]]) 即axis=0，按照第一维排序二维数组，得到的结果如上。

axis = 0后，即按照第一维排序，维数不变；

axis = 1后，即按照第二维排序，维数不变；

337 篇文章94 人订阅

0 条评论

1334

3844

4116

3716

1043

1130

2917

23810

1483

3199