我有兩個陣列,A 和 B,尺寸分別為 (l,m,n) 和 (l,m,n,n)。我想獲得一個維度為 (l,m,n) 的陣列 C,它是通過將 A 和 B 視為其第四個 (A) 和第三個和第四個索引 (B) 中的矩陣而獲得的。一個簡單的方法是:
import numpy as np
#Define dimensions
l = 1024
m = l
n = 6
#Create some random arrays
A = np.random.rand(l,m,n)
B = np.random.rand(l,m,n,n)
C = np.zeros((l,m,n))
#Desired multiplication
for i in range(0,l):
for j in range(0,m):
C[i,j,:] = np.matmul(A[i,j,:],B[i,j,:,:])
但是,它很慢(在我的 MacBook 上大約 3 秒)。最快、完全矢量化的方法是什么?
uj5u.com熱心網友回復:
嘗試使用einsum.
它有很多用例,請查看檔案:https ://numpy.org/doc/stable/reference/generated/numpy.einsum.html
或者,有關更多資訊,還可以在以下位置找到一個非常好的解釋:https ://ajcr.net/Basic-guide-to-einsum/
在你的情況下,它似乎
np.einsum('dhi,dhij->dhj',A,B)
應該管用。此外,如果需要,您可以嘗試使用 optimize=True 標志以獲得更快的速度。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432692.html
標籤:Python python-3.x 表现 矩阵 矩阵乘法
