一、创建矩阵
numpy库中有两种创建矩阵的方法,两种方法产生的矩阵类型有所不同。第一种方法是matrix方法,产生的是普通矩阵:
>>>import numpy as np #在IDLE下直接调用numpy库
>>>A=np.matrix([[1,2],[3,4],[5,6]]) #产生一个3×2的矩阵A
而另一种方法为array方法,产生的是二维数组:
>>>B=np.array(range(1,7)).reshape(3,2) #产生一个三行二列的数组B
上述两个方法生成的矩阵类型有所不同,体现在它们的计算上,在介绍运算 的时候我会提及。
接下来介绍几个numpy内置函数生成一些特殊矩阵:
>>>np.zeros((3,3)) #产生全零3×3方阵
>>>np.identity(3) #生成3×3单位矩阵
>>>np.diag([3,2,1]) #生成对角阵
二、矩阵运算
继续利用前面产生过的矩阵进行运算
>>> A+A
matrix([[ 2, 4],
[ 6, 8],
[10, 12]])
>>> B+B
array([[ 2, 4],
[ 6, 8],
[10, 12]])
>>> A-B
matrix([[0, 0],
[0, 0],
[0, 0]])
>>> B+A
matrix([[ 2, 4],
[ 6, 8],
[10, 12]])
可以看到矩阵类型在计算中的变化,不过虽然类型不同,但矩阵加减法的值的结果仍相同。接下来计算矩阵乘法,而两种类型的默认乘法有所不同。当矩阵是array类时,默认乘法为Hadamard乘法,即按照矩阵内对应元素的位置相乘;当矩阵是matrix类时,默认乘法为矩阵的乘法,即行×列,列×行。
>>> A*A
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
A*A
File "D:\Python36_64\lib\site-packages\numpy\matrixlib\defmatrix.py", line 215, in __mul__
return N.dot(self, asmatrix(other))
ValueError: shapes (3,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0)
>>> B*B
array([[ 1, 4],
[ 9, 16],
[25, 36]])
可以看到,由于A矩阵为matrix类,无法实现自乘,而B矩阵为array类,遵循Hadamard乘法规则实现自乘。若array类矩阵想实现矩阵乘法该怎么做呢?答案是利用dot()函数。
>>> B.dot(B)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
B.dot(B)
ValueError: shapes (3,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0)
B和B使用矩阵乘法,结果显然报错。
array类矩阵还可以实现乘幂的形式:
>>> B**4
array([[ 1, 16],
[ 81, 256],
[ 625, 1296]], dtype=int32)