https://www.cnblogs.com/td15980891505/p/6198036.html
numpy.random模塊中提供啦大量的隨機數相關的函數。
1 numpy中產生隨機數的方法
1)rand() 產生[0,1]的浮點隨機數,括號里面的參數可以指定產生數組的形狀
2)randn() 產生標准正太分布隨機數,參數含義與random相同
3)randint() 產生指定范圍的隨機數,最后一個參數是元祖,他確定數組的形狀
1
2
3
4
5
6
7
8
9
10
11
12
|
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
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
[[
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() 泊松分布
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
# -*- 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
|
1
2
3
4
5
6
7
8
9
10
|
[[
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()是從指定的樣本中隨機抽取。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
# -*- 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
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
[[
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)
|