We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 0344428 commit fd65f85Copy full SHA for fd65f85
1 file changed
useful_scripts/sparsify_matrix.py
@@ -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