8000 sparsify_matrix.py · adrianhust/python_reference@fd65f85 · GitHub
[go: up one dir, main page]

Skip to content

Commit fd65f85

Browse files
committed
sparsify_matrix.py
1 parent 0344428 commit fd65f85

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

useful_scripts/sparsify_matrix.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Sebastian Raschka 2014
2+
#
3+
# Sparsifying a matrix by Zeroing out all elements but the top k elements in a row.
4+
# The matrix could be a distance or similarity matrix (e.g., kernel matrix in kernel PCA),
5+
# where we are interested to keep the top k neighbors.
6+
7+
print('Sparsify a matrix by zeroing all elements but the top 2 values in a row.\n')
8+
9+
A = np.array([[1,2,3,4,5],[9,8,6,4,5],[3,1,7,8,9]])
10+
11+
print('Before:\n%s\n' %A)
12+
13+
14+
k = 2 # keep top k neighbors
15+
for row in A:
16+
sort_idx = np.argsort(row)[::-1] # get indexes of sort order (high to low)
17+
for i in sort_idx[k:]:
18+
row[i]=0
19+
20+
print('After:\n%s\n' %A)
21+
22+
23+
"""
24+
Sparsify a matrix by zeroing all elements but the top 2 values in a row.
25+
26+
Before:
27+
[[1 2 3 4 5]
28+
[9 8 6 4 5]
29+
[3 1 7 8 9]]
30+
31+
After:
32+
[[0 0 0 4 5]
33+
[9 8 0 0 0]
34+
[0 0 0 8 9]]
35+
36+
"""

0 commit comments

Comments
 (0)
0