def trim_sparse(M, n_std=<NUM_LIT:3>, s_min=None, s_max=None):
try:<EOL><INDENT>from scipy.sparse import coo_matrix<EOL><DEDENT>except ImportError as e:<EOL><INDENT>print(str(e))<EOL>print("<STR_LIT>")<EOL>return trim_dense(M.todense())<EOL><DEDENT>r = M.tocoo()<EOL>sparsity = np.array(r.sum(axis=<NUM_LIT:1>)).flatten()<EOL>mean = np.mean(sparsity)<EOL>std = np.std(sparsity)<EOL>if s_min is None:<EOL><INDENT>s_min = mean - n_std * std<EOL><DEDENT>if s_max is None:<EOL><INDENT>s_max = mean + n_std * std<EOL><DEDENT>f = (sparsity > s_min) * (sparsity < s_max)<EOL>indices = [u for u in range(len(r.data)) if f[r.row[u]] and f[r.col[u]]]<EOL>rows = np.array([r.row[i] for i in indices])<EOL>cols = np.array([r.col[j] for j in indices])<EOL>data = np.array([r.data[k] for k in indices])<EOL>N = coo_matrix((data, (rows, cols)))<EOL>return N<EOL>
Apply the trimming procedure to a sparse matrix.