12. NumPy创建matrix矩阵

严格意义上讲ndarray数据类型应属数组而非矩阵,而matrix才是矩阵。

12.1 matrix和ndarray区别

矩阵matrix和array的区别主要有两点: 1). 乘法规则有所不同, 如果是array那么乘法是对应元素的乘积作为结果对应位置上的值,而如果是matrix则需要满足第一个矩阵的列等于第二个矩阵的行的要求才能乘。

import numpy as np
a = np.arange(12).reshape([3, 4])
b = np.arange(12).reshape([4, 3])
# wrong
#print a * b
print "multi\n", a * b.T,type(a)
print "matrix multi\n", np.matmul(a, b)
x = np.matrix([[1, 3, 5], [2, 4, 6]])
print x, x.shape,type(x), "# x.shape"
y = np.matrix([[7, 9, 11], [8, 10, 12]])
print y, y.shape, "# y.shape"
# wrong 
#print x * y
print x * y.T, "# x * y.T"
print np.matmul(x, y.T), "# np.matmul(x, y.T)"
print np.multiply(x, y), "# matrix multiply"

a和b都是ndarray数组,a * b.T是数组相乘,要求*前后的操作数的shape必须是一致。而matmul(a, b)则是把第一个形参a和b看作矩阵做矩阵的乘法,要求a的列等与b的行。 x和y是matrix,x * y.T等价于matmul函数。 程序执行结果:

multi
[[  0   3  12  27]
 [  4  20  42  70]
 [ 16  45  80 121]] <type 'numpy.ndarray'>
matrix multi
[[ 42  48  54]
 [114 136 158]
 [186 224 262]]
[[1 3 5]
 [2 4 6]] (2, 3) <class 'numpy.matrixlib.defmatrix.matrix'># x.shape
[[ 7  9 11]
 [ 8 10 12]] (2, 3)# y.shape
[[ 89  98]
 [116 128]] # x * y.T
[[ 89  98]
 [116 128]] # np.matmul(x, y.T)
[[ 7 27 55]
 [16 40 72]] # matrix multiply

如果想对两个同型的matrix矩阵做乘法,需要调用numpy的multiply函数。

2). 数组和矩阵的shape不同。

import numpy as np
w = np.array([1, 2, 4])
print "ndarray", w.shape,w.T.shape
v = np.matrix([1, 2, 4])
print "matrix ", v.shape,v.T.shape

程序执行结果:

ndarray (3,) (3,)
matrix  (1, 3) (3, 1)

12.2 matrix创建方法

在numpy里创建matrix的方法很多,这里先给出常见的两种创建matrix矩阵的方式。

import numpy as np
x = np.matrix([[1, 3, 5], [2, 4, 6]])
print x, "# x"
y = np.matrix("1,2,3;4,5,6;7,8,9")
print y, "# y"

一种是传入二维列表,例如x矩阵的创建,另一种是字符串,用分号间隔每行,逗号间隔每列,例如y矩阵的创建方式。 程序执行结果:

[[1 3 5]
 [2 4 6]]# x
[[1 2 3]
 [4 5 6]
 [7 8 9]]# y

12.3 matrix创建其他方法

参加后续SciPy部分里的内容,有矩阵matrix的创建方法。