0
0
SciPydata~10 mins

CSR format (Compressed Sparse Row) in SciPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a CSR matrix from data, row indices, and column indices.

SciPy
from scipy.sparse import csr_matrix

data = [1, 2, 3]
rows = [0, 0, 1]
cols = [0, 2, 1]

matrix = csr_matrix(([1], (rows, cols)), shape=(2, 3))
print(matrix.toarray())
Drag options to blanks, or click blank then click option'
Ashape
Brows
Ccols
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Using row or column indices instead of data as the first argument.
2fill in blank
medium

Complete the code to get the number of non-zero elements in the CSR matrix.

SciPy
from scipy.sparse import csr_matrix

matrix = csr_matrix([[0, 0, 1], [2, 0, 3]])

non_zero_count = matrix.[1]
print(non_zero_count)
Drag options to blanks, or click blank then click option'
Asize
Bnnz
Ccount_nonzero
Dshape
Attempts:
3 left
💡 Hint
Common Mistakes
Using shape or size which give matrix dimensions, not count of non-zero elements.
3fill in blank
hard

Fix the error in the code to convert a dense numpy array to CSR format.

SciPy
import numpy as np
from scipy.sparse import csr_matrix

arr = np.array([[0, 4, 0], [3, 0, 0]])
csr = csr_matrix([1])
print(csr.toarray())
Drag options to blanks, or click blank then click option'
Aarr.flatten()
Barr.tolist()
Carr
Dlist(arr)
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a list or flattened array instead of the numpy array.
4fill in blank
hard

Fill both blanks to create a CSR matrix and then access its data array.

SciPy
from scipy.sparse import csr_matrix

data = [10, 20, 30]
rows = [0, 1, 2]
cols = [1, 2, 0]

matrix = csr_matrix(([1], (rows, cols)), shape=(3, 3))
data_array = matrix.[2]
print(data_array)
Drag options to blanks, or click blank then click option'
Adata
Brows
Dindices
Attempts:
3 left
💡 Hint
Common Mistakes
Using row or column indices instead of data for the first blank.
Using 'indices' instead of 'data' to access values.
5fill in blank
hard

Fill all three blanks to create a CSR matrix, convert it to dense, and get its shape.

SciPy
from scipy.sparse import csr_matrix

data = [5, 8, 3, 6]
rows = [0, 0, 1, 2]
cols = [0, 2, 2, 1]

matrix = csr_matrix(([1], ([2], [3])), shape=(3, 3))
dense = matrix.toarray()
print(dense)
print(matrix.shape)
Drag options to blanks, or click blank then click option'
Adata
Brows
Ccols
Dshape
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up rows and columns in the tuple.
Using shape as part of the tuple instead of a separate argument.