Concept Flow - Sparse matrix file I/O
Create sparse matrix
Save matrix to file
Close file
Open file
Load sparse matrix
Use matrix for analysis
This flow shows creating a sparse matrix, saving it to a file, then loading it back for use.
from scipy import sparse import numpy as np # Create sparse matrix matrix = sparse.csr_matrix(np.array([[0,0,1],[1,0,0],[0,2,0]])) # Save to file sparse.save_npz('matrix.npz', matrix) # Load from file loaded = sparse.load_npz('matrix.npz')
| Step | Action | Input/State | Output/State |
|---|---|---|---|
| 1 | Create numpy array | [[0,0,1],[1,0,0],[0,2,0]] | Dense numpy array created |
| 2 | Convert to sparse CSR matrix | Dense numpy array | Sparse matrix with 3 non-zero elements |
| 3 | Save sparse matrix to 'matrix.npz' | Sparse matrix | File 'matrix.npz' created with sparse data |
| 4 | Close file | File open | File closed |
| 5 | Open 'matrix.npz' for reading | File closed | File opened |
| 6 | Load sparse matrix from file | File 'matrix.npz' | Sparse matrix loaded with same data |
| 7 | Use loaded matrix | Sparse matrix | Matrix ready for analysis |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 6 | Final |
|---|---|---|---|---|---|---|
| matrix | None | None | Sparse matrix created | Sparse matrix saved | Sparse matrix saved | Sparse matrix saved |
| loaded | None | None | None | None | Sparse matrix loaded | Sparse matrix loaded |
Sparse matrix file I/O with scipy: - Create sparse matrix (e.g., csr_matrix) - Save with sparse.save_npz(filename, matrix) - Load with sparse.load_npz(filename) - Saves space by storing only non-zero elements - Use .npz files for efficient storage