这里是一个简单的例子。假设
arr1
和
arr2
是numpy阵列,每个阵列都包含长度3的向量,即它们具有形状
N
。
(N,3)
通常在500到2000年之间。我想计算内部产品的所有可能组合,但我也知道数学问题的设计方式是使i-th vector的内部产物在中的内部产物。
N
中的the vector在
arr1
中等于
j
-the vector的内部产物,在
arr2
-the中,the vector在
j
.。在循环的明确嵌套中,这看起来像这样。
arr1
有一种聪明的方法可以在单个命令中对此进行矢量化,而无需进行两倍的计算吗?所以,我用
对内循环进行了矢量
i
但是,尽管计算了两倍的内部产品,但该变体仍然比用单个
arr2
命令计算所有
N = 2000
# For simplicity, I choose arr1 and arr2 to be the same here, but this need not always be the case.
arr1 = np.arange(N*3).reshape((N,3))
arr2 = arr1.copy()
inner_products = np.zeros((arr1.shape[0],arr2.shape[0]))
for idx1 in range(arr1.shape[0]):
vec1 = arr1[idx1]
for idx2 in range(idx1, arr2.shape[0]):
vec2 = arr2[idx2]
inner_products[idx1,idx2] = np.dot(vec1,vec2)
inner_products = inner_products + inner_products.T
inner_products[np.diag_indices(arr1.shape[0])] /= 2
内部产品的速度仍然慢。
inner_products = np.zeros((arr1.shape[0],arr2.shape[0]))
for idx1 in range(arr1.shape[0]):
vec1 = arr1[idx1]
inner_products[idx1,idx1:] = np.dot(vec1.reshape(1,3), arr2[idx1:].T)
inner_products = inner_products + inner_products.T
inner_products[np.diag_indices(arr1.shape[0])] /= 2
numba汇编也不会改变结果;单
N*N
命令保持最快。有一种明智的方法可以将计算量至少保存的问题进行矢量化?
您可以简单地做
np.dot
。请参阅文件。