我有一个对称相似度矩阵,我只想保留每行中的 k 个最大值。
这是一些完全符合我要求的代码,但我想知道是否有更好的方法。特别是展平/重塑有点笨拙。提前致谢。
请注意,nrows(如下)必须扩展到数万。
from scipy.spatial.distance import pdist, squareform
random.seed(1)
nrows = 4
a = (random.rand(nrows,nrows))
# Generate a symmetric similarity matrix
s = 1-squareform( pdist( a, 'cosine' ) )
print "Start with:\n", s
# Generate the sorted indices
ss = argsort(s.view(np.ndarray), axis=1)[:,::-1]
s2 = ss + (arange(ss.shape[0])*ss.shape[1])[:,None]
# Zero-out after k-largest-value entries in each row
k = 3 # Number of top-values to keep, per row
s = s.flatten()
s[s2[:,k:].flatten()] = 0
print "Desired output:\n", s.reshape(nrows,nrows)
给出:
Start with:
[[ 1. 0.61103296 0.82177072 0.92487807]
[ 0.61103296 1. 0.94246304 0.7212526 ]
[ 0.82177072 0.94246304 1. 0.87247418]
[ 0.92487807 0.7212526 0.87247418 1. ]]
Desired output:
[[ 1. 0. 0.82177072 0.92487807]
[ 0. 1. 0.94246304 0.7212526 ]
[ 0. 0.94246304 1. 0.87247418]
[ 0.92487807 0. 0.87247418 1. ]]