要在伍兹陈出色的answer 上反弹,还可以使用np.triu() 或np.tril() 以及它们各自的函数来为给定形状的三角矩阵建立索引:np.triu_indices() 或np.tril_indices()。如果我们只想提取非冗余部分,这很有用(因为这样的点积矩阵根据定义是对称的)。
这里是一个使用点积矩阵的上三角部分的例子:
import numpy as np
mat = np.array([[0.64363829, 0.21027068, 0.7358777 ],
[0.39138384, 0.49072791, 0.7784631 ],
[0.22952251, 0.90537974, 0.35722115],
[0.40108871, 0.88992243, 0.21717715],
[0.06710475, 0.84022499, 0.53806962]])
dp = mat.dot(mat.T) # dp := dot_product matrix
dp_unique_vector_indices = np.triu_indices(mat.shape[0]) # assume square matrix
dp_unique_vector_indices_without_diagonal = np.triu_indices(mat.shape[0], 1) # skip the diagonal of ones here
dp_unique_vector = np.triu(dp)[dp_unique_vector_indices]
dp_unique_vector_without_diagonal = np.triu(dp)[dp_unique_vector_indices_without_diagonal]
dp_unique_vector如下:
array([1. , 0.927949 , 0.6009754, 0.6050965, 0.6158193, 1. ,
0.81221 , 0.7627538, 0.8574529, 1. , 0.9753569, 0.9683346,
1. , 0.8915064, 1. ])
而dp_unique_vector_without_diagonal 是:
array([0.927949 , 0.6009754, 0.6050965, 0.6158193, 0.81221 , 0.7627538,
0.8574529, 0.9753569, 0.9683346, 0.8915064])
与全点积矩阵相比:
array([[1. , 0.927949 , 0.6009754, 0.6050965, 0.6158193],
[0.927949 , 1. , 0.81221 , 0.7627538, 0.8574529],
[0.6009754, 0.81221 , 1. , 0.9753569, 0.9683346],
[0.6050965, 0.7627538, 0.9753569, 1. , 0.8915064],
[0.6158193, 0.8574529, 0.9683346, 0.8915064, 1. ]])