機器學習二——利用numpy庫對矩陣進行操作

UFly發表於2020-09-30

利用numpy庫對矩陣進行操作

矩陣的初始化

import numpy as np

# 生成3*5的0矩陣
myZero = np.zeros([3, 5])

# 生成3*5的1矩陣
myOnes = np.ones([3, 5])

# 生成3*4的隨機矩陣
myRand = np.random.rand(3, 4)

# 生成3*3的單位矩陣
myEye = np.eye(3)

在這裡插入圖片描述

矩陣的元素運算

1、元素相加減

兩個矩陣的行數和列數必須相同

from numpy import *

# 元素相加減
myOnes = ones([3,3])
myEye = eye(3)
print(myOnes + myEye)
print(myOnes - myEye)

[[2. 1. 1.]
 [1. 2. 1.]
 [1. 1. 2.]]
[[0. 1. 1.]
 [1. 0. 1.]
 [1. 1. 0.]]

2、矩陣數乘

from numpy import *

myMatrix = mat([[1,2,3], [4,5,6], [7,8,9]])
a = 10
print(a*myMatrix)

結果
[[10 20 30]
 [40 50 60]
 [70 80 90]]

3、矩陣所有元素求和

from numpy import *

myMatrix = mat([[1,2,3], [4,5,6], [7,8,9]])
a = 10
print(sum(myMatrix))

結果
45

4、矩陣各元素的積

pyfrom numpy import *

myMatrix = mat([[1,2,3], [4,5,6], [7,8,9]])
myMatrix2 = 1.5*ones([3,3])
print(multiply(myMatrix,myMatrix2))

結果
[[ 1.5  3.   4.5]
 [ 6.   7.5  9. ]
 [10.5 12.  13.5]]

5、矩陣各元素的n次冪

n=2

from numpy import *

myMatrix = mat([[1,2,3], [4,5,6], [7,8,9]])
print(power(myMatrix,2))

結果
[[ 1  4  9]
 [16 25 36]
 [49 64 81]]

矩陣的乘法:矩陣乘矩陣

from numpy import *

myMatrix1 = mat([[1,2,3], [4,5,6], [7,8,9]])
myMatrix2 = mat([[1], [2], [3]])
print(myMatrix1*myMatrix2)

結果
[[14]
 [32]
 [50]]

矩陣的轉置

from numpy import *

myMatrix = mat([[1,2,3], [4,5,6], [7,8,9]])
print(myMatrix.T)  # 從原矩陣上進行轉置
myMatrix.transpose()  # 從原矩陣上進行轉置
print(myMatrix)

結果
[[1 4 7]
 [2 5 8]
 [3 6 9]]
[[1 2 3]
 [4 5 6]
 [7 8 9]]

矩陣的其他操作:行列數、切片、複製、比較

from numpy import *

myMatrix = mat([[1,2,3], [4,5,6], [7,8,9]])
m, n = shape(myMatrix)
print("矩陣的行數和列數:%d和%d" % (m, n) )

myscl1 = myMatrix[0]
print("按行切片:", myscl1)

myscl2 = myMatrix.T[0]
print("按列切片:", myscl2)

mycpmat = myMatrix.copy()
print("複製矩陣:", mycpmat)

print("矩陣元素的比較:\n", myMatrix < myMatrix.T)

結果
矩陣的行數和列數:33
按行切片: [[1 2 3]]
按列切片: [[1 4 7]]
複製矩陣: [[1 2 3]
 [4 5 6]
 [7 8 9]]
矩陣元素的比較:
 [[False  True  True]
 [False False  True]
 [False False False]]

相關文章