NumPy(三)矩阵和随机数:
- 矩阵——np.matrix
matrix(字符串/列表/元组/数组)
mat(字符串/列表/元组/数组)
>>>a = np.mat('1 2 3; 4 5 6')
>>>a
matrix([[1, 2, 3],
[4, 5, 6]])
>>>a = np.mat([[1, 2, 3], [4, 5, 6]])
>>>a
matrix([[1, 2, 3],
[4, 5, 6]])
>>>type(a)
<class 'numpy.matrix'>
矩阵对象的属性
.ndim # 矩阵的维数
.shape # 矩阵的shape
.size # 矩阵的元素个数
.dtype # 元素的数据类型
矩阵相乘
>>> a1 = np.mat([[0, 1], [2, 3]])
>>> a2 = np.mat([[1, 1], [2, 0]])
>>> a1 * a2 # 点积
matrix([[2, 0],
[8, 2]])
矩阵转置、求逆
>>> a1.T # 矩阵转置
matrix([[0, 2],
[1, 3]])
>>> a1.I # 矩阵求逆
matrix([[-1.5, 0.5],
[ 1. , 0. ]])
# 验证逆矩阵:矩阵点乘逆矩阵为单位矩阵
>>> a1.I * a1
matrix([[1., 0.],
[0., 1.]])
>>> a1 * a1.I
matrix([[1., 0.],
[0., 1.]])
矩阵 VS 二维数组
- 矩阵:
- 运算符号简单
- 二维数组:
- 能够表示高维数组
- 数组更加灵活,速度更快
随机数模块
np.random
函数 | 功能描述 | 返回值 |
---|---|---|
np.random.rand(d0, d1,…dn) | 元素在[0, 1)区间均匀分布的数组 | 浮点数 |
np.random.uniform(low, high, size) | 元素在[low, high)区间均匀分布的数组 | 浮点数 |
np.random.randint(low, high, size) | 元素在[low, high)区间均匀分布的数组 | 整数 |
np.random.randn(d0, d1, …,dn) | 产生标准正态分布的数组 | 浮点数 |
np.random.normal(loc, scale, size) | 产生正态分布的数组 | 浮点数 |
np.random.rand(d0, d1,...dn)
np.random.uniform(low, high, size)
np.random.randint(low, high, size)
np.random.randn(d0, d1, ...,dn)
np.random.normal(loc, scale, size) # loc:均值;scale:标准差
例子:
>>> np.random.rand(2, 3)
array([[0.34929435, 0.97524057, 0.13821306],
[0.54342625, 0.6351517 , 0.09601334]])
>>> np.random.rand()
0.8941615648054206
>>> np.random.uniform(1, 5, (3, 2)) # 均匀分布 浮点数
array([[1.85460959, 1.76077055],
[3.27975011, 4.47869258],
[4.23639116, 1.61378559]])
>>> np.random.normal(0, 1, (3, 2)) # 正态分布 浮点数
array([[ 1.29502989, 0.2727421 ],
[-0.04497388, -0.20752521],
[ 1.2007246 , 0.50583995]])
- 伪随机数:由随机种子,根据一定的算法生成。
- 随机种子:指定随机数生成时所用算法开始的整数值。
- 如果使用相同的seed()值,则每次生成的随机数都相同。
- 如果不设置这个值,则系统根据时间来自己选择这个值,此时每次生成的随机数因时间差异而不同。
- seed()方式设置种子,仅一次有效。
- 随机数产生的算法和系统有关,如windows和Linux。
设置随机数种子:
>>> np.random.seed(612) # 设置随机数种子(这种方式设置种子,仅一次有效)
>>> np.random.rand(2, 3)
array([[0.14347163, 0.49589878, 0.95454587],
[0.13751674, 0.85456667, 0.42853136]])
>>> np.random.seed(612)
>>> np.random.rand(2, 3) # rand两次生成结果一致
array([[0.14347163, 0.49589878, 0.95454587],
[0.13751674, 0.85456667, 0.42853136]])
打乱顺序函数
np.random.shuffle(序列) # list或ndarray
>>> arr = np.arange(10)
>>> arr
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.random.shuffle(arr) # 打乱
>>> arr
array([5, 6, 0, 7, 3, 2, 9, 8, 1, 4])
# 注:对于多维数组,shuffle函数只打乱第0维元素的顺序。
>>> b = np.arange(12).reshape(4, 3)
>>> b
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
>>> np.random.shuffle(b)
>>> b # 只打乱了第0维的元素,相当于只打乱了图片顺序,而不打乱图片像素
array([[ 0, 1, 2],
[ 6, 7, 8],
[ 9, 10, 11],
[ 3, 4, 5]])