繁体   English   中英

如何在矩阵内成对计算

[英]How to calculate pairwise inside a matrix

如何对超过 2 个列表执行配对操作

例子

如果我的矩阵有 2 个列表 (L,M),我计算点积,结果为 [[MM ML, LM LL]]

如何以结果为对称矩阵的方式为具有 2 个以上列表的矩阵计算相同的运算

x = np.array([[1, 3, 5],[1, 4, 5],[2,6,10]])

如何进行成对分析?

Solution 1 :以下蛮力的替代方法是使用np.einsum ,但使用该功能并不简单。 此链接有关于如何使用它的说明, https://ajcr.net/Basic-guide-to-einsum/ 有关如何定义matrix的信息,请参见Solution 2

np.einsum('ij,jk', matrix,matrix.T)
Out[35]: 
array([[35, 38],
       [38, 42]])
matrix = np.array([L, M, N])  # matrix with 3 lists
np.einsum('ij,jk', matrix,matrix.T)
Out[37]: 
array([[ 35,  38,  70],
       [ 38,  42,  76],
       [ 70,  76, 140]])

较小矩阵的Solution 2 解释如下:

def dot_pairwise(matrix):
    return [[np.dot(i, j) for j in matrix]  for i in matrix]

dot_pairwise(matrix)

解释:

import numpy as np
L = np.array([1, 3, 5])
M = np.array([1, 4, 5])
N = np.array([2, 6, 10])

matrix = np.array([L, M, N]) # matrix with 3 lists
# matrix = np.array([L, M])  # matrix with 2 lists to replicate your example


# Initialize an empty result list
result = []

for i in matrix:
    row = []  # Initialize an empty row
    for j in matrix:
        # Calculate the dot product between the ith and jth lists using numpy.dot
        print(i,j) # to print the matrices
        dot_product = np.dot(i, j)
        row.append(dot_product)  # Add the dot product to the row
    result.append(row)  # Add the row to the result

print(result)  # [[LL, LM, LN], [ML, MM, MN], [NL, NM, NN]]

这是使用 L, M 矩阵的结果:

[1 3 5] [1 3 5] LL
[1 3 5] [1 4 5] LM
[1 4 5] [1 3 5] ML
[1 4 5] [1 4 5] MM
[[35, 38], [38, 42]] # dot products

此答案的替代方案,略有更改:

np.tensordot(x, x, axes=(1,1))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM