0
0
NumPydata~20 mins

Covariance with np.cov() in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Covariance Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of np.cov() with two 1D arrays
What is the output of the following code snippet?
NumPy
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
cov_matrix = np.cov(x, y)
print(cov_matrix)
A
[[1. 1.]
 [1. 1.]]
B
[[0.66666667 0.66666667]
 [0.66666667 0.66666667]]
C
[[1.5 1.5]
 [1.5 1.5]]
D
[[2. 2.]
 [2. 2.]]
Attempts:
2 left
💡 Hint
Recall that np.cov() by default calculates sample covariance with normalization by (N-1).
data_output
intermediate
1:30remaining
Shape of covariance matrix from 2D array input
Given the code below, what is the shape of the covariance matrix produced by np.cov()?
NumPy
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6]])
cov_matrix = np.cov(data)
print(cov_matrix.shape)
A(2, 2)
B(3, 3)
C(6, 6)
D(1, 1)
Attempts:
2 left
💡 Hint
np.cov() treats rows as variables and columns as observations by default.
🔧 Debug
advanced
2:00remaining
Identify the error in covariance calculation
What error will this code raise, if any?
NumPy
import numpy as np
x = [1, 2, 3]
y = [4, 5]
cov_matrix = np.cov(x, y)
print(cov_matrix)
ANo error, outputs a covariance matrix
BTypeError: unsupported operand type(s) for -: 'list' and 'list'
CValueError: all the input arrays must have the same length
DIndexError: index out of range
Attempts:
2 left
💡 Hint
Check if input arrays to np.cov() have the same length.
🧠 Conceptual
advanced
1:30remaining
Effect of rowvar parameter in np.cov()
Given a 2D array with shape (3, 4), what does setting rowvar=False do in np.cov()?
ATreats columns as variables and rows as observations
BTreats rows as variables and columns as observations
CRaises an error because rowvar must be True
DReturns a covariance matrix with shape (4, 4) but with zeros
Attempts:
2 left
💡 Hint
rowvar=False changes the interpretation of rows and columns.
🚀 Application
expert
2:30remaining
Calculate covariance matrix for multiple variables
You have a dataset with 3 variables and 5 observations: Variable A: [2, 4, 6, 8, 10] Variable B: [1, 3, 5, 7, 9] Variable C: [5, 7, 9, 11, 13] Using np.cov(), what is the covariance between Variable A and Variable C?
NumPy
import numpy as np
A = np.array([2, 4, 6, 8, 10])
B = np.array([1, 3, 5, 7, 9])
C = np.array([5, 7, 9, 11, 13])
data = np.array([A, B, C])
cov_matrix = np.cov(data)
print(cov_matrix[0, 2])
A9.0
B8.0
C12.5
D10.0
Attempts:
2 left
💡 Hint
Calculate covariance manually or trust np.cov() output for these linear sequences.