CertSafari

    Free Scikit-learn Professional Practitioner Certification Sample Questions

    35 free sample questions from our bank of 399+, covering every exam domain, with answers and detailed explanations. Updated August 2026.

    Domain 1: Machine learning concepts

    Subdomain 1.3: Regularization, L1, L2, Elasticnet

    1.Which of the following statements accurately describe the mathematical and practical differences between L1 and L2 regularization in scikit-learn?(Select 3)

    1. A.L1 regularization adds a penalty equal to the absolute value of the magnitude of coefficients.
    2. B.L2 regularization can yield exact zero coefficients, performing implicit feature selection.
    3. C.L2 regularization adds a penalty equal to the square of the magnitude of coefficients.
    4. D.ElasticNet is a linear combination of L1 and L2 penalties.
    5. E.L1 regularization is strictly preferred over L2 when features are highly collinear.
    6. F.The Ridge estimator uses L1 regularization.
    Show answer & explanation

    Correct answers: A, C, DL1 regularization adds a penalty equal to the absolute value of the magnitude of coefficients.; L2 regularization adds a penalty equal to the square of the magnitude of coefficients.; ElasticNet is a linear combination of L1 and L2 penalties.

    • A. Correct. L1 regularization (Lasso) adds a penalty proportional to the sum of the absolute values of the coefficients. This penalty encourages sparsity in the model, often driving some coefficients exactly to zero, which enables implicit feature selection.
    • B. Incorrect. L1 regularization, not L2, yields exact zero coefficients. L2 regularization (Ridge) shrinks coefficients toward zero but they rarely become exactly zero, as the penalty is proportional to the square of the weights.
    • C. Correct. L2 regularization (Ridge) adds a penalty proportional to the square of the magnitude of the coefficients. This effectively penalizes larger weights more heavily than smaller ones, leading to smaller, more stable coefficients, which is particularly useful for handling multicollinearity.
    • D. Correct. ElasticNet combines L1 and L2 penalties into a single objective function. In scikit-learn, this balance is controlled by the 'l1_ratio' parameter, allowing the user to benefit from both the sparsity of L1 and the grouping effects/stability of L2.
    • E. Incorrect. L1 regularization can be unstable when features are highly collinear, often picking one feature at random from a group of correlated features. L2 regularization (or ElasticNet) is generally preferred in these scenarios as it distributes weights across all correlated features.
    • F. Incorrect. In scikit-learn, the Ridge estimator is specifically designed for L2 regularization. The Lasso estimator is the one that implements L1 regularization.

    Subdomain 1.3: Regularization, L1, L2, Elasticnet

    2.You are analyzing a dataset where several predictor variables are highly correlated (multicollinearity). You want to retain all features but stabilize the coefficient estimates to prevent them from becoming wildly large. Which regularization technique is best suited for this specific goal?

    1. A.Lasso Regression
    2. B.Ridge Regression
    3. C.Least Angle Regression (LARS)
    4. D.Truncated SVD
    Show answer & explanation

    Correct answer: BRidge Regression

    • A. Lasso Regression (L1 regularization) is not ideal for this scenario because it encourages sparsity by driving some coefficients exactly to zero. This performs automatic feature selection, which contradicts the goal of retaining all features in the model.
    • B. Ridge Regression (L2 regularization) is the standard solution for multicollinearity when feature retention is required. By adding a penalty proportional to the square of the coefficients, it shrinks them towards zero (stabilizing their variance) without forcing them to zero, thus keeping all predictors in the model.
    • C. Least Angle Regression (LARS) is a specialized algorithm for fitting regression models to high-dimensional data and computing the solution path for Lasso. It is not a regularization penalty itself, and using it with a Lasso objective would still result in feature elimination.
    • D. Truncated SVD is a dimensionality reduction technique that transforms features into a lower-dimensional latent space. While it helps with multicollinearity by creating orthogonal components, it does not preserve the original features or their coefficients as requested.

    Subdomain 1.4: Hard and soft predictions, predict vs predict_proba

    3.You are developing a custom active learning sampling strategy. You want to query the samples that the model is most uncertain about. You are using a LinearSVC. Which method should you use to find the samples closest to the decision boundary?

    1. A.predict_proba(X) and find values closest to 0.5.
    2. B.predict(X) and find samples where the output fluctuates.
    3. C.decision_function(X) and find values with the smallest absolute magnitude (closest to 0).
    4. D.predict_log_proba(X) and find values closest to 0.
    Show answer & explanation

    Correct answer: Cdecision_function(X) and find values with the smallest absolute magnitude (closest to 0).

    • A. Incorrect. LinearSVC does not implement predict_proba by default. While probabilistic classifiers use probabilities near 0.5 to indicate uncertainty, this method is not available for LinearSVC unless wrapped in a utility like CalibratedClassifierCV.
    • B. Incorrect. The predict method returns hard class labels (e.g., 0 or 1). It provides no information regarding the model's confidence or the sample's distance from the decision boundary.
    • C. Correct. LinearSVC implements the decision_function method, which returns the signed distance of each sample to the separating hyperplane. Samples with the smallest absolute magnitude are located closest to the decision boundary, representing the points where the model is least certain.
    • D. Incorrect. LinearSVC does not implement predict_log_proba. Furthermore, log-probabilities are generally used with probabilistic models and are not the standard way to measure margin-based uncertainty in SVMs.

    Subdomain 1.2: Model families, tree-based, linear, ensemble, neighbors

    4.The performance and accuracy of distance-based models like KNeighborsRegressor are highly sensitive to the scale of the features. Which of the following preprocessing steps are commonly applied specifically to mitigate this issue before fitting a KNN model?(Select 2)

    1. A.StandardScaler
    2. B.MinMaxScaler
    3. C.OrdinalEncoder
    4. D.PolynomialFeatures
    5. E.Binarizer
    Show answer & explanation

    Correct answers: A, BStandardScaler; MinMaxScaler

    • A. StandardScaler standardizes features by removing the mean and scaling to unit variance. This ensures each feature contributes comparably to distance calculations in KNN, which is critical when features have different units or variances.
    • B. MinMaxScaler rescales features to a fixed range (typically 0 to 1). This prevents features with larger magnitudes from dominating Euclidean or other distance metrics used by KNN, ensuring all features are on a comparable scale.
    • C. OrdinalEncoder converts categorical values to integer codes. It does not address the scale of continuous features and can distort distance metrics by imposing an arbitrary numerical order on categorical data.
    • D. PolynomialFeatures generates interaction and higher-order terms, increasing the dimensionality of the data. It does not mitigate scale differences and often requires scaling to be applied after the transformation because higher-order terms can exacerbate scale disparities.
    • E. Binarizer thresholds features into binary values. This is a discretization method that discards magnitude information and is not a general scaling technique used to normalize feature ranges for distance-based models.

    Subdomain 1.5: Overfitting and underfitting, impact on soft predictions

    5.Which of the following are characteristic impacts of model underfitting on soft predictions?(Select 2)

    1. A.Predicted probabilities are heavily skewed towards the extremes of 0.0 and 1.0.
    2. B.The variance of the predicted probabilities is artificially low.
    3. C.The model exhibits high resolution in a Brier score decomposition.
    4. D.The calibration curve typically resembles a sigmoid shape.
    5. E.Predicted probabilities tend to cluster around the overall base rate of the positive class.
    Show answer & explanation

    Correct answers: B, EThe variance of the predicted probabilities is artificially low.; Predicted probabilities tend to cluster around the overall base rate of the positive class.

    • A. Incorrect. Predicted probabilities being heavily skewed towards 0.0 and 1.0 is characteristic of an overfitted or overconfident model that over-separates classes. Underfitting produces more muted, less extreme probability estimates.
    • B. Correct. An underfitted model fails to capture the underlying patterns in the data to distinguish between instances, which results in predicted probabilities that lack variety and show an artificially low variance (low spread).
    • C. Incorrect. In a Brier score decomposition, 'resolution' measures the model's ability to distinguish between different outcome frequencies. Underfitted models have low resolution because their predictions do not effectively separate distinct outcome groups.
    • D. Incorrect. A sigmoid-shaped calibration curve is often a sign of specific types of miscalibration (like those found in SVMs) that can be corrected with Platt scaling. Underfitting typically manifests as a lack of discrimination rather than a systematic sigmoid distortion.
    • E. Correct. Underfitted models often revert to the 'naive' prediction, which is the overall base rate (the mean frequency of the positive class), because the model lacks the complexity to learn features that would shift the probability for specific samples.

    Subdomain 1.5: Overfitting and underfitting, impact on soft predictions

    6.Scenario: You are training a `HistGradientBoostingClassifier`. As you increase the number of iterations (`max_iter`), the training log loss approaches zero. However, the validation log loss starts to increase rapidly after 100 iterations, while the validation accuracy remains completely flat. What does this divergence between validation accuracy and validation log loss indicate about the soft predictions?

    1. A.The model is underfitting the decision boundary, causing accuracy to stagnate.
    2. B.The model is becoming overconfident in its predictions on the validation set, pushing probabilities to extremes without changing the hard class assignments.
    3. C.The learning rate is set too low, causing the probabilities to stagnate and log loss to rise.
    4. D.The validation set has a fundamentally different class distribution than the training set.
    Show answer & explanation

    Correct answer: BThe model is becoming overconfident in its predictions on the validation set, pushing probabilities to extremes without changing the hard class assignments.

    • A. Incorrect. Underfitting is inconsistent with the training log loss approaching zero. The model is clearly fitting the training data extremely well. Accuracy stagnation in this context indicates that the decision boundary is no longer improving for the validation set, not that it failed to learn initially.
    • B. Correct. This scenario illustrates a classic case of overfitting in terms of probability calibration. Log loss is highly sensitive to the confidence of a prediction (the distance of the soft prediction from the true label). If the model pushes probabilities closer to 0 or 1 for validation samples it is actually getting wrong, the log loss will spike dramatically even if the top-1 predicted class (and thus accuracy) remains unchanged.
    • C. Incorrect. A low learning rate would slow down the minimization of the loss function across both training and validation sets, making progress more gradual. It would not cause a rapid divergence where validation log loss increases while training loss continues to drop toward zero.
    • D. Incorrect. A distribution mismatch would likely cause poor initial performance or a steady gap in metrics. It does not specifically explain the phenomenon where validation log loss diverges from accuracy during the late stages of iterative boosting.

    Subdomain 1.1: Supervised and unsupervised, regression, classification, clustering, dimensional reduction

    7.Scenario: You have a dataset with 10,000 features and 500 samples. You plan to use `PCA` to reduce the dimensionality to 50 components before training a `LogisticRegression` model. To strictly prevent data leakage during model evaluation, how should you implement this workflow in scikit-learn?

    1. A.Apply `PCA` to the entire dataset using `fit_transform`, then use `train_test_split` on the reduced data.
    2. B.Create a `Pipeline` with `PCA` and `LogisticRegression`, then pass the pipeline to `cross_val_score`.
    3. C.Use `train_test_split`, fit `PCA` on the test set, and transform both the training and test sets.
    4. D.Apply `PCA` independently to the training and test sets using `fit_transform` on both.
    Show answer & explanation

    Correct answer: BCreate a `Pipeline` with `PCA` and `LogisticRegression`, then pass the pipeline to `cross_val_score`.

    • A. Applying PCA to the entire dataset before splitting introduces data leakage. Information from the test set (the distribution and variance) would influence the principal components, leading to an overly optimistic estimate of model performance.
    • B. This is the correct approach. Using a scikit-learn `Pipeline` ensures that the transformer (PCA) is only fitted on the training folds during each iteration of cross-validation. The fitted PCA is then used to transform the validation fold, preventing any information from the validation set from leaking into the training process.
    • C. Fitting PCA on the test set is a fundamental error. Transformers should always be fitted on training data. Using test set statistics to transform training data leaks future information into the model training phase.
    • D. Applying `fit_transform` independently creates two different coordinate systems. The principal components of the training set will not align with the principal components of the test set, resulting in inconsistent feature spaces and invalid model evaluations.

    Subdomain 1.1: Supervised and unsupervised, regression, classification, clustering, dimensional reduction

    8.Scenario: You are building a pipeline that scales features, reduces dimensionality, and then fits a classifier. You want to use Non-Negative Matrix Factorization (`NMF`) for dimensionality reduction. Because `NMF` requires non-negative inputs, you should use ________ as the scaling step in your pipeline to ensure all scaled features are between 0 and 1.

    1. A.StandardScaler
    2. B.MinMaxScaler
    3. C.RobustScaler
    Show answer & explanation

    Correct answer: BMinMaxScaler

    • A. StandardScaler standardizes features by removing the mean and scaling to unit variance. This centering around zero results in both positive and negative values, which violates the non-negativity constraint required for Non-Negative Matrix Factorization (NMF).
    • B. MinMaxScaler scales features to a user-defined range, defaulting to [0, 1]. This transformation ensures all input features are non-negative and bounded, making it the ideal choice for pipelines using NMF or other algorithms that require strictly non-negative inputs.
    • C. RobustScaler scales features based on the median and interquartile range (IQR). Because it centers data around the median, it typically produces negative values for observations below the median, which is incompatible with the requirements of NMF.

    Domain 2: Model building and evaluation

    Subdomain 2.4: Choosing metrics for outliers and imbalanced settings

    9.You are evaluating a multi-label classification model. You want to strictly evaluate if the model predicted the exact set of true labels for each sample. Partial matches should receive a score of 0. Which scikit-learn metric provides this exact match ratio (subset accuracy)?

    1. A.hamming_loss
    2. B.accuracy_score
    3. C.f1_score(average='micro')
    4. D.jaccard_score(average='samples')
    Show answer & explanation

    Correct answer: Baccuracy_score

    • A. Incorrect. Hamming loss computes the fraction of labels that are incorrectly predicted. It averages the error over the total number of labels and samples, effectively giving partial credit for partially correct label sets rather than enforcing an all-or-nothing match.
    • B. Correct. In scikit-learn, when used with multilabel indicator arrays, the accuracy_score function computes the subset accuracy (exact match ratio). This is a strict metric where a sample is considered correctly classified only if the predicted set of labels exactly matches the true set of labels; any partial match results in a score of 0 for that sample.
    • C. Incorrect. The micro-averaged F1 score aggregates global true positives, false positives, and false negatives across all labels. It measures overall label-level performance and rewards partial matches, failing to satisfy the requirement for a strict subset accuracy check.
    • D. Incorrect. The Jaccard score with 'samples' averaging calculates the intersection over union for each sample and then averages these scores. While a perfect match yields 1, it provides fractional credit (between 0 and 1) for partial overlaps between predicted and true label sets.

    Subdomain 2.4: Choosing metrics for outliers and imbalanced settings

    10.You are predicting delivery times. Underestimating time (late delivery) is much worse than overestimating (early delivery). You need a metric that can apply asymmetric penalties to positive and negative errors. Which metric should you use?

    1. A.Mean Squared Error
    2. B.Mean Absolute Error
    3. C.D2 Pinball Score
    4. D.Huber Loss
    Show answer & explanation

    Correct answer: CD2 Pinball Score

    • A. Incorrect. Mean Squared Error (MSE) penalizes squared errors symmetrically. Positive and negative residuals are treated identically regardless of direction, making it unable to account for the higher cost of underestimation without manual modification.
    • B. Incorrect. Mean Absolute Error (MAE) uses the absolute value of the residual, meaning it treats overestimation and underestimation equally. It lacks the mechanism to encode asymmetric costs required for this scenario.
    • C. Correct. The pinball loss (evaluated via the D2 Pinball Score in scikit-learn) is the standard metric for quantile regression. It is inherently asymmetric, allowing the model to penalize underestimation more heavily than overestimation by adjusting the quantile parameter (tau).
    • D. Incorrect. Huber Loss is a robust loss function that switches from squared error to absolute error for large residuals to reduce the influence of outliers. However, it remains symmetric around zero and does not weight positive and negative errors differently.

    Subdomain 2.1: Linear models as baselines

    11.You are building a baseline model but suspect the relationship between the features and the target is non-linear. You want to capture interactions between features while still using a linear model under the hood. What is the standard scikit-learn approach to achieve this?

    1. A.Use LogisticRegression with solver='liblinear'
    2. B.Create a Pipeline with PolynomialFeatures and LinearRegression
    3. C.Use SGDRegressor with loss='squared_epsilon_insensitive'
    4. D.Use RidgeCV with cv=10
    Show answer & explanation

    Correct answer: BCreate a Pipeline with PolynomialFeatures and LinearRegression

    • A. LogisticRegression (with solver='liblinear' or any other solver) is a linear classifier. While the choice of solver affects optimization, it does not create polynomial or interaction terms to capture non-linear relationships in the feature space.
    • B. This is the standard scikit-learn approach. PolynomialFeatures generates interaction terms (e.g., x1*x2) and higher-order terms (e.g., x1^2). By chaining this with a linear model in a Pipeline, the model can represent non-linear relationships while the estimator itself remains linear relative to the transformed features.
    • C. SGDRegressor with 'squared_epsilon_insensitive' loss changes the optimization objective to be more robust to outliers (similar to support vector regression), but it remains a linear estimator and does not inherently model feature interactions or non-linearities.
    • D. RidgeCV performs linear regression with built-in cross-validation for the regularization parameter (alpha). Although it helps prevent overfitting, it is still a linear model acting on the original features and does not introduce non-linear interactions.

    Subdomain 2.3: Bagging and boosting, the working ensemble methods

    12.You are training a BaggingClassifier and want to ensure that each base estimator is trained on a random subset of features, but uses all available samples. To achieve this, you should set bootstrap=False and ___________=True.

    1. A.max_features
    2. B.bootstrap_features
    3. C.oob_score
    Show answer & explanation

    Correct answer: Bbootstrap_features

    • A. Incorrect. 'max_features' is a parameter used to specify the number (or fraction) of features to draw for each base estimator, but it is not a boolean flag. While setting max_features to a value smaller than the total number of features creates subsets, the question specifically asks for a parameter to be set to 'True'.
    • B. Correct. 'bootstrap_features' is a boolean parameter in BaggingClassifier. When set to True, it enables the sampling of features (optionally with replacement depending on max_features). Combined with bootstrap=False (which ensures all samples are used), this configuration implements the Random Subspace method.
    • C. Incorrect. 'oob_score' is a boolean parameter that determines whether to use out-of-bag samples to estimate generalization accuracy. This parameter requires 'bootstrap=True' (for samples) to function and does not control the selection of feature subsets.

    Subdomain 2.3: Bagging and boosting, the working ensemble methods

    13.You are building a RandomForestRegressor and want to make the individual trees as deep as possible until all leaves are pure or contain less than min_samples_split samples. You should leave the ___________ parameter at its default value of None.

    1. A.max_depth
    2. B.max_leaf_nodes
    3. C.min_samples_leaf
    Show answer & explanation

    Correct answer: Amax_depth

    • A. Correct. In scikit-learn's RandomForestRegressor, the max_depth parameter defaults to None. The documentation specifies that if max_depth is None, nodes are expanded until all leaves are pure or until all leaves contain fewer than min_samples_split samples.
    • B. Incorrect. Although max_leaf_nodes also defaults to None (which allows an unlimited number of leaf nodes), the specific stopping criteria regarding purity and min_samples_split mentioned in the question is the formal definition of the behavior when max_depth is None.
    • C. Incorrect. The min_samples_leaf parameter specifies the minimum number of samples required to be at a leaf node. It defaults to 1, not None, and does not define the tree's growth limit in the context of purity and splitting described.

    Subdomain 2.2: Handling correlation with regularization and feature selection

    14.A practitioner is using `RFECV` with a `RandomForestClassifier` to eliminate redundant features. The dataset has 500 features. To speed up the process without significantly compromising the optimal feature subset discovery, what is the most appropriate parameter adjustment?

    1. A.Set `cv=LeaveOneOut()`
    2. B.Increase the `step` parameter to an integer greater than 1 or a float like 0.1
    3. C.Set `importance_getter='auto'` to bypass tree building
    4. D.Change the estimator to `KNeighborsClassifier`
    Show answer & explanation

    Correct answer: BIncrease the `step` parameter to an integer greater than 1 or a float like 0.1

    • A. Using LeaveOneOut cross-validation is extremely computationally expensive as it requires fitting the model N times for every feature subset iteration (where N is the number of samples). This would drastically slow down the process rather than speeding it up.
    • B. Increasing the `step` parameter (e.g., to an integer > 1 or a float like 0.1) reduces the total number of iterations by removing multiple features at each step. This significantly reduces the total number of expensive model refits required, accelerating the process while typically still finding a near-optimal feature subset.
    • C. The `importance_getter` parameter simply specifies how the algorithm retrieves feature importance scores (e.g., from `feature_importances_` or `coef_`). It does not bypass the model fitting process or reduce the number of RFE iterations, so it provides no meaningful performance speed-up.
    • D. Changing the estimator to `KNeighborsClassifier` is inappropriate because KNN does not inherently provide feature importance scores. Using it with RFECV would require external methods like permutation importance, which could be even slower, and it would fundamentally change the logic of the feature selection.

    Domain 3: Interpretation and communication

    Subdomain 3.3: Communicating results to non-technical stakeholders

    15.You are building a biometric authentication system. The security team needs to understand the trade-off between False Rejection Rate (FRR) and False Acceptance Rate (FAR) on a logarithmic scale to set strict security thresholds. Which scikit-learn display is specifically designed to present this exact trade-off to the stakeholders?

    1. A.RocCurveDisplay
    2. B.PrecisionRecallDisplay
    3. C.DetCurveDisplay
    4. D.CalibrationDisplay
    Show answer & explanation

    Correct answer: CDetCurveDisplay

    • A. Incorrect. RocCurveDisplay is used to plot the Receiver Operating Characteristic (ROC) curve, which shows the trade-off between the True Positive Rate (TPR) and the False Positive Rate (FPR). While useful for general classification, it is not the specialized display for biometric systems requiring FRR vs. FAR analysis on a logarithmic scale.
    • B. Incorrect. PrecisionRecallDisplay focuses on the trade-off between precision and recall, which is highly effective for imbalanced datasets. However, it does not directly present the false rejection and false acceptance rates used in biometric threshold selection.
    • C. Correct. DetCurveDisplay is designed for Detection Error Tradeoff curves, which plot the False Negative Rate (FNR, also known as False Rejection Rate) against the False Positive Rate (FPR, also known as False Acceptance Rate). These are commonly used in biometrics and speech recognition because the axes are often scaled such that a normal distribution results in a linear plot, typically visualized on a logarithmic scale to allow stakeholders to distinguish performance at very low error rates.
    • D. Incorrect. CalibrationDisplay is used to assess the reliability of a model by comparing predicted probabilities against actual observed frequencies. It does not communicate the trade-off between classification error types (FAR/FRR).

    Domain 3: Interpretation of results & communication

    Subdomain 3.1: Visualizing results with intermediate matplotlib and seaborn techniques

    16.Scenario: You are evaluating a multi-class classification model. You want to plot a confusion matrix, but you want to completely mask out (hide) the diagonal cells so that the color scale and annotations focus entirely on the off-diagonal misclassifications. You decide to use Seaborn for this custom visualization. Which approach correctly achieves this?

    1. A.Calculate the matrix using `confusion_matrix()`, create a boolean mask for the diagonal using `np.eye()`, and pass both to `sns.heatmap(..., mask=mask)`.
    2. B.Call `ConfusionMatrixDisplay.from_estimator(..., mask_diagonal=True)`.
    3. C.Calculate the matrix using `confusion_matrix(..., normalize='off_diagonal')` and pass it to `sns.heatmap()`.
    4. D.Use `sns.pairplot(..., diag_kind='None')` on the predicted and true labels.
    Show answer & explanation

    Correct answer: ACalculate the matrix using `confusion_matrix()`, create a boolean mask for the diagonal using `np.eye()`, and pass both to `sns.heatmap(..., mask=mask)`.

    • A. Correct. This is the standard procedure for customizing heatmaps in Seaborn. `sklearn.metrics.confusion_matrix` generates the raw data, and `numpy.eye` creates an identity matrix (diagonal of 1s). When passed to `sns.heatmap` via the `mask` parameter, values corresponding to `True` or 1 in the mask are hidden. This allows the color scale and annotations to focus solely on the off-diagonal errors, which are often the primary interest in error analysis.
    • B. Incorrect. The `ConfusionMatrixDisplay` class and its `from_estimator` method in scikit-learn do not feature a `mask_diagonal` parameter in the public API. For custom masking, you must calculate the matrix manually or manipulate the underlying Matplotlib axes.
    • C. Incorrect. The `normalize` parameter in `confusion_matrix` only accepts 'true', 'pred', 'all', or `None`; 'off_diagonal' is not a valid option. Furthermore, normalization changes the value scale but does not mask or hide cells from the visual plot.
    • D. Incorrect. `sns.pairplot` is a tool for visualizing pairwise relationships between features in a DataFrame (using scatter plots or KDEs). It is not appropriate for visualizing a confusion matrix, which represents the relationship between discrete true and predicted labels.

    Subdomain 3.1: Visualizing results with intermediate matplotlib and seaborn techniques

    17.Scenario: You are performing 5-fold cross-validation on a highly imbalanced dataset. You want to plot the Precision-Recall (PR) curve for each individual fold, as well as the mean PR curve with a shaded standard deviation region, all on a single Matplotlib figure. Which of the following steps are required to achieve this using scikit-learn and Matplotlib?(Select 3)

    1. A.Iterate through the CV splits and call `PrecisionRecallDisplay.from_estimator` (or `from_predictions`) for each fold, passing the same `ax`.
    2. B.Use `PrecisionRecallDisplay.from_estimator(..., cv=5)` to automatically plot all folds and the mean curve in one line of code.
    3. C.Interpolate the precision values at a common set of recall levels across all folds to compute the mean PR curve.
    4. D.Use `matplotlib.pyplot.fill_between` to shade the area representing the standard deviation of the precision across the folds.
    5. E.Use `seaborn.relplot` with `kind='line'` and `estimator='mean'` directly on the estimator object.
    6. F.Set `plot_mean=True` and `plot_std=True` in `PrecisionRecallDisplay.from_predictions`.
    Show answer & explanation

    Correct answers: A, C, DIterate through the CV splits and call `PrecisionRecallDisplay.from_estimator` (or `from_predictions`) for each fold, passing the same `ax`.; Interpolate the precision values at a common set of recall levels across all folds to compute the mean PR curve.; Use `matplotlib.pyplot.fill_between` to shade the area representing the standard deviation of the precision across the folds.

    • A. Correct. Iterating through CV splits and calling `PrecisionRecallDisplay.from_estimator` (or `from_predictions`) for each fold while passing the same axes object (`ax`) overlays individual fold curves on a single figure. Scikit-learn's plotting utilities do not automatically iterate over cross-validation folds.
    • B. Incorrect. `PrecisionRecallDisplay.from_estimator` does not provide a `cv` parameter to automatically handle cross-validation and plotting in a single call. This logic must be implemented manually via a loop.
    • C. Correct. Because the specific recall points (thresholds) vary across folds, you cannot average the raw precision results directly. You must interpolate precision values onto a consistent, common set of recall levels (e.g., using `np.linspace`) to calculate a meaningful mean and standard deviation curve.
    • D. Correct. `matplotlib.pyplot.fill_between` is the standard tool for creating shaded uncertainty regions. After calculating the mean and standard deviation of interpolated precision values, this function is used to visualize the variability across folds.
    • E. Incorrect. `seaborn.relplot` is designed for statistical relationships in DataFrames and does not interface directly with scikit-learn estimators to generate Precision-Recall curves. It is not the standard tool for this specific visualization task in the scikit-learn ecosystem.
    • F. Incorrect. Scikit-learn's `PrecisionRecallDisplay` classes do not feature `plot_mean` or `plot_std` parameters. Calculating the mean and shading the standard deviation requires manual interpolation and Matplotlib plotting calls.

    Subdomain 3.2: Interpreting model outputs and performance metrics

    18.A stakeholder wants to understand the relationship between product price and the model's predicted purchase probability. Which approach should you use to explain this relationship most effectively?

    1. A.Show the permutation importance score of the price feature.
    2. B.Generate a Partial Dependence Plot (PDP) using PartialDependenceDisplay to visually show the marginal effect of price on the predicted purchase probability.
    3. C.Plot a scatter plot of price vs actual sales from the training data.
    4. D.Provide the coefficients of a Decision Tree to show the exact mathematical relationship.
    Show answer & explanation

    Correct answer: BGenerate a Partial Dependence Plot (PDP) using PartialDependenceDisplay to visually show the marginal effect of price on the predicted purchase probability.

    • A. Permutation importance quantifies how much model performance drops when a feature is shuffled. While this communicates global importance, it does not illustrate the direction, magnitude, or shape of the relationship between the feature and the target variable.
    • B. A Partial Dependence Plot (PDP), available via scikit-learn's `PartialDependenceDisplay`, visually shows the average marginal effect of a feature on the predicted outcome. This is highly intuitive for non-technical stakeholders as it clearly maps how changes in price correlate with changes in the model's predicted probability.
    • C. A scatter plot of price versus actual sales reflects the raw historical data, not the model's internal logic. This can be misleading because the model may have learned patterns that differ from simple historical correlations due to interactions with other features.
    • D. Decision Trees do not have global linear coefficients like linear regression models; they use split rules and thresholds. Furthermore, providing raw mathematical relationships or coefficients is generally less effective for non-technical stakeholders than visual summaries.

    Subdomain 3.2: Interpreting model outputs and performance metrics

    19.A data scientist has performed K-Means clustering on a dataset with 50 features reduced to 10 principal components to segment customers. The marketing team needs to understand the specific characteristics of 'Cluster 2' to design a targeted campaign. Which of the following are effective ways to communicate the characteristics of this cluster to the stakeholders?(Select 3)

    1. A.Provide the marketing team with the raw coordinates of the cluster centroids in the 50-dimensional PCA space.
    2. B.Explain that K-Means is unsupervised, so it is mathematically impossible to describe the clusters using the original features.
    3. C.Train a DecisionTreeClassifier using the cluster labels as the target variable and visualize the tree to extract simple rules defining Cluster 2.
    4. D.Calculate and present the mean or median values of the original features for Cluster 2 compared to the overall population.
    5. E.Use a parallel coordinates plot or radar chart to visually contrast the feature profiles of the different clusters.
    6. F.Show the silhouette score of the clustering to explain the exact business value of Cluster 2.
    Show answer & explanation

    Correct answers: C, D, ETrain a DecisionTreeClassifier using the cluster labels as the target variable and visualize the tree to extract simple rules defining Cluster 2.; Calculate and present the mean or median values of the original features for Cluster 2 compared to the overall population.; Use a parallel coordinates plot or radar chart to visually contrast the feature profiles of the different clusters.

    • A. Raw coordinates in a PCA-transformed space are linear combinations of original features and are not interpretable to stakeholders. Providing these coordinates would confuse the marketing team rather than offer actionable insights.
    • B. This is factually incorrect. While K-Means finds clusters without ground-truth labels (unsupervised), it is standard practice to interpret those clusters post-hoc using the original features to give them business meaning.
    • C. Training a simple Decision Tree as a 'global surrogate model' is a highly effective interpretability technique. It generates human-readable 'if-then' rules (e.g., 'If Age > 40 and Income > 100k') that approximate the cluster boundaries, making them easy for marketing teams to use for targeting.
    • D. This is a fundamental technique known as 'cluster profiling.' By comparing the average feature values of a specific cluster against the global average (population mean), you can identify the unique traits that define that segment (e.g., 'Cluster 2 spends 30% more on electronics than the average customer').
    • E. Visualizations like radar charts (spider plots) or parallel coordinates are excellent for showing the 'fingerprint' of a cluster. They allow non-technical stakeholders to quickly see which features are over-indexed or under-indexed for a specific group relative to others.
    • F. The silhouette score is a technical diagnostic metric used to evaluate cluster cohesion and separation. It helps the data scientist select the optimal number of clusters but does not describe the business characteristics or content of the clusters themselves.

    Domain 4: Data preprocessing

    Subdomain 4.3: Identifying strongly correlated features

    20.You are building a predictive model for housing prices. Features 'num_bedrooms' and 'house_sqft' have a Pearson correlation of 0.95. When fitting a standard LinearRegression model, you notice the coefficient for 'num_bedrooms' is highly negative, which contradicts domain knowledge. Which scikit-learn approach is the most appropriate to handle this multicollinearity without manually dropping features?

    1. A.Wrap the model in RFE to recursively eliminate features.
    2. B.Replace LinearRegression with Ridge to constrain the coefficient magnitudes.
    3. C.Apply StandardScaler before fitting the LinearRegression model.
    4. D.Use PolynomialFeatures to create interaction terms between the correlated features.
    Show answer & explanation

    Correct answer: BReplace LinearRegression with Ridge to constrain the coefficient magnitudes.

    • A. Incorrect. Recursive Feature Elimination (RFE) works by iteratively removing features. Not only does this effectively drop features (which the prompt suggests avoiding), but it also relies on coefficient weights or feature importances to rank features. Because multicollinearity makes Ordinary Least Squares (OLS) coefficients unstable and unreliable, RFE may produce inconsistent results in this scenario.
    • B. Correct. Ridge regression (L2 regularization) adds a penalty to the loss function proportional to the square of the coefficient magnitudes. This specific constraint reduces the variance of the estimates, which stabilizes coefficients in the presence of multicollinearity. It allows the model to keep all features while mitigating the 'swings' in coefficient values that lead to counter-intuitive signs.
    • C. Incorrect. StandardScaler centers and scales features to unit variance, which is a critical preprocessing step for many estimators (especially regularized ones like Ridge). however, scaling does not change the underlying correlation structure between features and will not resolve the mathematical instability caused by multicollinearity in an OLS model.
    • D. Incorrect. PolynomialFeatures generates interaction and higher-order terms. This increases the complexity and dimensionality of the feature space, which typically exacerbates multicollinearity and coefficient instability rather than resolving it.

    Subdomain 4.3: Identifying strongly correlated features

    21.You are using permutation_importance to evaluate a RandomForestClassifier. You notice that two highly correlated features, A and B, both show near-zero importance, even though domain experts insist they are critical. Which strategies can you implement in scikit-learn to reveal their true importance?(Select 2)

    1. A.Perform hierarchical clustering on the features' correlation matrix, select one representative feature from each cluster, and re-run the model and permutation importance.
    2. B.Group the correlated features and permute them simultaneously as a block using a custom permutation loop, since scikit-learn's native permutation_importance does not support block permutation natively.
    3. C.Increase the n_repeats parameter in permutation_importance to 100 to force the algorithm to separate the correlated features.
    4. D.Switch the scoring metric in permutation_importance from accuracy to f1_score.
    5. E.Apply StandardScaler to features A and B before calculating permutation importance.
    Show answer & explanation

    Correct answers: A, BPerform hierarchical clustering on the features' correlation matrix, select one representative feature from each cluster, and re-run the model and permutation importance.; Group the correlated features and permute them simultaneously as a block using a custom permutation loop, since scikit-learn's native permutation_importance does not support block permutation natively.

    • A. Correct. This is a recommended technique in scikit-learn's documentation for handling multicollinearity. By performing hierarchical clustering and keeping only one feature per cluster, you remove the redundancy that causes the model to split the importance signal. This forces the model to rely on a single informative feature, allowing permutation importance to correctly reflect its contribution.
    • B. Correct. Permutation importance often fails on correlated features because permuting one feature at a time doesn't significantly drop the model's score, as the signal is still available in the correlated twin. Permuting them as a group (block permutation) reveals their joint contribution. Since scikit-learn's 'permutation_importance' function currently only supports individual feature shuffling, a custom implementation is necessary for this strategy.
    • C. Incorrect. The 'n_repeats' parameter increases the number of times the permutation is performed to reduce the variance of the importance estimate. It does not address the bias or 'masking' effect caused by feature correlation.
    • D. Incorrect. Changing the scoring metric might change the magnitude of the importance score based on the performance loss metric used, but it does not address the underlying issue where correlated features mask each other's importance.
    • E. Incorrect. RandomForests are scale-invariant, and applying StandardScaler does not change the relationship or correlation between features. It has no effect on how permutation importance handles multicollinearity.

    Subdomain 4.2: Heatmaps and PCA for first look

    22.When visualizing a massive dataset (e.g., 500,000 samples and 1,000 features) by projecting it down to 2 dimensions using `PCA`, computing the exact full SVD is computationally prohibitive. Which `svd_solver` parameter value in `PCA` is the most efficient choice for extracting only the top 2 components?

    1. A.'full'
    2. B.'arpack'
    3. C.'randomized'
    4. D.'exact'
    Show answer & explanation

    Correct answer: C'randomized'

    • A. The 'full' solver computes the complete SVD using LAPACK, which has a computational complexity of O(n * p * min(n, p)). For a 500,000 x 1,000 matrix, this is extremely slow and memory-intensive, as it calculates all components regardless of how many are requested.
    • B. The 'arpack' solver uses the truncated SVD method (via SciPy's ARPACK wrappers). While more efficient than 'full' for extracting a few components, it is generally slower and less scalable than the randomized approach for very large dense matrices.
    • C. The 'randomized' solver implements a randomized SVD algorithm that is significantly faster and more memory-efficient when the number of components to extract is much smaller than the data dimensions (n_components << min(n_samples, n_features)). It is the default choice in scikit-learn's 'auto' logic for datasets of this scale.
    • D. 'exact' is not a valid parameter value for the `svd_solver` argument in scikit-learn's `PCA` implementation. The standard exact solver is 'full'.

    Subdomain 4.2: Heatmaps and PCA for first look

    23.A data scientist is analyzing a trained `LogisticRegression` model to understand feature importance. To visualize the feature weights as a bar chart, they must extract the `________` attribute from the fitted model object.

    1. A.coef_
    2. B.feature_importances_
    3. C.weights_
    Show answer & explanation

    Correct answer: Acoef_

    • A. Correct. In scikit-learn, the `coef_` attribute stores the learned coefficients (weights) of the linear model. For binary classification, it returns an array of shape (1, n_features), and for multiclass classification (when using OvR or multinomial), it returns an array of shape (n_classes, n_features). These coefficients represent the weights assigned to each feature, which can be plotted to understand feature importance and effect direction.
    • B. Incorrect. The `feature_importances_` attribute is used by tree-based models like `RandomForestClassifier`, `DecisionTreeClassifier`, or `GradientBoostingClassifier`. It is not available in linear models like `LogisticRegression` and will raise an `AttributeError` if accessed.
    • C. Incorrect. While 'weights' is a conceptual term for the parameters, `weights_` is not a valid scikit-learn attribute for the `LogisticRegression` estimator. Scikit-learn uses the `coef_` attribute for coefficients and `intercept_` for the bias term.

    Subdomain 4.5: Feature engineering with PolynomialFeatures, SplineTransformer

    24.By default, `PolynomialFeatures` outputs a dense array in 'C' (row-major) order, but setting `order='F'` changes the output array to Fortran-contiguous (column-major) order, which can be faster for certain downstream linear models.

    1. A.True
    2. B.False
    Show answer & explanation

    Correct answer: ATrue

    • A. The statement is true because scikit-learn's `PolynomialFeatures` includes an `order` parameter (introduced in version 0.24) that defaults to 'C'. Setting this to 'F' results in a Fortran-contiguous array, which is often faster to compute during the transformation phase and can optimize performance for downstream estimators like `Lasso` or `ElasticNet` that utilize coordinate descent and prefer column-major data access.
    • B. The statement is false because `PolynomialFeatures` does indeed support the `order` parameter for dense outputs, and the memory layout (C-contiguous vs. Fortran-contiguous) is a significant factor in the computational efficiency of both the feature generation process and subsequent linear model fitting.

    Subdomain 4.5: Feature engineering with PolynomialFeatures, SplineTransformer

    25.When using `PolynomialFeatures`, if you want to avoid generating the constant feature (a column of 1s) to prevent collinearity with a model's intercept, you must set `_______`.

    1. A.include_bias=False
    2. B.drop_first=True
    3. C.interaction_only=True
    Show answer & explanation

    Correct answer: Ainclude_bias=False

    • A. Correct. `PolynomialFeatures` has an `include_bias` parameter (default `True`) that controls whether a column of ones (the bias/constant term) is produced. Setting `include_bias=False` prevents the generation of that constant column, which is essential to avoid collinearity when the downstream model (like `LinearRegression` with `fit_intercept=True`) handles its own intercept.
    • B. Incorrect. `drop_first=True` is a parameter used by categorical encoders such as `OneHotEncoder` to drop the first category and reduce multicollinearity; it is not a valid parameter for `PolynomialFeatures`.
    • C. Incorrect. `interaction_only=True` restricts the transformer to only produce interaction terms (e.g., $x_1 * x_2$) rather than higher powers of individual features (e.g., $x_1^2$). However, this setting does not affect the presence of the bias/constant column, which is managed strictly by the `include_bias` parameter.

    Subdomain 4.6: Combining features with FeatureUnion

    26.Scenario: You are using `FeatureUnion` to combine three transformers: `T1`, `T2`, and `T3`. After fitting the union, you want to retrieve the feature names of the concatenated output to use as column headers in a report. You call `get_feature_names_out()`. How are the output feature names formatted by default?

    1. A.They are prefixed with the name of the transformer (e.g., `t1__feature1`).
    2. B.They are returned exactly as output by the individual transformers without any prefixes.
    3. C.They are prefixed with the integer index of the transformer (e.g., `0__feature1`).
    4. D.`FeatureUnion` does not support the `get_feature_names_out()` method.
    Show answer & explanation

    Correct answer: AThey are prefixed with the name of the transformer (e.g., `t1__feature1`).

    • A. Correct. By default, FeatureUnion prefixes each feature name with the user-defined name of the transformer followed by a double underscore (e.g., `t1__feature1`). This behavior ensures that the origin of each output column is clear and prevents name collisions if different transformers output features with the same name.
    • B. Incorrect. FeatureUnion adds transformer name prefixes to avoid potential naming conflicts and to provide clarity on which transformer produced which feature in the combined output.
    • C. Incorrect. While transformers are stored in an ordered list, scikit-learn uses the string names provided in the `transformer_list` during initialization as prefixes, not numeric indices.
    • D. Incorrect. FeatureUnion supports the `get_feature_names_out()` method. As long as the constituent transformers implement this method, FeatureUnion will concatenate and return the prefixed feature names.

    Subdomain 4.1: Loading parquet datasets

    27.A practitioner is using a `ColumnTransformer` with `remainder='drop'`. The source parquet file contains 5,000 columns, but the transformers only specify 50 columns to be processed. Loading the full file causes an Out-Of-Memory (OOM) error. What is the most memory-efficient way to load the required data?

    1. A.Load the file using `pd.read_parquet`, then immediately use `df.drop()` to remove the 4,950 unused columns.
    2. B.Pass the list of the 50 required columns to the `columns` argument of `pd.read_parquet`.
    3. C.Use scikit-learn's `SelectKBest` to filter the columns during the loading process.
    4. D.Compress the parquet file using gzip before loading it with `pd.read_parquet`.
    Show answer & explanation

    Correct answer: BPass the list of the 50 required columns to the `columns` argument of `pd.read_parquet`.

    • A. Incorrect. Loading the entire parquet file with pd.read_parquet and then calling df.drop() still requires the system to allocate memory for all 5,000 columns during the initial read. Since the OOM error occurs during the load, this post-load cleanup is never reached and does not solve the memory issue.
    • B. Correct. Parquet is a columnar storage format. By passing the list of 50 required columns to the `columns` argument of `pd.read_parquet`, the underlying engine (such as pyarrow or fastparquet) only reads the specific data blocks for those columns from disk. This drastically reduces the memory footprint and avoids loading the 4,950 unused columns.
    • C. Incorrect. `SelectKBest` is a scikit-learn transformer used for feature selection after data is already loaded into memory. It cannot interface with the I/O layer to filter columns during the loading process, meaning the OOM error would still occur when trying to read the dataset.
    • D. Incorrect. While gzip compression reduces the size of the file on disk, it does not change the memory required to represent the data once it is decompressed and loaded into a DataFrame. Furthermore, Parquet files already use built-in columnar compression; adding external compression does not enable selective column loading.

    Subdomain 4.1: Loading parquet datasets

    28.A parquet file contains a column with timestamp data. Because scikit-learn models cannot natively process datetime objects, what is the standard preprocessing step immediately after loading the parquet file?

    1. A.Extract numerical features (e.g., year, month, day, hour) from the timestamp and drop the original datetime column.
    2. B.Pass the datetime column directly to a RandomForestRegressor, which handles timestamps internally.
    3. C.Use SimpleImputer(strategy='mean') to convert the timestamps into normalized float values.
    4. D.Encode the datetime column using LabelBinarizer to create a sparse matrix of dates.
    Show answer & explanation

    Correct answer: AExtract numerical features (e.g., year, month, day, hour) from the timestamp and drop the original datetime column.

    • A. Correct. Scikit-learn estimators require numeric input arrays. The standard practice is to perform feature engineering by extracting meaningful numeric components (year, month, day, day of week, hour) or cyclical features (sine/cosine transformations) from the datetime object to allow the model to interpret temporal patterns.
    • B. Incorrect. Scikit-learn estimators, including RandomForestRegressor, do not natively support Python datetime objects or NumPy datetime64 dtypes. Attempting to pass them directly will result in a ValueError.
    • C. Incorrect. SimpleImputer is designed to handle missing values (NaNs), not to perform type conversion from datetime to numeric. While one could calculate a mean timestamp, it does not solve the fundamental requirement of providing numeric features to the model.
    • D. Incorrect. LabelBinarizer is a form of one-hot encoding. Using it on raw timestamps would result in an extremely high-dimensional, sparse matrix where the model loses all information regarding the ordinal relationship and cyclical nature of time.

    Subdomain 4.4: Missing values in the target via label propagation

    29.Which statement accurately describes the difference between the LabelPropagation and LabelSpreading estimators in scikit-learn?

    1. A.LabelPropagation uses a normalized graph Laplacian, while LabelSpreading uses an unnormalized one.
    2. B.LabelSpreading minimizes a loss function with regularization (soft clamping), whereas LabelPropagation strictly enforces the original labels (hard clamping).
    3. C.LabelPropagation only supports the 'knn' kernel, while LabelSpreading only supports the 'rbf' kernel.
    4. D.LabelSpreading can handle continuous target variables for regression, while LabelPropagation is strictly for classification.
    Show answer & explanation

    Correct answer: BLabelSpreading minimizes a loss function with regularization (soft clamping), whereas LabelPropagation strictly enforces the original labels (hard clamping).

    • A. Incorrect. The statement is reversed: LabelSpreading is the variant that uses a normalized graph Laplacian, while LabelPropagation follows the formulation based on the unnormalized graph transition matrix.
    • B. Correct. LabelSpreading minimizes a regularized objective function that allows for 'soft clamping' (controlled by the alpha parameter), meaning original labels can change to better fit the manifold structure. LabelPropagation uses 'hard clamping,' where original labels are fixed and cannot change during the propagation process.
    • C. Incorrect. Both estimators in scikit-learn are flexible and support multiple kernel/affinity choices, including 'rbf' and 'knn'.
    • D. Incorrect. Both LabelPropagation and LabelSpreading are designed for semi-supervised classification tasks with discrete labels; neither is intended for continuous target variables in regression.

    Subdomain 4.4: Missing values in the target via label propagation

    30.When dealing with large datasets in scikit-learn's LabelSpreading, which approach is recommended to mitigate memory issues related to the affinity matrix?

    1. A.Use the 'knn' kernel, which internally constructs a memory-efficient sparse affinity matrix.
    2. B.Pass a custom callable to the kernel parameter that returns a sparse matrix.
    3. C.Set memory_efficient=True in the LabelSpreading constructor.
    4. D.Use MiniBatchLabelSpreading to process the graph in chunks.
    5. E.Convert the target array y to a sparse matrix format.
    Show answer & explanation

    Correct answer: BPass a custom callable to the kernel parameter that returns a sparse matrix.

    • A. Incorrect. While the 'knn' kernel option uses a k-neighbors graph, simply selecting this string does not always guarantee that the implementation will maintain a memory-efficient sparse representation throughout all internal matrix operations in the propagation step.
    • B. Correct. The kernel parameter in LabelSpreading can accept a callable function. By providing a custom callable that returns a sparse affinity matrix (for example, using kneighbors_graph), you can ensure the algorithm uses a sparse representation, significantly reducing the memory footprint for large datasets.
    • C. Incorrect. Scikit-learn's LabelSpreading estimator does not have a 'memory_efficient' parameter. Memory management must be handled through kernel selection or pre-computed matrices.
    • D. Incorrect. Scikit-learn does not implement a 'MiniBatchLabelSpreading' class. Semi-supervised algorithms like Label Propagation and Label Spreading are typically batch-oriented and do not support partial_fit or chunked processing.
    • E. Incorrect. The memory bottleneck in LabelSpreading is the N x N affinity matrix calculated from the features (X). Converting the 1D target label array (y) to a sparse format does not resolve the primary memory issue.

    Domain 5: Model selection and validation

    Subdomain 5.1: Cross-validation with group structure and non i.i.d. data

    31.You are implementing a nested cross-validation routine. Applying SMOTE (Synthetic Minority Over-sampling Technique) to the entire dataset before passing it into the outer `cross_val_score` loop is a valid approach that prevents data leakage.

    1. A.True
    2. B.False
    Show answer & explanation

    Correct answer: BFalse

    • A. The statement is false because applying oversampling techniques like SMOTE to the entire dataset before any splitting occurs results in data leakage; synthetic samples are generated using information from observations that will later appear in the validation or test sets, which leads to biased and overly optimistic performance estimates.
    • B. The statement is false because proper validation requires that resampling techniques be applied only to the training portion of each cross-validation fold, typically achieved by using a Pipeline (such as from imbalanced-learn), to ensure that the evaluation set remains completely independent and unseen during the data augmentation process.

    Subdomain 5.3: Stability of optimal hyperparameters via nested cross-validation

    32.You need to evaluate a pipeline containing PCA and a RandomForestClassifier. You want to ensure the performance estimate is unbiased and check if the hyperparameters are stable. Which scikit-learn code structure correctly implements a nested cross-validation?

    1. A.cross_val_score(RandomizedSearchCV(pipe, params, cv=3), X, y, cv=5)
    2. B.RandomizedSearchCV(pipe, params, cv=cross_val_score(X, y, cv=5))
    3. C.GridSearchCV(pipe, params, cv=5).fit(X_train, y_train)
    4. D.cross_validate(pipe, X, y, cv=GridSearchCV(params, cv=3))
    Show answer & explanation

    Correct answer: Across_val_score(RandomizedSearchCV(pipe, params, cv=3), X, y, cv=5)

    • A. Correct. Nested cross-validation is implemented by passing a search estimator (like RandomizedSearchCV or GridSearchCV) as the estimator argument to an outer cross-validation function like cross_val_score or cross_validate. The outer loop (cv=5) provides an unbiased performance estimate, while the inner loop (cv=3) handles hyperparameter optimization within each fold. To specifically check hyperparameter stability, one would use cross_validate with return_estimator=True to access the best_params_ of each inner search.
    • B. Incorrect. This option incorrectly passes the output of cross_val_score (which is a NumPy array of scores) to the cv parameter. The cv parameter expects an integer, a cross-validation generator, or an iterable of splits. This structure is syntactically invalid and does not implement nested CV.
    • C. Incorrect. This code performs standard hyperparameter tuning on a single data split. While GridSearchCV uses cross-validation internally to select parameters, it lacks the outer loop required to provide an unbiased estimate of generalization error or to assess how stable the parameter selection is across different data distributions.
    • D. Incorrect. This structure is invalid because the cv argument in cross_validate must be a cross-validation splitter or an integer, not a search estimator. To implement nested cross-validation, the GridSearchCV object must be the first argument (the estimator) passed to the cross_validate function.

    Subdomain 5.3: Stability of optimal hyperparameters via nested cross-validation

    33.When implementing nested CV manually using a `for` loop over `KFold.split(X)`, you should call the `score` method of the fitted `GridSearchCV` object using the ________ data for that specific outer fold to evaluate performance.

    1. A.test
    2. B.train
    3. C.validation
    Show answer & explanation

    Correct answer: Atest

    • A. Correct. In nested cross-validation, the outer loop is used to estimate the generalization error of the entire model selection process. After GridSearchCV performs inner cross-validation to select hyperparameters and fits the best estimator on the outer training set, it must be evaluated on the independent outer test (held-out) set to provide an unbiased performance estimate.
    • B. Incorrect. Using the outer training data would produce an optimistically biased estimate since the estimator and its hyperparameters were selected and fitted using that same data. Performance measured on training data does not reflect true generalization.
    • C. Incorrect. In the context of nested CV, 'validation' typically refers to the inner CV splits used by GridSearchCV to tune hyperparameters. Those inner results cannot serve as the independent outer-loop evaluation; the manual outer loop specifically designates a 'test' (held-out) set for this purpose.

    Subdomain 5.2: Hyperparameter tuning, GridSearchCV, RandomSearchCV

    34.You are running a GridSearchCV on a pipeline created using make_pipeline(StandardScaler(), PCA(), SVC()). You want to tune the n_components of PCA and the kernel of SVC. What is the correct syntax for the keys in the param_grid dictionary?

    1. A.{'PCA__n_components': [2, 5], 'SVC__kernel': ['linear', 'rbf']}
    2. B.{'pca__n_components': [2, 5], 'svc__kernel': ['linear', 'rbf']}
    3. C.{'n_components': [2, 5], 'kernel': ['linear', 'rbf']}
    4. D.{'Pipeline__pca__n_components': [2, 5], 'Pipeline__svc__kernel': ['linear', 'rbf']}
    Show answer & explanation

    Correct answer: B{'pca__n_components': [2, 5], 'svc__kernel': ['linear', 'rbf']}

    • A. Incorrect. Although the double-underscore syntax is used, make_pipeline automatically names steps using the lowercase class names. Therefore, 'PCA' and 'SVC' are incorrect as they do not match the generated step names 'pca' and 'svc'.
    • B. Correct. When using make_pipeline, scikit-learn automatically assigns step names based on the lowercase version of the estimator's class name (e.g., PCA becomes 'pca', SVC becomes 'svc'). GridSearchCV identifies nested parameters using the syntax <step_name>__<parameter_name>.
    • C. Incorrect. In a scikit-learn Pipeline, parameters must be prefixed with the step name and a double underscore. Using only 'n_components' or 'kernel' would lead to an error as GridSearchCV does not know which step in the pipeline these parameters belong to.
    • D. Incorrect. There is no need to prefix step names with 'Pipeline__'. The correct way to reference a step in a pipeline is simply by the step name itself (the lowercase class name when using make_pipeline).

    Subdomain 5.2: Hyperparameter tuning, GridSearchCV, RandomSearchCV

    35.By default, if the scoring parameter is set to None in GridSearchCV, it will use the estimator's ________ method to evaluate the predictions.

    1. A.score
    2. B.predict
    3. C.evaluate
    Show answer & explanation

    Correct answer: Ascore

    • A. Correct. In scikit-learn, when the 'scoring' parameter is set to None, GridSearchCV defaults to calling the estimator's 'score' method. This method returns a scalar value representing the default evaluation metric—for instance, accuracy for classifiers or the coefficient of determination R² for regressors—which GridSearchCV uses to rank hyperparameter candidates.
    • B. Incorrect. The 'predict' method is used to generate predictions (such as class labels or continuous values) for a given dataset, but it does not calculate a performance metric. GridSearchCV requires a scalar score to evaluate and compare the performance of different hyperparameter configurations.
    • C. Incorrect. There is no standard 'evaluate' method in the scikit-learn estimator API. While other machine learning frameworks like Keras or TensorFlow may use an 'evaluate' method, scikit-learn consistently relies on the 'score' method for default evaluation.

    Want the full experience?

    These are just samples. Practice the full Scikit-learn Professional Practitioner Certification question bank in quiz mode — free, no signup, with domain practice and exam simulation.