Python数据分析库-Numpy中矩阵的点积与乘法
各位客官姥爷好,欢迎回来。上节我们了解了numpy中数组用法,听说numpy也可以创建矩阵,那我们这节来试试吧。
01
矩阵的用法
1. 创建矩阵的方法
#np.mat方法支持以下三种用法a = np.arange(10).reshape((2,5))b = np.mat(a)print(b,type(b))c = np.mat([[1,2,3],[2,3,4]])print(c,type(c))#行与行用分号间隔,列与列用空格分隔d = np.mat('1 2 3; 2 3 4') print(d,type(d))[[0 1 2 3 4]
[5 6 7 8 9]]
<class 'numpy.matrixlib.defmatrix.matrix'>
[[1 2 3]
[2 3 4]]
<class 'numpy.matrixlib.defmatrix.matrix'>
[[1 2 3]
[2 3 4]]
<class 'numpy.matrixlib.defmatrix.matrix'>
2. 矩阵的转置
a = np.arange(10).reshape((2,5))b = np.mat(a)print(b)#第一种用法c = b.Tprint(c,type(c))#第二种用法d = np.transpose(b)print(d,type(d))[[0 1 2 3 4]
[5 6 7 8 9]]
[[0 5]
[1 6]
[2 7]
[3 8]
[4 9]]
<class 'numpy.matrixlib.defmatrix.matrix'>
[[0 5]
[1 6]
[2 7]
[3 8]
[4 9]]
<class 'numpy.matrixlib.defmatrix.matrix'>
3. 矩阵的逆
a = np.arange(10).reshape((2,5))b = np.mat(a)print(b)c = b.Iprint(c)[[0 1 2 3 4]
[5 6 7 8 9]]
[[-3.20000000e-01 1.20000000e-01]
[-1.80000000e-01 8.00000000e-02]
[-4.00000000e-02 4.00000000e-02]
[ 1.00000000e-01 -1.28275056e-17]
[ 2.40000000e-01 -4.00000000e-02]]
4. 矩阵的迹
即对角线元素之和
a = np.arange(9).reshape((3,3))b = np.mat(a)print(b)c = np.trace(b)print(c)[[0 1 2]
[3 4 5]
[6 7 8]]
12
5. 矩阵的点积
a = np.arange(9).reshape((3,3))b = np.mat(a)print(b)c = np.mat([1,2,3]).Tprint(c)#等价于*号d = np.dot(b,c)print(d)#注意当两对象是数组时,*又表示乘积了。e = b*cprint(e)[[0 1 2]
[3 4 5]
[6 7 8]]
[[1]
[2]
[3]]
[[ 8]
[26]
[44]]
[[ 8]
[26]
[44]]
6. 矩阵的乘法
即对应元素相乘,那么这时候就要求矩阵的形状相同。
a = np.arange(4).reshape((2,2))b = np.mat(a)print(b)c = np.mat([[1,2],[5,6]])print(c)#矩阵对应元素相乘d = np.multiply(c,b)print(d)[[0 1]
[2 3]]
[[1 2]
[5 6]]
[[ 0 2]
[10 18]]
以上就是本次的分享,欢迎各位客官姥爷关注我,方便您第一次时间收到【干货】!
