核心區別
矩陣:對應的是二維空間。
數組:對應的是多維空間。
生成方式區別
>>> import numpy as np
>>> a = np.array([[[1,2,3],['a','b','c']],[['e','f','g'],[4,5,6]]])
>>> a
array([[['1', '2', '3'],
['a', 'b', 'c']],
[['e', 'f', 'g'],
['4', '5', '6']]], dtype='<U21')
>>> a.shape
(2, 2, 3)
>>> b = np.matrix([[[1,2,3],['a','b','c']],[['e','f','g'],[4,5,6]]])
ValueError: matrix must be 2-dimensional
>>> c = np.matrix([[1,2,3],['a','b','c']])
>>> c
matrix([['1', '2', '3'],
['a', 'b', 'c']], dtype='<U21')
可以看到矩陣只能是二維的!
運算方式區別
先生成矩陣和數組
import numpy as np
>>> a = np.array([[1,2],[3,4]])
>>> a
array([[1, 2],
[3, 4]])
>>> b = np.array([[4,3],[2,1]])
>>> b
array([[4, 3],
[2, 1]])
>>> a_m = np.matrix([[1,2],[3,4]])
>>> a_m
matrix([[1, 2],
[3, 4]])
>>> b_m = np.matrix([[4,3],[2,1]])
>>> b_m
matrix([[4, 3],
[2, 1]])
對於 array,“ * ” 表示元素相乘
對於 matrix, “ * ” 表示矩陣乘積
>>> a*b
array([[4, 6],
[6, 4]])
>>> a_m*b_m
matrix([[ 8, 5],
[20, 13]])
對 array 計算矩陣乘積,要用 np.dot
>>> np.dot(a,b)
array([[ 8, 5],
[20, 13]])
對於 array,“ **n ” 表示元素的n次方
對於 matrix, “ **n ” 表示矩陣與自己的乘積n次
>>> a**3
array([[ 1, 8],
[27, 64]])
>>> a_m**3
matrix([[ 37, 54],
[ 81, 118]])
在神經網絡中,我們通常都是用的 array ,因爲需要用到多維度的數據,所以在運算方式上,np.dot 是非常常用的,當然元素的批量操作也是很常用。另外 numpy 具有的廣播功能 brodcast 也是非常便利的!