WorksheetsBounty Quiz - Part 2
Total questions: 100
Worksheet time: 1hrs 15mins
What is the output of [1,2,3] + [4,5,6] in Python?
[5, 7, 9]
[1, 2, 3, 4, 5, 6]
Error
[[1,2,3], [4,5,6]]
Given x = [1, 2, 3] and y = x, then y[0] = 10. What is the value of x[0]?
1
10
None
Error
What is the result of 5 // 2 in Python 3?
2.5
2
3
2.0
Given nums = [1, 2, 3, 4, 5], what does nums[-2:] return?
[4, 5]
[2, 3]
[1, 2]
[3, 4]
What sequence does list(range(10, 1, -2)) generate?
[10, 8, 6, 4, 2]
[10, 8, 6, 4, 2, 0]
[1, 3, 5, 7, 9]
[2, 4, 6, 8, 10]
What type of error occurs when executing s = "hello"; s[0] = 'H'?
SyntaxError
TypeError
ValueError
AttributeError
Given a = [1, 2, 3] and b = [1, 2, 3]. Which statement is True?
a == b is False, a is b is True
a == b is True, a is b is True
a == b is True, a is b is False
a == b is False, a is b is False
Given matrix = [[1,2,3], [4,5,6], [7,8,9]], which list comprehension extracts diagonal elements?
[matrix[i][i] for i in range(len(matrix))]
[row[i] for i, row in enumerate(matrix)]
Both A and B
[matrix[i][j] for i in range(3) for j in range(3) if i==j]
What is the key difference between list.sort() and sorted(list)?
sort() returns a new list, sorted() modifies in place
sort() modifies in place and returns None, sorted() returns a new list
Both return a new list
Both modify in place
What happens when you execute d = {'a': 1, 'b': 2}; d['c']?
Returns None
Returns 0
Raises KeyError
Returns empty string
What does lambda x: x**2 if x > 0 else 0 return for input -5?
25
-25
0
Error
Given nums = [1, 2, 3, 4, 5] and result = [x for i, x in enumerate(nums) if i != nums.index(x)], what is result?
[1]
[2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1]
Consider: a = [[1, 2], [3, 4]]; b = a[:]; b[0][0] = 99. What is a[0][0]?
1
99
None
Error
What is the time complexity of x in my_list for a list with n elements?
O(1)
O(log n)
O(n)
O(n2)
Given def func(x, lst=[]): lst.append(x); return lst, what happens when you call func(1) then func(2) separately?
Returns [1] then [2]
Returns [1] then [1, 2]
Returns [2] then [2]
Error
What is the default color space when reading an image using cv2.imread()?
RGB
BGR
Grayscale
HSV
If an image has shape (480, 640, 3), what does the first dimension (480) represent?
Width
Height
Number of channels
Depth
What does cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) do?
Converts BGR to RGB
Converts BGR to grayscale using weighted average
Takes only the first channel
Inverts the image colors
In cv2.GaussianBlur(img, (5,5), 0), why must the kernel size be odd numbers?
For faster computation
To have a center pixel for the kernel
OpenCV requirement only, no mathematical reason
To reduce memory usage
When applying cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY), what is a potential problem?
It's too slow
Hard threshold can lose edge information near the threshold value
It only works on color images
Memory overflow
In Canny edge detection, why are two thresholds needed?
One for upper edge, one for lower edge
One for strong edges, one for weak edges that connect to strong edges
One for vertical edges, one for horizontal edges
For redundancy and error checking
If you resize an image from 1000×1000 to 100×100 and then back to 1000×1000, what happens?
You get the exact original image
Image quality is lost due to downsampling
Image becomes sharper
Only color information is lost
In cv2.CascadeClassifier face detection, how does the scaleFactor parameter affect performance?
Larger scaleFactor = faster but may miss faces
Larger scaleFactor = slower but more accurate
It only affects memory usage
It has no effect on detection
In morphological operations, what does Opening (Erosion then Dilation) remove?
Large white regions
Small white noise
Small black holes
Large black regions
When using cv2.warpAffine(), what determines the output image dimensions?
Only the transformation matrix
Only the input image size
The dsize parameter must be specified explicitly
Automatically calculated from matrix
What is the result of np.array([1,2,3]) * 2?
[1, 2, 3, 1, 2, 3]
[2, 4, 6]
6
Error
Given arr = np.array([[1,2,3],[4,5,6]]), what does arr.shape return?
(2, 3)
(3, 2)
6
(6,)
If a = np.array([1,2,3]) and b = np.array([4,5,6]), what is np.dot(a, b)?
[4, 10, 18]
32
[5, 7, 9]
[[4,5,6],[8,10,12],[12,15,18]]
How many elements does np.arange(0, 1, 0.1) create?
9
10
11
100
Given arr = np.array([1,2,3,4,5]), what does arr[arr > 2] return?
[True, True, True, False, False]
[3, 4, 5]
[False, False, True, True, True]
Error
What is the shape of np.array([1,2,3]) + np.array([[1],[2],[3]])?
(3,)
(3, 1)
(3, 3)
Error
You have feature matrix x with shape (1000, 50). To compute mean of each feature, which axis do you use?
axis=0
axis=1
axis=None
No axis needed
Given arr = np.array([[1,2,3],[4,5,6]]), what is the result of np.sum(arr, axis=1)?
[5, 7, 9]
[6, 15]
21
[[1,2,3],[4,5,6]]
What's the difference between np.zeros((3,3)) and np.empty((3,3))?
No difference
zeros() initializes to 0, empty() has arbitrary values
empty() initializes to 0, zeros() has arbitrary values
empty() is always faster
For matrices A (100x50) and B (50x100), which operations are valid?
Only np.dot(A, B)
Only A @ B
Both np.dot(A, B) and A @ B
Neither operation is valid
Why is np.random.seed(42) important in ML experiments?
Makes code run faster
Ensures reproducibility of random operations
Reduces memory usage
Prevents errors
You have data x with shape (10000, 100) and want random batches of size 32. Which approach is most efficient?
Use for loop with random selection
Use np.random.permutation() then slice
Use np.random.choice() for each batch
Manually shuffle each time
For broadcasting, A has shape (5, 3) and b has shape (3,). What is the result shape of A * b?
Error - incompatible shapes
(5, 3)
(5,)
(3,)
Given x with shape (n, d), which formula computes squared Euclidean distance matrix efficiently?
np.sum((X[:, None] - X)**2, axis=2)
np.sum(X**2, axis=1).reshape(-1,1) + np.sum(X**2, axis=1) - 2*np.dot(X, X.T)
Both A and B
Neither is correct
You have weights W (100, 50) and input batch X (32, 100). Which operation is valid?
W @ X
X @ W
Both A and B
Neither A nor B
What's the difference between df['column'] and df[['column']]?
No difference
First returns Series, second returns DataFrame
First returns DataFrame, second returns Series
Both return arrays
What does df.dropna() do?
Removes all data
Removes rows with any missing values
Fills missing values with 0
Removes duplicate rows
If df.shape returns (1000, 5), how many rows and columns are there?
5 rows, 1000 columns
1000 rows, 5 columns
5000 elements total
Cannot determine
What does df.head() return by default?
First row
First 5 rows
First 10 rows
Last 5 rows
Given df['age'] = [25, 30, 35, 40], what does df['age'].mean() return?
30
32.5
35
130
What does df[df['age'] > 30] return?
Boolean array
DataFrame with rows where age > 30
Series of ages > 30
Error
What's the difference between groupby().sum() and groupby().transform('sum')?
No difference
First returns aggregated DataFrame, second returns original shape with aggregated values
First is faster
Second only works with numerical data
In pd.merge(df1, df2, on='id', how='left'), what happens to rows in df1 without matching id in df2?
They are removed
They are kept with NaN for df2 columns
Error is raised
They are duplicated
Why should you use pd.to_datetime() on date strings?
To reduce memory
To enable date-based operations and feature extraction
To sort data
For visualization only
To create time-series sequences of length 10, which Pandas function is most useful?
df.rolling()
df.shift()
df.resample()
df.groupby()
Which operation is generally faster for element-wise operations on DataFrames?
df.apply(lambda x: x**2)
df ** 2
Both are equally fast
Depends on DataFrame size
In pd.get_dummies(df['category'], drop_first=True), why use drop_first=True for linear models?
To save memory
To avoid multicollinearity (dummy variable trap)
To make computation faster
To reduce number of features
When would you use plt.scatter() instead of plt.plot()?
For continuous line plots
For showing individual data points without connections
For bar charts
They are interchangeable
What happens if you create multiple plots without plt.figure() or plt.show()?
Error occurs
Plots overlay on same figure
Each plot creates new window
Nothing happens
What is the purpose of plt.xlabel() and plt.ylabel()?
To title the plot
To label the axes
To add legend
To resize the plot
When plotting training and validation loss, why use plt.legend()?
To make plot colorful
To identify which line represents which metric
To add title
To save the plot
What advantage does sns.heatmap(df.corr(), annot=True) provide?
Faster computation
Visual representation of correlations with values displayed
Uses less memory
Automatically selects important features
Which plot best shows the distribution shape of a continuous variable?
sns.barplot()
sns.scatterplot()
sns.histplot() OR sns.kdeplot()
sns.lineplot()
With fig, axes = plt.subplots(2, 3) creating 6 subplots, how do you access the subplot in 2nd row, 1st column?
axes[0, 1]
axes[1, 0]
axes[1, 1]
axes[2, 1]
When plotting a confusion matrix for imbalanced classes, why normalize by row?
To make values sum to 1
To show percentages per true class, avoiding misleading conclusions
To make the heatmap prettier
To reduce computation time
If input shape is (1, 784) and weight matrix is (784, 128), what is the output shape?
(1, 784)
(1, 128)
(784, 128)
(128, 1)
What does it mean when two vectors are orthogonal?
They are parallel
Their dot product is zero
They have the same magnitude
They point in opposite directions
Given vectors a = [1, 0] and b = [0, 1], what is their dot product?
0
1
[1, 1]
[0, 0]
What happens when you multiply any matrix by the identity matrix?
Matrix becomes zero
Matrix becomes transposed
Matrix remains unchanged
Matrix becomes inverted
What is the dimension of the transpose of a 3x4 matrix?
3x4
4x3
1x21
1x12
In neural networks, what happens if you multiply matrices in wrong order?
Result is transposed
Dimension mismatch error
Same result
Zero matrix
In linear regression solution (XTX)−1XTy , what is XTX ?
Covariance matrix
Square matrix of size (features × features)
Identity matrix
Diagonal matrix
When is a matrix non-invertible?
When it's square
When it's rectangular
When its determinant is zero
When it's symmetric
You have 1000 samples with 10 features. What is the maximum rank of your data matrix?
1000
10
10000
999
In PCA, eigenvectors of the covariance matrix represent:
Original features
Directions of maximum variance
Data points
Error terms
What does L2 regularization term λ∣∣W∣∣2 prevent?
Underfitting
Weight values from becoming too large
Bias in predictions
Data leakage
If a neural network layer maps R^n → R^m, what is the shape of its Jacobian matrix?
(n, n)
(m, n)
(n, m)
(m, m)
Why can we compute softmax(x - max(x)) instead of softmax(x) for numerical stability?
It's faster
Subtracting a constant doesn't change softmax output but prevents overflow
It gives different results
It reduces memory usage
In SVD a = UΣVT, what does Σ represent?
Rotation matrix
Diagonal matrix of singular values
Eigenvectors
Covariance matrix
What is the "curse of dimensionality" effect on KNN?
KNN becomes faster
All points become approximately equidistant, reducing discrimination
Memory usage decreases
Accuracy always improves
What is the goal of Linear Regression?
To classify data into categories
To find the best-fit line that minimizes prediction error
To cluster similar data points
To reduce dimensionality
In the linear regression equation y = mx + b, what does 'm' represent?
Y-intercept
Slope/coefficient
Error term
Learning rate
What loss function does Linear Regression typically minimize?
Cross-entropy loss
Hinge loss
Mean Squared Error (MSE)
Absolute error
If learning rate is too large in gradient descent, what happens?
Convergence is slow
Loss may oscillate or diverge
Training is faster and stable
No effect
What does the gradient in gradient descent represent?
The learning rate
The direction and magnitude of steepest ascent
The final weights
The number of iterations
In gradient descent, we update weights by moving in which direction?
Direction of the gradient
Opposite direction of the gradient
Random direction
Direction of maximum loss
What is the main difference between Ridge and Lasso regression?
Ridge uses L1 penalty, Lasso uses L2 penalty
Ridge uses L2 penalty, Lasso uses L1 penalty
Ridge is for classification, Lasso is for regression
No difference
Why do we need a separate test set in regression?
To train faster
To evaluate generalization to unseen data
To save memory
To reduce computation
What problem does Ridge regression solve that ordinary linear regression doesn't?
Non-linear relationships
Multicollinearity and overfitting by penalizing large coefficients
Missing data
Imbalanced classes
In the Ridge regression cost function: MSE + λ∑(wi²), what happens when λ = 0?
All coefficients become zero
It becomes standard linear regression
Model cannot train
Overfitting is maximized
What is a key property of Lasso regression (L1 regularization)?
It can shrink some coefficients exactly to zero (feature selection)
It always increases all coefficients
It only works with categorical data
It requires no hyperparameter tuning
In batch gradient descent, when do we update the weights?
After each sample
After processing all training samples in an epoch
Randomly during training
Only at the end of training
Why is mini-batch gradient descent often preferred over batch gradient descent?
Always more accurate
Balances computation efficiency and gradient estimation quality
Uses less memory than stochastic
Guaranteed to find global minimum
A linear regression model fits training data perfectly but fails on test data. This indicates:
High bias (underfitting)
High variance (overfitting)
Optimal fit
Data is corrupted
In gradient descent, the update rule is: w = w - α × ∂L/∂w. What does α represent and how does it affect convergence?
Momentum; speeds up training
Learning rate; too small = slow, too large = divergence
Regularization parameter; controls overfitting
Batch size; determines update frequency
For Ridge regression with cost function: (1/n)Σ(yi - ŷi)² + λΣwi², what is the effect of increasing λ?
Coefficients get larger, model complexity increases
Coefficients shrink toward zero, model becomes simpler
No effect on coefficients
Training becomes faster
Why is the linear regression cost function (MSE) convex?
It has multiple local minima
It has a single global minimum, guaranteeing gradient descent convergence
It's non-differentiable
It's always zero
In stochastic gradient descent (SGD), weights are updated:
After seeing all samples
After each individual sample
Only once at the end
Never updated
Given features with very different scales (e.g., age: 0-100, income: 0-1000000), why is feature scaling important for gradient descent?
Makes training faster only
Prevents features with larger scales from dominating gradient updates, ensures balanced convergence
Reduces memory usage
Improves visualization
In the normal equation solution: w=(XTX)−1XTy , when would this approach fail or be inefficient compared to gradient descent?
When n (samples) is large and d (features) is small
When XTX is singular (non-invertible) or d is very large (computationally expensive)
When data is normalized
When using regularization
Given predictions [0.1, 0.4, 0.7, 0.9] and true labels [0, 0, 1, 1] with threshold 0.5, what is the accuracy?
50%
75%
100%
25%
For K-fold cross-validation, if you have 100 samples and K=5, how many samples in each fold?
5
10
20
25
In a binary confusion matrix, a False Positive means:
Predicted positive, actually positive
Predicted positive, actually negative
Predicted negative, actually positive
Predicted negative, actually negative
Why is initializing all neural network weights to zero problematic?
Causes overflow
All neurons learn the same features (symmetry problem)
Training is too slow
Prevents backpropagation
You train for 1000 epochs at 5 seconds/epoch with early stopping after 50 epochs of no improvement. If best loss occurs at epoch 100, when does training stop?
Epoch 100
Epoch 150
Epoch 1000
Epoch 50
