def sparsify(x, percentage):
"""
Keeps only as many entries nonzero as specified by percentage.
Note that only the larges values are kept.
--------------------------------------------------------------------------
Usage:
Call: y = sparsify(x, percentage)
Input: x input ndarray x
percentage percentage of nonzero entries in y
Output: sparsified version of x
--------------------------------------------------------------------------
Copyright (C) 2011 Michael Hirsch
"""
vals = np.sort(x.flatten())[::-1]
idx = np.floor(np.prod(x.shape) * percentage/100)
x[x < vals[idx]] = 0
return x
评论列表
文章目录