GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — python_reference/useful_scripts/sparsify_matrix.py at master · nickwork/python_reference

Expand file tree

/

sparsify_matrix.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
38 lines (26 loc) · 824 Bytes
/

sparsify_matrix.py

Copy path

File metadata and controls

38 lines (26 loc) · 824 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Sebastian Raschka 2014
#
# Sparsifying a matrix by Zeroing out all elements but the top k elements in a row.
# The matrix could be a distance or similarity matrix (e.g., kernel matrix in kernel PCA),
# where we are interested to keep the top k neighbors.
import numpy as np
print('Sparsify a matrix by zeroing all elements but the top 2 values in a row.\n')
A = np.array([[1,2,3,4,5],[9,8,6,4,5],[3,1,7,8,9]])
print('Before:\n%s\n' %A)
k = 2 # keep top k neighbors
for row in A:
sort_idx = np.argsort(row)[::-1] # get indexes of sort order (high to low)
for i in sort_idx[k:]:
row[i]=0
print('After:\n%s\n' %A)
"""
Sparsify a matrix by zeroing all elements but the top 2 values in a row.
Before:
[[1 2 3 4 5]
[9 8 6 4 5]
[3 1 7 8 9]]
After:
[[0 0 0 4 5]
[9 8 0 0 0]
[0 0 0 8 9]]
"""
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.