Python numpy的矩陣計算

2021-08-23 12:21:58 字數 2428 閱讀 2769

import numpy as np

def numpywork1(): # 矩陣的求和運算

one = np.array([[1, 0, 1, 3, 4, 1],

[2, 1, 4, 2, 3, 0],

[3, 5, 4, 1, 3, 2],

[2, 6, 3, 1, 3, 8],

[9, 1, 2, 1, 5, 0],

])two = np.sum(one, axis= 0) # 每一列求和,得到的新矩陣

three = np.sum(one, axis= 1) # 每一行求和,得到的新矩陣

print('two=', two)

print('three=', three)

return

def numpywork2(): # 兩個向量相乘

one = np.array([3, 5, 8, 10, 9, 2, 4, 5, 1])

two = np.array([2, 3, 4, 2, 6, 7, 9, 10, 2])

three = np.multiply(one, two)

print('three=', three)

return

def numpywork3(): # 矩陣的歐氏距離

one = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 3, 9, 7, 8, 9], [1, 2, 6, 4, 8, 6, 7, 8, 9]])

two = np.array([[2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 3, 4, 8, 6, 7, 12, 9, 10], [2, 3, 4, 9, 2, 7, 8, 9, 10]])

dist1 = np.linalg.norm(one - two) # 矩陣的歐氏距離

dist2 = np.square(one - two)

print('one=', one)

print('two=', two)

print('dist1=', dist1) # 此處為乙個數值

print('dist2=', dist2)

return

def euclideandistances(a, b): # 兩個矩陣求歐氏距離 - - - 偏慢(網上提供的方法)

bt = b.transpose()

vecprod = a * bt

sqa = a.geta()**2

sumsqa = np.matrix(np.sum(sqa, axis=1))

sumsqaex = np.tile(sumsqa.transpose(), (1, vecprod.shape[1]))

sqb = b.geta()**2

sumsqb = np.sum(sqb, axis=1)

sumsqbex = np.tile(sumsqb, (vecprod.shape[0], 1))

sqed = sumsqbex + sumsqaex - 2*vecprod

ed = (sqed.geta())**0.5

return np.matrix(ed)

def euclideandistancesbetter(): # 矩陣與向量的歐氏距離計算速度很快,根據數學公式計算的,算起來較快,推薦使用

one = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11],

[15, 16, 17, 18, 19, 20, 21, 22, 23, 24],

[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],

])two = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

result_ed1 = np.linalg.multi_dot([one, two]) # 兩個矩陣向量的歐氏距離

result_ed2 = 1 / (1 + result_ed1)

print('result_ed1= ', result_ed1) # result_ed1= [ 385 440 1155 85]

print('result_ed2= ', result_ed2) # result_ed2= [0.00259067 0.00226757 0.00086505 0.01162791]

return

#numpywork1(): # 矩陣的求和運算

#numpywork2(): # 兩個向量相乘

#numpywork3() # 矩陣的歐氏距離

#euclideandistances(a, b): # 兩個矩陣求歐氏距離 - - - 偏慢

#euclideandistancesbetter() # 矩陣與向量的歐氏距離計算速度很快(推薦使用)

python numpy 矩陣堆疊

在實際操作中,遇到了矩陣堆疊的操作,本來想著自己寫乙個函式,後來想,應該有庫函式,於是一陣找尋 import numpy as np a np.array 1,2,3 b np.array 4,5,6 np.stack a,b 預設行堆疊 輸出 array 1,2,3 4,5,6 np.vstack...

python numpy 矩陣運算

轉置np.transpose x 乘np.dot x,y a.dot b dot c 逆np.linalg.inv x 轉為1維 a.flatten 除 就是乘矩陣的逆a b a.dot np.linalg.inv b 刪除一列axis 1 行axis 0 np.delete t1,j,axis 0...

python numpy包 矩陣運算

下面簡要介紹python和matlab處理數學問題的幾個不同點。1.matlab的基本是矩陣,而numpy的基本型別是多為陣列,把matrix看做是array的子類。2.matlab的索引從1開始,而numpy從0開始。1.建立矩陣 a1 np.array 1,2,3 dtype int 建立乙個一...