基於numpy的隨機數構造
class numpy.random.RandomState(seed=None)
RandomState 是一個基於Mersenne Twister算法的偽隨機數生成類
RandomState 包含很多生成 概率分布的偽隨機數 的方法。
如果指定seed值,那麽每次生成的隨機數都是一樣的。即對於某一個偽隨機數發生器,只要該種子相同,產生的隨機數序列就是相同的。
numpy.random.RandomState.rand(d0, d1, ..., dn)
Random values in a given shape.
Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).
rand()函數產生 [0,1)間的均勻分布的指定維度的 偽隨機數
Parameters:
d0, d1, …, dn : int, optional
The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.
Returns:
out : ndarray, shape (d0, d1, ..., dn)
Random values.
numpy.random.RandomState.uniform(low=0.0, high=1.0, size=None)
Draw samples from a uniform distribution.
Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform.
uniform()函數產生 [low,high)間的 均勻分布的指定維度的 偽隨機數
Parameters:
low : float or array_like of floats, optional
Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.
high : float or array_like of floats
Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
If size is None (default), a single value is returned if low and high are both scalars. Otherwise, np.broadcast(low, high).size samples are drawn.
Returns:
out : ndarray or scalar
Drawn samples from the parameterized uniform distribution.
有時候我們需要自己模擬構造 輸入數據(矩陣),那麽這種隨機數的生成是一種很好的方式。
1 # -*- coding: utf-8 -*- 2 """ 3 Created on Tue May 29 12:14:11 2018 4 5 @author: Frank 6 """ 7 8 import numpy as np 9 10 #基於seed產生隨機數 11 rng = np.random.RandomState(seed) 12 print(type(rng)) 13 14 #生成[0,1)間的 32行2列矩陣 15 X=rng.rand(32, 2) 16 print("X.type{}".format(type(X))) 17 print(X) 18 19 #生成[0,1)間的 一個隨機數 20 a1 = rng.rand() 21 print("a1.type{}".format(type(a1))) 22 print(a1) 23 24 #生成[0,1)間的 一個包含兩個元素的隨機數組 25 a2 = rng.rand(2) 26 print("a2.type{}".format(type(a2))) 27 print(a2) 28 29 #生成[1,2)間的隨機浮點數 30 X1 = rng.uniform(1,2) 31 print("X1.type{}".format(type(X1))) 32 print(X1) 33 34 #生成[1,2)間的隨機數,一維數組且僅含1個數 35 X2 = rng.uniform(1,2,1) 36 print("X2.type{}".format(type(X2))) 37 print(X2) 38 39 #生成[1,2)間的隨機數,一維數組且僅含2個數 40 X3 = rng.uniform(1,2,2) 41 print("X3.type{}".format(type(X3))) 42 print(X3) 43 44 #生成[1,2)間的隨機數,2行3列矩陣 45 X4 = rng.uniform(1,2,(2,3)) 46 print("X4.type{}".format(type(X4))) 47 print(X4)
基於numpy的隨機數構造