矩陣
創建矩陣
import numpy as np
if __name__ == '__main__':
# 使用mat函數創建矩陣
matr1 = np.mat("1 2 3;4 5 6;7 8 9")
print(matr1)
print("shape:", matr1.shape)
print("------------------------------")
# 使用matrix函數創建矩陣
matr2 = np.matrix([[123], [456], [789]])
print(matr2)
print("shape:", matr2.shape)
print("------------------------------")
# 使用bmat函數創建矩陣
bmat = np.bmat("matr1 matr2; matr1 matr2")
print(bmat)
print("shape:", bmat.shape)
運行結果:
矩陣運算
import numpy as np
if __name__ == '__main__':
matr1 = np.mat("1 2 3;4 5 6;7 8 9")
matr2 = np.matrix([[123], [456], [789]])
# 矩陣不數相乘
print(matr1 * 3)
print("-------------------")
# 矩陣相加減
print(matr1 + matr2)
print("-------------------")
# 矩陣相乘
print(matr1 * matr2)
print("-------------------")
# 矩陣對應元素相乘
print(np.multiply(matr1, matr2))
print("-------------------")
運行結果:
線性代數
Numpy數組間的運算只是相對元素間的運算。可以用numpy.dot和numpy.transpose迚行矩陣乘法運算和矩陣轉置。優點是避免對數據的遍歷。
解方程組:
import numpy as np
if __name__ == '__main__':
A = np.matrix([[3, 6, 5], [1, -3, 2], [5, -1, 4]])
B = np.matrix([[12], [-2], [10]])
x = A ** (-1) * B
print(x)
運行結果:
ufunc函數
全稱通用函數(universal function),是一種能夠對數組中所有元素迚行操作的函數。
- 四則運算:加(+)、減(-)、乘(*)、除(/)、冪(**)。數組間的四則運算表示對每個數組中的元素分別迚行四則運算,所以形狀必須相同。
- 比較運算:>、<、==、>=、<=、!=。比較運算返回的結果是一個布爾數組,每個元素爲每個數組對應元素的比較結果。
- 邏輯運算:np.any函數表示邏輯“or”,np.all函數表示邏輯“and”。運算結果返回布爾值。
ufunc函數的廣播機制
廣播(broadcasting)是指不同形狀的數組之間執行算術運算的斱式。需要遵循4個原則。
- 讓所有輸入數組都向其中shape最長的數組看齊,shape中不足的部分都通過在前面加1補齊。
- 輸入數組的shape是輸入數組shape的各個軸上的最大值。
- 如果輸入數組的某個軸和輸出數組的對應軸的長度相同或者其長度爲1時,這個數組能夠用來計算,否則出錯。
- 當輸入數組的某個軸的長度爲1時,沿着此軸運算時都用此軸上的第一組值。