Bird
0
0

You have a large sparse matrix representing user-item ratings with many zeros. You want to efficiently compute the sum of all ratings for each user (row). Which approach using CSR format is best?

hard📝 Application Q15 of 15
SciPy - Sparse Matrices (scipy.sparse)
You have a large sparse matrix representing user-item ratings with many zeros. You want to efficiently compute the sum of all ratings for each user (row). Which approach using CSR format is best?
AUse the CSR matrix's <code>sum(axis=0)</code> method to sum rows.
BConvert the CSR matrix back to a dense array and use NumPy sum along axis 1.
CUse the CSR matrix's <code>sum(axis=1)</code> method to sum non-zero values per row efficiently.
DManually iterate over all elements including zeros to sum each row.
Step-by-Step Solution
Solution:
  1. Step 1: Understand CSR matrix row sum

    CSR format stores data row-wise, so summing along axis 1 is efficient and skips zeros.
  2. Step 2: Evaluate options for efficiency

    Use the CSR matrix's sum(axis=1) method to sum non-zero values per row efficiently. uses sum(axis=1) directly on CSR, which is fast and memory efficient. Convert the CSR matrix back to a dense array and use NumPy sum along axis 1. wastes memory converting to dense. Manually iterate over all elements including zeros to sum each row. is slow. Use the CSR matrix's sum(axis=0) method to sum rows. sums columns, not rows.
  3. Final Answer:

    Use the CSR matrix's sum(axis=1) method to sum non-zero values per row efficiently. -> Option C
  4. Quick Check:

    Sum rows with csr.sum(axis=1) [OK]
Quick Trick: Sum rows with csr.sum(axis=1) for efficiency [OK]
Common Mistakes:
MISTAKES
  • Converting to dense wastes memory
  • Summing axis=0 sums columns, not rows
  • Iterating manually is slow and unnecessary

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SciPy Quizzes