今天我們要來研究一下NumPy多維陣列,先從一點簡單的開始,二維陣列,俗稱矩陣(matrix),
import numpy as np
if __name__ == "__main__":
# 以二維列表來建立numpy二維陣列
l1 = [[12, 14, 0], [5, 23, 3]]
a1 = np.array(l1)
l2 = [[34, 17, 97], [83, 18, 34]]
a2 = np.array(l2)
print(a1)
# [[12 14 0] [ 5 23 3]]
print(a2)
# [[34 17 97] [83 18 34]]
#矩陣加法
print(a1 + a2)
#[[46 31 97] [88 41 37]]
#矩陣減法
print(a1 - a2)
#[[-22 -3 -97] [-78 5 -31]]
#元素乘積(不是矩陣乘法)
print(a1 * a2)
#[[408 238 0] [415 414 102]]
#矩陣除法
print(a1 / a2)
#[[0.35294118 0.82352941 0. ] [0.06024096 1.27777778 0.08823529]]
矩陣轉置會將欄和列互換
import numpy as np
if __name__ == "__main__":
# 以二維列表來建立numpy二維陣列
l1 = [[12, 14, 0], [5, 23, 3]]
a1 = np.array(l1)
print(a1)
# [[12 14 0]
# [ 5 23 3]]
# 矩陣轉置
print(a1.T)
# [[12 5]
# [14 23]
# [ 0 3]]
注意矩陣點積需要第一個矩陣的欄數等於第二個矩陣的列數喔
import numpy as np
if __name__ == "__main__":
# 以二維列表來建立numpy二維陣列
l1 = [[12, 14, 0], [5, 23, 3]]
a1 = np.array(l1)
l2 = [[34, 17, 97], [83, 18, 34], [44, 19, 22]]
a2 = np.array(l2)
print(a1)
# [[12 14 0]
# [ 5 23 3]]
print(a2)
# [[34 17 97]
# [83 18 34]
# [44 19 22]]
# 矩陣點積
print(a1.dot(a2))
# [[1570 456 1640]
# [2211 556 1333]]
print(a2.dot(a1))
# 報錯 a2的欄數是3 a1的列數是2
import numpy as np
if __name__ == "__main__":
# 以二維列表來建立numpy二維陣列
l1 = [[12, 14, 0], [5, 23, 3]]
a1 = np.array(l1)
l2 = [[34, 17, 97], [83, 18, 34], [44, 19, 22]]
a2 = np.array(l2)
print(a1)
# [[12 14 0]
# [ 5 23 3]]
print(a2)
# [[34 17 97]
# [83 18 34]
# [44 19 22]]
# 矩陣內積
print(np.inner(a1,a2))
# [[ 646 1248 794]
# [ 852 931 723]]
import numpy as np
if __name__ == "__main__":
# 以二維列表來建立numpy二維陣列
l1 = [[12, 14, 0], [5, 23, 3]]
a1 = np.array(l1)
l2 = [[34, 17, 97], [83, 18, 34], [44, 19, 22]]
a2 = np.array(l2)
print(a1)
# [[12 14 0]
# [ 5 23 3]]
print(a2)
# [[34 17 97]
# [83 18 34]
# [44 19 22]]
# 矩陣外積
print(np.outer(a1,a2))
# [[ 408 204 1164 996 216 408 528 228 264]
# [ 476 238 1358 1162 252 476 616 266 308]
# [ 0 0 0 0 0 0 0 0 0]
# [ 170 85 485 415 90 170 220 95 110]
# [ 782 391 2231 1909 414 782 1012 437 506]
# [ 102 51 291 249 54 102 132 57 66]]