人工智慧 機器學習Numpy函式庫基礎功能(MacOS)
阿新 • • 發佈:2019-01-11
進入Python Numpy 開發環境
- 進入開發環境,匯入函式庫。
python
>>> from numpy import *
>>>
- 構造隨機4*4的陣列。
>>> random.rand(4,4) array([[0.768388 , 0.25985153, 0.22463279, 0.15207017], [0.54974659, 0.66975723, 0.43260259, 0.16968662], [0.99561439, 0.19247713, 0.06272048, 0.02427845], [0.37828522, 0.07717839, 0.82606638, 0.62284816]])
- 呼叫
mat()
函式可以將陣列轉化為矩陣:
randMat = mat(random.rand(4,4))
.I
操作符實現了矩陣求逆的運算:
>>> randMat.I matrix([[ 1.82854954, 6.18721531, -1.23217589, -6.21081253], [-2.77985587, -6.95624578, 3.20273141, 6.39917325], [ 3.59647331, 4.48562014, -2.46083948, -4.08390475], [-5.94615554, -9.97699439, 3.74538554, 11.04422169]])
- 執行矩陣的乘法運算,得到矩陣與其逆矩陣相乘的結果:
>>> invRandMat = randMat.I
>>> randMat*invRandMat
matrix([[ 1.0000000e+00, 0.0000000e+00, 0.0000000e+00, 0.0000000e+00],
[ 8.8817842e-16, 1.0000000e+00, 0.0000000e+00, 0.0000000e+00],
[-4.4408921e-16, 0.0000000e+00, 1.0000000e+00, 0.0000000e+00],
[ 0.0000000e+00, 8.8817842e-16, 0.0000000e+00, 1.0000000e+00]])
結果應該是單位矩陣,除了對角線是1,其他都應該是0,但是實際運算中存在誤差。
eye(4)
函式可以建立一個4*4的單位矩陣。用計算後的矩陣減去單位矩陣,計算誤差:
myEye = randMat*invRandMat
>>> myEye - eye(4)
matrix([[ 2.22044605e-16, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00],
[ 8.88178420e-16, 1.77635684e-15, 0.00000000e+00,
0.00000000e+00],
[-4.44089210e-16, 0.00000000e+00, 4.44089210e-16,
0.00000000e+00],
[ 0.00000000e+00, 8.88178420e-16, 0.00000000e+00,
-8.88178420e-16]])