CertSafari

    Free Scikit-learn Associate Practitioner Certification Sample Questions

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

    Domain 1: Machine learning concepts

    Subdomain 1.5: The bias / variance trade-off

    1.In the context of the bias-variance decomposition of mean squared error, what does the 'variance' term specifically refer to?

    1. A.The error introduced by approximating a complex real-world problem with a simplified model.
    2. B.The amount by which the model's prediction would change if it were estimated using a different training dataset.
    3. C.The inherent noise in the dataset that cannot be reduced by any machine learning model.
    4. D.The difference between the average prediction of the model and the true target value.
    Show answer & explanation

    Correct answer: BThe amount by which the model's prediction would change if it were estimated using a different training dataset.

    • A. This option describes the bias term. Bias represents the error introduced by approximating a complex real-world relationship with a simplified model, which often leads to underfitting.
    • B. This is the correct definition. Variance measures the model's sensitivity to the specific training set used. It captures how much the model's predictions would fluctuate if it were trained on different samples from the same data-generating process.
    • C. This refers to the irreducible error (often denoted as sigma squared). This is the noise inherent in the data itself that cannot be eliminated regardless of the model chosen.
    • D. This describes the mathematical definition of bias: the difference between the average prediction of our model (across many hypothetical training sets) and the true underlying value.

    Subdomain 1.5: The bias / variance trade-off

    2.You are using a `DecisionTreeRegressor` in scikit-learn and notice from the learning curves that it is severely overfitting the training data. Which hyperparameter adjustment is the most appropriate first step to reduce the model's variance?

    1. A.Increase the max_depth parameter.
    2. B.Decrease the min_samples_split parameter.
    3. C.Decrease the max_depth parameter.
    4. D.Set the max_features parameter to None.
    Show answer & explanation

    Correct answer: CDecrease the max_depth parameter.

    • A. Incorrect. Increasing the max_depth parameter allows the tree to grow deeper and model more complex patterns, which typically increases variance and worsens overfitting rather than reducing it.
    • B. Incorrect. Decreasing the min_samples_split parameter allows the tree to perform splits on nodes with fewer samples, creating a more granular and complex tree. To reduce variance, you would generally increase this parameter to prevent the model from learning noise in small subsets of data.
    • C. Correct. Decreasing the max_depth parameter constrains how deep the tree can grow, effectively limiting its complexity. This is a primary form of regularization for decision trees that helps reduce variance and mitigate overfitting.
    • D. Incorrect. Setting max_features to None is the default behavior, which forces the tree to consider all features for each split. To reduce variance and overfitting, one would typically set this to a smaller subset of features (e.g., 'sqrt' or a float) to introduce randomness and limit the tree's capacity.

    Subdomain 1.1: Types of ML, supervised, unsupervised, semi-supervised

    3.A real estate agency wants to estimate the selling price of houses in a new neighborhood. They have a dataset containing features like square footage, number of bedrooms, and the final selling price of 5,000 houses in a similar neighborhood. What type of machine learning problem is this?

    1. A.Unsupervised clustering
    2. B.Supervised classification
    3. C.Supervised regression
    4. D.Semi-supervised classification
    Show answer & explanation

    Correct answer: CSupervised regression

    • A. Incorrect. Unsupervised clustering is used to group data points without labeled responses. This problem involves predicting a numeric outcome (selling price) based on a labeled dataset where the target is already known for existing houses.
    • B. Incorrect. Supervised classification is used when the target variable is categorical or discrete (e.g., 'spam' vs 'not spam'). In this case, the selling price is a continuous numeric value.
    • C. Correct. This is a supervised regression problem because the goal is to predict a continuous numeric output variable (selling price) based on labeled input features such as square footage and number of bedrooms.
    • D. Incorrect. Semi-supervised classification typically involves a dataset with a mix of many unlabeled examples and a few labeled examples for categorical prediction. This scenario provides a fully labeled dataset and seeks a continuous value prediction, not a discrete label.

    Subdomain 1.3: Key concepts, features, labels, training and test sets

    4.You have trained a decision tree classifier on a dataset of customer purchases. When evaluating the model, you notice it achieves 99% accuracy on the training set but only 62% accuracy on the test set. Which of the following are likely explanations or appropriate next steps?(Select 2)

    1. A.The model is overfitting the training data.
    2. B.The model is underfitting the training data.
    3. C.You should decrease the complexity of the model (e.g., limit tree depth) to improve generalization.
    4. D.You should increase the complexity of the model to capture more patterns in the test set.
    5. E.The test set is likely identical to the training set.
    Show answer & explanation

    Correct answers: A, CThe model is overfitting the training data.; You should decrease the complexity of the model (e.g., limit tree depth) to improve generalization.

    • A. Correct. A very high training accuracy (99%) combined with a significantly lower test accuracy (62%) is a classic sign of overfitting. This means the model has learned noise and specific patterns within the training data that do not generalize to unseen data. Decision trees are particularly prone to this if they are allowed to grow deep without constraints.
    • B. Incorrect. Underfitting occurs when a model is too simple to capture the underlying structure of the data, resulting in low accuracy on both the training and test sets. Since the training accuracy here is very high, underfitting is not the issue.
    • C. Correct. Reducing model complexity is a standard technique to mitigate overfitting and improve generalization. For scikit-learn's DecisionTreeClassifier, this can be achieved by tuning hyperparameters such as max_depth, min_samples_leaf, or min_samples_split to constrain the tree growth.
    • D. Incorrect. Increasing model complexity would likely worsen overfitting. More complexity allows the model to fit the training data even more tightly (memorizing more noise), which typically leads to an even wider gap between training and test performance.
    • E. Incorrect. If the test set were identical to the training set, the performance on the test set would be nearly identical to the training performance (99%). The significant drop to 62% confirms that the test set is different and that the model's performance fails to generalize to it.

    Subdomain 1.3: Key concepts, features, labels, training and test sets

    5.You have a very small dataset consisting of only 150 medical records. You need to evaluate a classification model. Which data splitting strategy is most appropriate to maximize the data used for training while still getting a reliable estimate of model performance?

    1. A.A 50/50 train/test split.
    2. B.A 99/1 train/test split.
    3. C.K-fold cross-validation (e.g., 5-fold or 10-fold).
    4. D.Training and testing on the entire dataset.
    Show answer & explanation

    Correct answer: CK-fold cross-validation (e.g., 5-fold or 10-fold).

    • A. A 50/50 train/test split significantly reduces the amount of data available for training. For a small dataset of 150 records, this leaves only 75 samples for the model to learn from, likely resulting in poor performance and a performance estimate with high variance.
    • B. A 99/1 train/test split uses almost all data for training but leaves an extremely small test set (e.g., 1 or 2 samples for a dataset of 150). This produces an unreliable and high-variance estimate of performance that cannot accurately reflect the model's ability to generalize to new data.
    • C. K-fold cross-validation is the standard approach for small datasets. By partitioning the data into k folds and rotating which fold is used for testing, every data point is used for both training and testing across different iterations. This maximizes training data usage in each fold (e.g., 90% in 10-fold) while providing a stable, averaged performance estimate.
    • D. Training and testing on the same dataset is a major methodological error. It leads to an overoptimistic bias because the model is evaluated on data it has already seen, making it impossible to detect overfitting or measure how the model will perform on unseen data.

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

    6.You are tuning a `KNeighborsClassifier` for a binary classification problem. When setting `n_neighbors=1`, the model has high variance and captures noise. If you set `n_neighbors` equal to the total number of samples in the training dataset, what behavior will the model exhibit?

    1. A.It will perfectly memorize the training data, resulting in 100% training accuracy.
    2. B.It will always predict the majority class of the entire training dataset for any input.
    3. C.It will overfit the training data severely due to the high number of neighbors.
    4. D.It will automatically switch to a linear decision boundary.
    Show answer & explanation

    Correct answer: BIt will always predict the majority class of the entire training dataset for any input.

    • A. Incorrect. Setting n_neighbors equal to the number of training samples does not result in memorization; instead, every prediction is based on the vote of all training points. Unless the dataset consists of only one class, this will not result in 100% training accuracy, as it defaults to the majority label regardless of the local data structure.
    • B. Correct. When k is equal to the total number of training samples (N), the set of nearest neighbors for any query point is the entire training dataset. Therefore, the classifier will always return the most frequent label (the majority class) in the training set, effectively acting as a constant classifier.
    • C. Incorrect. A very large k (like k = N) increases bias and reduces variance, causing extreme underfitting. Overfitting is characterized by high variance and is associated with a very small k (e.g., k = 1), not a k equal to the total dataset size.
    • D. Incorrect. K-Nearest Neighbors is a non-parametric model and does not transform into a parametric linear model. While a constant prediction technically has no complex boundary, the model does not change its underlying algorithm to a linear function.

    Subdomain 1.4: Overfitting and underfitting

    7.You use scikit-learn's `learning_curve` function to plot the training and cross-validation scores of a `LogisticRegression` model as a function of the number of training samples. On the resulting plot, both the training score and the cross-validation score converge to a relatively low value (e.g., 0.55) as the number of samples increases. What does this learning curve indicate?

    1. A.The model is suffering from high variance (overfitting).
    2. B.The model is suffering from high bias (underfitting).
    3. C.The model needs more training data to generalize better.
    4. D.The model is perfectly tuned and generalizing well.
    Show answer & explanation

    Correct answer: BThe model is suffering from high bias (underfitting).

    • A. Incorrect. High variance (overfitting) is characterized by a significant gap between the training score and the cross-validation score. In that scenario, the training score remains high, while the validation score is much lower.
    • B. Correct. When both the training and cross-validation scores converge to a low value as the sample size increases, it indicates high bias (underfitting). This means the model is too simple or constrained to capture the underlying patterns in the data, regardless of how much data is provided.
    • C. Incorrect. If the model primarily needed more data, the cross-validation score would typically still be trending upward as more data is added. Here, the scores have plateaued at a low level, suggesting that the model capacity, not the data volume, is the bottleneck.
    • D. Incorrect. A well-tuned model that generalizes effectively would show both the training and validation scores converging to a high value. Converging to a low performance value (near chance) indicates poor predictive utility.

    Subdomain 1.4: Overfitting and underfitting

    8.You are working with a dataset containing 500 samples and 10,000 features (e.g., gene expression data). You train a `LogisticRegression` model, but it severely overfits due to the curse of dimensionality. Besides applying L1 regularization, which scikit-learn preprocessing step is most appropriate to reduce overfitting in this scenario?

    1. A.Apply `PolynomialFeatures` to capture interactions between the genes.
    2. B.Use `PCA` (Principal Component Analysis) to reduce the dimensionality of the feature space before training.
    3. C.Apply `MinMaxScaler` to ensure all features are between 0 and 1.
    4. D.Use `SMOTE` to generate synthetic samples for the minority class.
    Show answer & explanation

    Correct answer: BUse `PCA` (Principal Component Analysis) to reduce the dimensionality of the feature space before training.

    • A. Incorrect. Applying `PolynomialFeatures` expands the feature space by creating interaction and higher-order terms. When the number of features (10,000) already far exceeds the number of samples (500), this would severely exacerbate the curse of dimensionality and increase overfitting.
    • B. Correct. PCA (Principal Component Analysis) reduces dimensionality by projecting the data onto a smaller number of principal components that capture the maximum variance. In high-dimensional settings where p >> n, reducing the feature count via PCA helps mitigate overfitting and reduces noise while retaining the most significant underlying patterns.
    • C. Incorrect. `MinMaxScaler` rescales features to a common range, which can help optimization algorithms (like gradient descent) converge and ensures regularization is applied fairly across features. However, it does not reduce the number of features or directly solve the overfitting problem caused by the curse of dimensionality.
    • D. Incorrect. `SMOTE` is designed to address class imbalance by generating synthetic samples for the minority class. It does not reduce feature dimensionality and is not a technique intended to fix overfitting caused by having too many features relative to the number of samples.

    Domain 2: Model building and evaluation

    Subdomain 2.1: Splitting datasets with train_test_split

    9.Which of the following data structures are valid inputs that can be passed to train_test_split to be split?(Select 3)

    1. A.Standard Python lists
    2. B.pandas DataFrames
    3. C.scipy sparse matrices
    4. D.Python set objects
    5. E.Generator expressions
    Show answer & explanation

    Correct answers: A, B, CStandard Python lists; pandas DataFrames; scipy sparse matrices

    • A. Standard Python lists are valid inputs for train_test_split. These are treated as array-like structures that are indexable and have a defined length, allowing the function to compute consistent and repeatable splits.
    • B. pandas DataFrames and Series objects are fully supported by train_test_split. The function preserves the array-like behavior and often maintains the original indices and column names in the returned subsets.
    • C. SciPy sparse matrices (such as CSR or CSC formats) are valid inputs. The function can split sparse matrix inputs and will return the resulting splits in a compatible sparse format, which is essential for memory efficiency in large datasets.
    • D. Python set objects are not valid inputs because they are unordered and do not support indexing. train_test_split requires sequence-like objects with a consistent order to ensure that features (X) and labels (y) remain aligned.
    • E. Generator expressions are iterators that do not have a defined length and are consumed upon iteration. Because train_test_split needs to determine the size of the dataset and perform indexing to shuffle/split data, generators are not supported.

    Subdomain 2.4: Evaluating with accuracy, precision, recall, F1, MSE, R squared

    10.You run `confusion_matrix(y_true, y_pred)` for a binary classification problem and receive the following output array: [[45, 5], [10, 40]] Assuming the default scikit-learn layout, how many False Positives did the model produce?

    1. A.45
    2. B.5
    3. C.10
    4. D.40
    Show answer & explanation

    Correct answer: B5

    • A. Incorrect. In the scikit-learn default confusion matrix layout, the value at index [0, 0] represents True Negatives (TN), which are instances correctly predicted as the negative class (0).
    • B. Correct. In scikit-learn, the confusion matrix follows the layout [[TN, FP], [FN, TP]]. The value at position [0, 1] corresponds to False Positives (FP), which occurs when the true label is 0 (Negative) but the model predicted 1 (Positive).
    • C. Incorrect. In the default layout, the value at position [1, 0] represents False Negatives (FN), which are positive instances incorrectly predicted as negative.
    • D. Incorrect. In the default layout, the value at position [1, 1] represents True Positives (TP), which are instances correctly predicted as the positive class (1).

    Subdomain 2.2: Training models with fit()

    11.According to scikit-learn API conventions, how are attributes that are estimated from the data during the `fit` method named?

    1. A.They are prefixed with an underscore (e.g., `_coef`).
    2. B.They are suffixed with an underscore (e.g., `coef_`).
    3. C.They are capitalized (e.g., `Coef`).
    4. D.They are stored in a `learned_params_` dictionary.
    Show answer & explanation

    Correct answer: BThey are suffixed with an underscore (e.g., `coef_`).

    • A. Incorrect. In scikit-learn, a leading underscore (e.g., `_coef`) is typically reserved for private or internal attributes and methods, following general Python conventions. It is not used for public attributes estimated during the fitting process.
    • B. Correct. The scikit-learn API convention dictates that attributes estimated from the data during the `fit` method must be suffixed with a single trailing underscore (e.g., `coef_`, `intercept_`, `mean_`, `classes_`). This convention helps users distinguish between hyperparameters (set in the constructor) and learned parameters (calculated during fit).
    • C. Incorrect. Capitalization is not part of scikit-learn's convention for designating estimated attributes. Scikit-learn adheres to PEP 8 standards where attribute names are lowercase with underscores.
    • D. Incorrect. Scikit-learn does not store estimated parameters in a dedicated dictionary like `learned_params_`. Instead, learned attributes are assigned individually to the estimator instance with the trailing underscore suffix.

    Subdomain 2.3: Predicting with predict()

    12.You are building a fraud detection system using a `RandomForestClassifier`. For the final application, you need to output the definitive 'Fraud' or 'Not Fraud' label, as well as the model's confidence score (probability) for the 'Fraud' class to rank the alerts. Which two methods must you call on your fitted model to obtain these specific outputs for a new dataset `X_test`?(Select 2)

    1. A.predict(X_test)
    2. B.decision_function(X_test)
    3. C.predict_proba(X_test)
    4. D.transform(X_test)
    5. E.score(X_test)
    Show answer & explanation

    Correct answers: A, Cpredict(X_test); predict_proba(X_test)

    • A. The predict(X_test) method is the standard scikit-learn API for obtaining the definitive class labels (e.g., 'Fraud' or 'Not Fraud'). It returns the label of the class with the highest predicted probability for each sample.
    • B. The decision_function(X_test) method is not implemented for RandomForestClassifier. While it is used in models like SVM or SGDClassifier to return signed distances to a decision boundary, it does not provide the probability scores required for this specific application.
    • C. The predict_proba(X_test) method returns the class probability estimates for each sample. This provides the 'confidence scores' needed to rank alerts; for a RandomForestClassifier, these probabilities are calculated as the mean predicted class probabilities of the individual trees in the forest.
    • D. The transform(X_test) method is used by transformers (like PCA or StandardScaler) or feature selectors to modify the input data. It is not used by classifiers to output predictions or confidence scores.
    • E. The score(X_test, y_test) method returns the mean accuracy for the given test data. It requires the true labels (y_test) and returns a single aggregate scalar rather than the per-sample labels or probabilities needed for a final application.

    Subdomain 2.3: Predicting with predict()

    13.You are evaluating a binary classification model (`LogisticRegression`). By default, `model.predict(X_test)` uses a threshold of 0.5 to determine the class labels. You want to increase the recall of the positive class by lowering the decision threshold to 0.3. How can you achieve this using scikit-learn?(Select 2)

    1. A.Pass the argument `threshold=0.3` directly to the predict() method: `model.predict(X_test, threshold=0.3)`.
    2. B.Extract the probabilities for the positive class using `model.predict_proba(X_test)[:, 1]`, and manually apply the condition `>= 0.3`.
    3. C.Scikit-learn's predict() method does not natively accept a threshold parameter for classification models.
    4. D.Modify the `class_weight` parameter of the fitted model directly before calling predict().
    5. E.Use `model.decision_function(X_test) >= 0.3` to get the exact same result as lowering the probability threshold to 0.3.
    Show answer & explanation

    Correct answers: B, CExtract the probabilities for the positive class using `model.predict_proba(X_test)[:, 1]`, and manually apply the condition `>= 0.3`.; Scikit-learn's predict() method does not natively accept a threshold parameter for classification models.

    • A. Incorrect. Scikit-learn's `predict()` method does not accept a `threshold` parameter. Attempting to pass one will result in a TypeError. Custom thresholding must be performed manually using the output of score-based methods.
    • B. Correct. This is the standard procedure in scikit-learn to implement a custom threshold. `predict_proba(X_test)[:, 1]` retrieves the estimated probability of the positive class, which can then be compared against the desired threshold (0.3) to generate binary labels.
    • C. Correct. In scikit-learn classifiers, the `predict()` method uses a hardcoded internal decision rule (typically a 0.5 probability threshold for binary classification). To use a different threshold, the user must manually compute it from probabilities or decision scores.
    • D. Incorrect. The `class_weight` parameter is used during the training phase (the `fit()` method) to penalize misclassifications differently. Changing this parameter on a model that has already been fitted does not modify the existing decision boundary or the behavior of the `predict()` method.
    • E. Incorrect. `decision_function` returns raw scores, such as the signed distance to the hyperplane (SVM) or log-odds (Logistic Regression). These are on a different scale than probabilities (0 to 1). A probability threshold of 0.3 does not equal a decision score of 0.3; for instance, in Logistic Regression, the probability 0.5 maps to a decision score of 0.

    Subdomain 2.5: Interpreting score against a dummy baseline

    14.You are working on a multi-class classification problem with classes A, B, and C distributed as 50%, 30%, and 20% respectively in the training data. You fit a DummyClassifier(strategy='stratified'). How will this dummy model generate predictions for the test set?

    1. A.It will always predict class A for every sample.
    2. B.It will predict A, B, and C with equal probability (33.3% each).
    3. C.It will randomly predict A 50% of the time, B 30% of the time, and C 20% of the time.
    4. D.It will predict the class that maximizes the F1-score based on the test set distribution.
    Show answer & explanation

    Correct answer: CIt will randomly predict A 50% of the time, B 30% of the time, and C 20% of the time.

    • A. Incorrect. Always predicting the majority class (class A) is the behavior of the 'most_frequent' strategy. The 'stratified' strategy instead generates predictions by sampling based on the class priors.
    • B. Incorrect. Predicting classes with equal probability (33.3% each) regardless of the training data distribution is the behavior of the 'uniform' strategy.
    • C. Correct. The 'stratified' strategy in scikit-learn's DummyClassifier generates predictions by randomly sampling the class labels according to the empirical distribution (priors) found in the training data. Since the training data contains 50% A, 30% B, and 20% C, the model will produce predictions following those exact proportions.
    • D. Incorrect. The DummyClassifier does not use test set distribution to make decisions, nor does it perform optimization for metrics like F1-score. It follows simple rules based on the training set distribution or constant values.

    Subdomain 2.5: Interpreting score against a dummy baseline

    15.Which scikit-learn evaluation metric inherently represents a comparison against a DummyRegressor using the 'mean' strategy?

    1. A.Mean Absolute Error (MAE)
    2. B.Mean Squared Error (MSE)
    3. C.R-squared (R2) score
    4. D.Explained Variance Score
    Show answer & explanation

    Correct answer: CR-squared (R2) score

    • A. Mean Absolute Error (MAE) measures the average absolute difference between predicted and actual values. While it can be calculated for a dummy model, the metric itself is an absolute value and does not inherently encode a comparison to a baseline model.
    • B. Mean Squared Error (MSE) measures the average squared difference between predicted and actual values. Although the MSE of a mean-predicting model is equal to the variance of the target, MSE is an absolute metric and is not normalized against a dummy baseline by definition.
    • C. R-squared (R2) is defined as 1 - (SS_res / SS_tot), where SS_tot is the sum of squared deviations from the mean. This denominator represents the error of a DummyRegressor using the 'mean' strategy. Therefore, R2 inherently measures how much better (or worse) the model is compared to a mean-only baseline. An R2 of 0 indicates performance equal to that dummy model.
    • D. The Explained Variance Score is similar to R2 as it measures the proportion of variance explained by the model. However, it uses the variance of the residuals rather than the sum of squared errors and does not account for systematic offsets (bias) in the same way R2 does, making R2 the standard metric for direct dummy comparison.

    Domain 3: Interpretation and communication

    Subdomain 3.4: Reporting uncertainty without hand-waving

    16.When reporting uncertainty in model evaluation, practitioners often use cross-validation or bootstrapping. Which of the following statements are true regarding these techniques in the context of scikit-learn?(Select 2)

    1. A.cross_val_score provides an array of scores that can be used to calculate the standard deviation of the model's performance across folds.
    2. B.sklearn.utils.resample can be used to generate bootstrap samples to estimate the confidence interval of a specific metric.
    3. C.cross_val_score automatically returns the 95% confidence interval of the scoring metric as a tuple.
    4. D.Bootstrapping in scikit-learn is exclusively performed using the BootstrapCV class.
    5. E.cross_validate only supports a single scoring metric, limiting uncertainty analysis to accuracy.
    Show answer & explanation

    Correct answers: A, Bcross_val_score provides an array of scores that can be used to calculate the standard deviation of the model's performance across folds.; sklearn.utils.resample can be used to generate bootstrap samples to estimate the confidence interval of a specific metric.

    • A. Correct. cross_val_score returns a NumPy array containing the score for each cross-validation fold. This distribution of scores allows practitioners to calculate the mean and standard deviation, providing a measure of the variability and stability of the model performance.
    • B. Correct. While scikit-learn does not have a dedicated 'Bootstrap' class in model_selection, sklearn.utils.resample is the standard tool for generating resampled datasets with replacement. This allows users to manually implement bootstrapping to derive empirical distributions and confidence intervals for any metric.
    • C. Incorrect. cross_val_score returns an array of scores for each split. It does not perform statistical inference (like calculating 95% confidence intervals) automatically; the user must compute these statistics from the returned array.
    • D. Incorrect. There is no BootstrapCV class in the official scikit-learn API. Bootstrapping is typically achieved using sklearn.utils.resample or by using ShuffleSplit for repeated random sub-sampling.
    • E. Incorrect. The cross_validate function is specifically designed to support multiple scoring metrics simultaneously. This allows for a more comprehensive analysis of uncertainty across various performance dimensions compared to cross_val_score.

    Subdomain 3.2: Reading a confusion matrix and an ROC curve

    17.Which of the following function calls will successfully compute the multi-class ROC AUC score?(Select 2)

    1. A.`roc_auc_score(y_test, y_proba, multi_class='ovr')`
    2. B.`roc_auc_score(y_test, y_proba, multi_class='ovo')`
    3. C.`roc_auc_score(y_test, y_proba)`
    4. D.`roc_auc_score(y_test, np.argmax(y_proba, axis=1), multi_class='ovr')`
    5. E.`roc_auc_score(y_test, y_proba, average='binary')`
    Show answer & explanation

    Correct answers: A, B`roc_auc_score(y_test, y_proba, multi_class='ovr')`; `roc_auc_score(y_test, y_proba, multi_class='ovo')`

    • A. Correct. `roc_auc_score` supports multiclass AUC when `multi_class='ovr'` (One-vs-Rest) is specified. This approach requires `y_proba` to contain class probability estimates for each class.
    • B. Correct. `roc_auc_score` supports multiclass AUC when `multi_class='ovo'` (One-vs-One) is specified. This method computes the average of pairwise ROC AUCs for all possible combinations of classes.
    • C. Incorrect. Without specifying the `multi_class` parameter, `roc_auc_score` will not successfully handle multiclass probability arrays and will typically raise an error because the default behavior is intended for binary classification.
    • D. Incorrect. `np.argmax(y_proba, axis=1)` produces discrete class labels (hard predictions). ROC AUC score requires continuous probability scores or decision values for each class to evaluate different thresholds.
    • E. Incorrect. `average='binary'` is only applicable to binary classification tasks. For multiclass scenarios, you must use a multiclass strategy ('ovr' or 'ovo') and an appropriate averaging method like 'macro' or 'weighted'.

    Subdomain 3.2: Reading a confusion matrix and an ROC curve

    18.Which of the following approaches are valid and will successfully produce the plot?(Select 2)

    1. A.`RocCurveDisplay.from_estimator(svc, X_test, y_test)`
    2. B.`y_score = svc.decision_function(X_test)` followed by `RocCurveDisplay.from_predictions(y_test, y_score)`
    3. C.`RocCurveDisplay.plot(svc, X_test, y_test)`
    4. D.`roc_curve(svc, X_test, y_test).plot()`
    5. E.`RocCurveDisplay.from_estimator(y_test, svc.predict(X_test))`
    Show answer & explanation

    Correct answers: A, B`RocCurveDisplay.from_estimator(svc, X_test, y_test)`; `y_score = svc.decision_function(X_test)` followed by `RocCurveDisplay.from_predictions(y_test, y_score)`

    • A. Correct. `RocCurveDisplay.from_estimator` is the standard scikit-learn API to create an ROC curve plot directly from a fitted estimator, feature matrix, and true labels. It automatically handles score computation internally.
    • B. Correct. `RocCurveDisplay.from_predictions` accepts ground truth labels and score-like continuous values. Since `svc.decision_function(X_test)` provides these scores, this is a valid manual two-step approach.
    • C. Incorrect. While `RocCurveDisplay` has a `.plot()` method, it is an instance method used to render an already-created display object. It cannot be called as a class method with these arguments.
    • D. Incorrect. The `roc_curve` function computes the FPR and TPR and returns NumPy arrays. It does not return a display object and does not have a `.plot()` method.
    • E. Incorrect. The signature for `from_estimator` requires the estimator first, then features (X), then labels (y). Furthermore, `svc.predict` returns discrete class labels, which are insufficient for a standard ROC curve that requires continuous scores or probabilities.

    Domain 3: Interpretation of results & communication

    Subdomain 3.3: Explaining performance to non-technical stakeholders

    19.Why is it important to communicate a 'baseline' model's performance (such as scikit-learn's `DummyClassifier`) to business stakeholders?

    1. A.To show the maximum possible accuracy the data can achieve.
    2. B.To demonstrate the computational efficiency of the machine learning pipeline.
    3. C.To provide a reference point showing how much value the complex model adds over a simple, naive guess.
    4. D.To prove that the underlying data is normally distributed.
    Show answer & explanation

    Correct answer: CTo provide a reference point showing how much value the complex model adds over a simple, naive guess.

    • A. Incorrect. A baseline model (like a DummyClassifier) represents a naive level of performance, acting as a lower bound or starting point. It does not indicate the theoretical maximum or upper limit of accuracy for the dataset.
    • B. Incorrect. While baseline models are often computationally inexpensive, their primary purpose in stakeholder communication is to provide context for performance metrics rather than to demonstrate the speed of the pipeline.
    • C. Correct. A baseline model provides a crucial benchmark to show the 'lift' or incremental value added by a more sophisticated model. This helps stakeholders understand whether the complexity, cost, and risk associated with a complex model are justified compared to a simple, rule-based approach (like always predicting the most frequent class).
    • D. Incorrect. A baseline model is used for performance comparison and does not serve as a tool for statistical hypothesis testing regarding the distribution of the underlying data.

    Subdomain 3.1: Visualizing results with matplotlib and seaborn

    20.While scikit-learn provides built-in display classes, practitioners often use seaborn and matplotlib for custom visualizations. Which of the following statements accurately describe the relationship between these libraries when visualizing scikit-learn results?(Select 2)

    1. A.Scikit-learn's Display classes (like `RocCurveDisplay`) return objects that contain a matplotlib `ax_` attribute, allowing further customization.
    2. B.Seaborn functions like `sns.scatterplot` can directly accept scikit-learn estimator objects as the `data` parameter.
    3. C.Scikit-learn's built-in plotting functions are built on top of matplotlib.
    4. D.Matplotlib must be uninstalled to use scikit-learn's Display API.
    Show answer & explanation

    Correct answers: A, CScikit-learn's Display classes (like `RocCurveDisplay`) return objects that contain a matplotlib `ax_` attribute, allowing further customization.; Scikit-learn's built-in plotting functions are built on top of matplotlib.

    • A. Scikit-learn's Display classes (e.g., RocCurveDisplay, PrecisionRecallDisplay, ConfusionMatrixDisplay) return an object that stores the matplotlib Axes used in the `ax_` attribute. This allows users to apply additional matplotlib customizations, such as setting titles or adjusting axes, after the display has been created.
    • B. Seaborn functions expect data structures like Pandas DataFrames, NumPy arrays, or lists. They do not accept scikit-learn estimator objects (the models themselves) as the data source; model outputs like predictions or residuals must be extracted into compatible arrays first.
    • C. Scikit-learn's visualization API is designed as a high-level wrapper around matplotlib. Because it is built on top of matplotlib, the resulting plots are standard matplotlib figures and axes, making them fully compatible with the broader matplotlib ecosystem for fine-tuning.
    • D. Matplotlib is a core dependency for scikit-learn's plotting and display utilities. Far from needing to be uninstalled, it must be installed for these functions to work, as they rely on matplotlib's rendering engine.

    Domain 4: Data preprocessing

    Subdomain 4.5: Feature scaling, StandardScaler, MinMaxScaler

    21.Which of the following statements are true regarding StandardScaler in scikit-learn?(Select 2)

    1. A.It scales each feature to have a minimum of 0 and a maximum of 1.
    2. B.It centers the data by removing the mean and scales it to unit variance.
    3. C.It is highly robust to the presence of extreme outliers.
    4. D.Its transformation is calculated independently for each feature.
    5. E.It scales individual samples to have unit norm.
    Show answer & explanation

    Correct answers: B, DIt centers the data by removing the mean and scales it to unit variance.; Its transformation is calculated independently for each feature.

    • A. Incorrect. This describes MinMaxScaler, which scales features to a specific range (typically [0, 1]). StandardScaler centers features around mean 0 and scales to unit variance but does not enforce specific min/max bounds.
    • B. Correct. The core function of StandardScaler is to standardize features by removing the mean and scaling to unit variance (z-score normalization). This results in features with approximately zero mean and unit variance.
    • C. Incorrect. StandardScaler is sensitive to outliers because outliers significantly skew the calculation of the mean and standard deviation. RobustScaler (which uses the median and interquartile range) is preferred when outliers are present.
    • D. Correct. StandardScaler computes its statistics (mean and variance) and applies the transformation independently for each feature (column), meaning each variable is standardized based on its own distribution.
    • E. Incorrect. Scaling individual samples (rows) to have a unit norm is the behavior of the Normalizer transformer. StandardScaler standardizes features (columns) across all samples.

    Subdomain 4.5: Feature scaling, StandardScaler, MinMaxScaler

    22.You are building a machine learning pipeline. You split your data into X_train and X_test. You apply StandardScaler to your data. To prevent data leakage, what is the correct sequence of method calls?

    1. A.Call fit_transform on X_train, and fit_transform on X_test.
    2. B.Call fit on the entire dataset X, then transform on X_train and X_test.
    3. C.Call fit_transform on X_train, and transform on X_test.
    4. D.Call transform on X_train, and fit_transform on X_test.
    Show answer & explanation

    Correct answer: CCall fit_transform on X_train, and transform on X_test.

    • A. Incorrect. Calling fit_transform on both X_train and X_test is a mistake because it computes different scaling parameters (mean and standard deviation) for each set independently. The test set should never be used to fit the scaler, as it would influence the preprocessing step with information the model shouldn't have.
    • B. Incorrect. Fitting the scaler on the entire dataset X (before the split or by combining sets) results in data leakage. The scaler would incorporate the mean and variance of the test data into the training process, providing the model with information about the distribution of unseen data.
    • C. Correct. This is the standard procedure to prevent data leakage. fit_transform on X_train calculates the parameters (mean/std) based only on the training data and applies them. Then, transform on X_test uses those same training-derived parameters to scale the test data, ensuring the test set remains truly unseen during the fitting process.
    • D. Incorrect. Calling transform on X_train without first fitting the scaler will result in an error (NotFittedError) because the scaler has no parameters yet. Additionally, using fit_transform on the test set would leak test-set information.

    Subdomain 4.4: Imputation with SimpleImputer

    23.What is the default imputation strategy used by `SimpleImputer` if the `strategy` parameter is not explicitly specified during initialization?

    1. A.'mean'
    2. B.'median'
    3. C.'most_frequent'
    4. D.'constant'
    Show answer & explanation

    Correct answer: A'mean'

    • A. Correct. The default strategy for `sklearn.impute.SimpleImputer` is 'mean'. This strategy calculates the mean (average) of the non-missing values in each column and replaces the missing values with that result. This strategy is only applicable to numerical data types.
    • B. Incorrect. While 'median' is a valid strategy that can be more robust to outliers for numeric features, it is not the default behavior of `SimpleImputer`. It must be explicitly set using `strategy='median'`.
    • C. Incorrect. The 'most_frequent' strategy replaces missing values with the most common value (mode) in each column. This is often used for categorical data, but it is not the default setting.
    • D. Incorrect. The 'constant' strategy replaces missing values with a fixed value (defined by the `fill_value` parameter). While useful for filling specific constants or placeholders like 'missing_value', it is not the default strategy.

    Subdomain 4.4: Imputation with SimpleImputer

    24.After fitting a `SimpleImputer` with `strategy='mean'` on a training dataset with 5 numeric features, you want to inspect the actual mean values that the imputer learned and will use for the test set. Which attribute of the fitted `SimpleImputer` object contains these values?

    1. A.means_
    2. B.statistics_
    3. C.imputed_values_
    4. D.fill_values_
    Show answer & explanation

    Correct answer: Bstatistics_

    • A. Incorrect. The `SimpleImputer` class does not have an attribute called `means_`. While other scikit-learn objects like `StandardScaler` use `mean_` (singular), `SimpleImputer` uses a consistent generic name for all imputation strategies.
    • B. Correct. The `statistics_` attribute stores the values learned during the `fit` process. Whether the strategy is 'mean', 'median', or 'most_frequent', the resulting values used for imputation are always stored in this array.
    • C. Incorrect. `imputed_values_` is not a valid attribute in the scikit-learn API. The imputer provides the per-feature learned values via `statistics_`, rather than exposing the results under this name.
    • D. Incorrect. While `fill_value` is a parameter used when `strategy='constant'`, the resulting attribute after fitting is still `statistics_`. There is no attribute named `fill_values_` on the `SimpleImputer` object.

    Subdomain 4.1: Loading parquet datasets

    25.Which library does scikit-learn natively use to read Parquet files directly via a built-in `sklearn.datasets.read_parquet` function?

    1. A.pyarrow
    2. B.fastparquet
    3. C.pandas
    4. D.Scikit-learn does not have a built-in function for reading Parquet files; external libraries must be used.
    Show answer & explanation

    Correct answer: DScikit-learn does not have a built-in function for reading Parquet files; external libraries must be used.

    • A. Incorrect. While pyarrow is a widely used engine for Parquet files, scikit-learn does not provide a native `sklearn.datasets.read_parquet` function that utilizes it.
    • B. Incorrect. fastparquet is an alternative library for reading Parquet data, but scikit-learn does not include a built-in module or function to interface with it for file loading.
    • C. Incorrect. Pandas is the industry standard for reading Parquet files into DataFrames using `pd.read_parquet()`, but scikit-learn does not wrap this functionality or ship its own equivalent function in the `sklearn.datasets` module.
    • D. Correct. Scikit-learn does not have a built-in `read_parquet` function. It is designed to work with data that has already been loaded into memory (e.g., as NumPy arrays or Pandas DataFrames) using external libraries like pandas, pyarrow, or fastparquet.

    Subdomain 4.2: Scatterplots and boxplots for first look

    26.In a standard boxplot used during exploratory data analysis, what does the interquartile range (IQR) visually represent?

    1. A.The distance between the minimum and maximum values of the dataset, excluding outliers.
    2. B.The range containing the middle 50% of the data points.
    3. C.The standard deviation of the feature centered around the mean.
    4. D.The 95% confidence interval of the median.
    Show answer & explanation

    Correct answer: BThe range containing the middle 50% of the data points.

    • A. Incorrect. The distance between the minimum and maximum values (excluding outliers) is typically represented by the whiskers in a boxplot. The IQR specifically measures the distance between the first and third quartiles, not the full range of the data.
    • B. Correct. The interquartile range (IQR) is defined as the distance between the first quartile (Q1) and the third quartile (Q3). In a boxplot, this is visually represented by the 'box' itself, which contains the middle 50% of the dataset's observations.
    • C. Incorrect. IQR is a robust, quantile-based measure of spread, whereas standard deviation measures average deviation around the mean. Boxplots are built using medians and quartiles, making them less sensitive to outliers than mean-based metrics.
    • D. Incorrect. The IQR describes the observed spread of the central distribution, not a statistical confidence interval. While some boxplot variations include 'notches' to represent a confidence interval for the median, the box itself always represents the IQR.

    Subdomain 4.6: Encoding with OrdinalEncoder, OneHotEncoder

    27.Your training dataset has a 'Color' feature with values ['Red', 'Green', 'Blue']. During production, the model might encounter the value 'Yellow'. You want the encoder to produce an all-zero array for 'Yellow' without raising an error. How should you initialize `OneHotEncoder`?

    1. A.OneHotEncoder(handle_unknown='ignore')
    2. B.OneHotEncoder(handle_unknown='error')
    3. C.OneHotEncoder(unknown_value=0)
    4. D.OneHotEncoder(drop='first')
    Show answer & explanation

    Correct answer: AOneHotEncoder(handle_unknown='ignore')

    • A. Correct. Setting handle_unknown='ignore' ensures that categories not seen during the fit method (like 'Yellow') will result in an all-zero row in the transformed output instead of raising a ValueError. This maintains the same number of output columns as learned during training.
    • B. Incorrect. handle_unknown='error' is the default behavior of OneHotEncoder. It will raise a ValueError when it encounters an unknown category like 'Yellow' during transformation, which does not meet the requirement.
    • C. Incorrect. OneHotEncoder does not have an unknown_value parameter. This parameter is used in OrdinalEncoder to specify the value assigned to unknown categories.
    • D. Incorrect. The drop='first' parameter is used to remove the first category of each feature to avoid multicollinearity (the dummy variable trap). It does not handle unknown categories and will still result in an error if an unseen value is encountered unless handle_unknown='ignore' is also specified.

    Subdomain 4.2: Scatterplots and boxplots for first look

    28.When using a scatterplot matrix (e.g., `pandas.plotting.scatter_matrix` or `seaborn.pairplot`) for exploratory data analysis, what is typically displayed on the diagonal axes?

    1. A.Scatterplots of a feature against itself.
    2. B.The Pearson correlation coefficients between features.
    3. C.The univariate distribution of each feature (e.g., histograms or KDE plots).
    4. D.Boxplots showing the outliers of each feature.
    Show answer & explanation

    Correct answer: CThe univariate distribution of each feature (e.g., histograms or KDE plots).

    • A. Plotting a feature against itself as a scatterplot would simply result in a straight line (the identity line), which provides no useful insight. Most plotting libraries replace this redundant visualization with univariate summaries.
    • B. Pearson correlation coefficients are numerical summaries typically presented in a correlation matrix or heatmap. While they describe the relationship between features, they are not the standard graphical element placed on the diagonal of a scatterplot matrix.
    • C. The diagonal axes are used to display the marginal (univariate) distribution of each variable. This allows the user to observe the frequency, range, skewness, and modality of individual features using histograms or Kernel Density Estimate (KDE) plots.
    • D. While boxplots are useful for identifying outliers and understanding the spread of data, they are not the default choice for the diagonal of a scatterplot matrix. Histograms and KDE plots are the industry standard as they provide more detail about the density of the distribution.

    Subdomain 4.3: Spotting wrongly-encoded columns (float as string, etc.)

    29.You load a CSV into a pandas DataFrame `df`. The 'price' column contains values like '12.50' and '9.99' but was loaded as an object dtype. You pass `df[['price']]` directly to `StandardScaler().fit()`. What happens?

    1. A.It scales the strings based on their ASCII values.
    2. B.It raises a ValueError because it cannot convert the strings to floats.
    3. C.It automatically parses the strings to floats and scales them.
    4. D.It ignores the column and returns an empty array.
    Show answer & explanation

    Correct answer: BIt raises a ValueError because it cannot convert the strings to floats.

    • A. StandardScaler is designed for numerical data scaling and does not operate on character codes or ASCII values. It requires numeric inputs to calculate the mean and standard deviation.
    • B. Scikit-learn estimators perform data validation using `check_array`, which attempts to convert the input into a numeric NumPy array (usually float64). If the column has an 'object' dtype containing Python strings, this conversion fails and raises a ValueError. You must ensure data is numeric (e.g., using `pd.to_numeric` or `.astype(float)`) before fitting.
    • C. StandardScaler does not automatically parse strings or perform implicit type coercion for the user. Ensuring that the data types are correct is a prerequisite step in the preprocessing pipeline.
    • D. StandardScaler validates all provided input features. It will not silently ignore or drop non-numeric columns; instead, it will raise an error if any part of the input is incompatible with numeric processing.

    Subdomain 4.3: Spotting wrongly-encoded columns (float as string, etc.)

    30.What specific exception does scikit-learn typically raise if you attempt to fit a model (like LinearRegression) on a feature matrix X that contains a column of numeric values wrongly encoded as strings (e.g., '3.14')?

    1. A.TypeError: unhashable type: 'numpy.ndarray'
    2. B.ValueError: could not convert string to float
    3. C.KeyError: 'Column not found'
    4. D.NotFittedError: Estimator not fitted
    Show answer & explanation

    Correct answer: BValueError: could not convert string to float

    • A. This exception occurs when trying to use a mutable object like a numpy array as a hashable key in a dictionary or set; it is unrelated to data type conversion during the model fitting process.
    • B. Correct. Scikit-learn estimators internally use validation functions like `check_array` to ensure inputs are numeric. If the input contains strings or is an object-type array that cannot be converted to the required floating-point type, a ValueError is raised with the message 'could not convert string to float'.
    • C. A KeyError is typically raised when attempting to access a missing column in a pandas DataFrame or a missing key in a dictionary. It does not reflect issues with the data types contained within existing columns.
    • D. The NotFittedError is a scikit-learn specific exception raised when calling methods that require a trained model (such as predict or transform) before fit has been executed. It is not triggered by data validation issues during the fitting phase itself.

    Subdomain 4.7: Combining steps with ColumnTransformer

    31.After fitting a `ColumnTransformer`, which attribute should you use to access a specific fitted transformer by its given name?

    1. A.transformers_
    2. B.named_transformers_
    3. C.fitted_steps_
    4. D.get_params()
    Show answer & explanation

    Correct answer: Bnamed_transformers_

    • A. Incorrect. The `transformers_` attribute is a list of (name, transformer, columns) tuples created after fitting. Because it is a list and not a name-keyed mapping, it is not the intended API for direct, efficient lookup by name.
    • B. Correct. The `named_transformers_` attribute is a dictionary-like (Bunch) object that maps the user-provided transformer names to the fitted transformer instances. This allows for direct access using the syntax `ct.named_transformers_['name']`.
    • C. Incorrect. `fitted_steps_` is not a valid attribute in scikit-learn. While the `Pipeline` class has a `named_steps` attribute, the `ColumnTransformer` class specifically uses `named_transformers_` for this purpose.
    • D. Incorrect. The `get_params()` method returns the configuration and parameters of the estimator. While it lists sub-estimators, it is not the designated attribute for retrieving fitted transformer objects by name after the fitting process.

    Domain 5: Model selection and validation

    Subdomain 5.2: Reading learning and validation curves

    32.You execute the `learning_curve` function and it returns three arrays: `train_sizes`, `train_scores`, and `test_scores`. The `cv` parameter was set to 5, and the `train_sizes` array has a length of 10. What is the shape of the returned `train_scores` array?

    1. A.(10,)
    2. B.(5, 10)
    3. C.(10, 5)
    4. D.(50,)
    Show answer & explanation

    Correct answer: C(10, 5)

    • A. Incorrect. The shape (10,) would be a 1-dimensional array. However, `train_scores` is a 2D array because it must record the specific score for every cross-validation fold at each of the 10 training sizes.
    • B. Incorrect. While this contains the correct factors, the dimensions are reversed. In scikit-learn's `learning_curve`, the first axis corresponds to the training set sizes (rows) and the second axis corresponds to the CV folds (columns).
    • C. Correct. The `train_scores` array is returned with the shape `(n_ticks, n_cv_folds)`. Since there are 10 training sizes (n_ticks) and 5 cross-validation folds (cv=5), the resulting shape is (10, 5). This allows for calculating statistics like the mean score for each size using `np.mean(train_scores, axis=1)`.
    • D. Incorrect. The shape (50,) would be a flattened 1D array. `learning_curve` returns a 2D array to keep the scores organized by training size and cross-validation split.

    Subdomain 5.4: Stability of learned coefficients across splits

    33.When using `cross_validate` in scikit-learn, which parameter must be explicitly set to allow inspection of the `coef_` attribute of the models trained on each fold?

    1. A.return_train_score=True
    2. B.return_estimator=True
    3. C.return_coefs=True
    4. D.extract_features=True
    Show answer & explanation

    Correct answer: Breturn_estimator=True

    • A. Incorrect. The `return_train_score` parameter determines whether training scores are included in the output dictionary. While useful for detecting overfitting, it does not provide access to the fitted estimator objects or their internal attributes like `coef_`.
    • B. Correct. By default, `cross_validate` discards the estimators after scoring. Setting `return_estimator=True` ensures that the fitted model for each fold is returned in a list under the 'estimator' key, allowing you to iterate through them and inspect coefficients, feature importances, or other model-specific attributes.
    • C. Incorrect. Scikit-learn's `cross_validate` does not have a `return_coefs` parameter. Accessing coefficients is done indirectly by returning the full estimator objects using `return_estimator=True`.
    • D. Incorrect. `extract_features` is not a valid parameter for the `cross_validate` function. Feature extraction is typically handled in a preprocessing step or within a Pipeline, not as a parameter of the cross-validation scoring utility.

    Subdomain 5.1: Cross-validation, KFold, ShuffleSplit, and friends

    34.You are building a diagnostic model using a dataset of 5,000 X-ray images collected from 400 unique patients. Some patients have up to 20 images, while others have only 1. To properly evaluate how well the model generalizes to new, unseen patients, which cross-validation splitter must you use?

    1. A.StratifiedKFold
    2. B.TimeSeriesSplit
    3. C.GroupKFold
    4. D.RepeatedKFold
    Show answer & explanation

    Correct answer: CGroupKFold

    • A. StratifiedKFold preserves class proportions across folds but performs the split at the individual sample level. In this scenario, different images from the same patient would likely end up in both training and validation sets, causing data leakage and an overoptimistic estimate of generalization to new patients.
    • B. TimeSeriesSplit is intended for temporally ordered data where the chronological sequence must be preserved. It does not group samples by patient and therefore cannot prevent images from the same patient from appearing in both the training and testing sets.
    • C. GroupKFold ensures that all samples with the same group label (in this case, patient ID) are kept together in the same fold. This prevents patient-level data leakage, ensuring that no patient seen during training appears in the validation set, which accurately measures how the model generalizes to new individuals.
    • D. RepeatedKFold repeats the K-Fold cross-validation process multiple times to reduce variance, but it still splits data at the sample level. Like standard K-Fold, it would allow images from the same patient to be split across folds, leading to leakage.

    Subdomain 5.3: Hyperparameter tuning with GridSearchCV, RandomSearchCV

    35.How must you configure the `refit` parameter to ensure the `GridSearchCV` object can be used to make predictions after fitting?

    1. A.refit=True
    2. B.refit='roc_auc' (or 'accuracy')
    3. C.refit=['accuracy', 'roc_auc']
    4. D.refit=False
    Show answer & explanation

    Correct answer: Brefit='roc_auc' (or 'accuracy')

    • A. While `refit=True` is the default behavior and works for single-metric evaluation, it is insufficient when multiple metrics are provided to the `scoring` parameter. In a multi-metric setup, `refit=True` becomes ambiguous, leading to a ValueError because the search object does not know which metric to use for final model optimization.
    • B. When using multiple scoring metrics, the `refit` parameter must be set to a specific string (the name of one of the scorers provided in the `scoring` dictionary). This ensures the GridSearchCV object refits the best found estimator on the entire dataset according to that specific metric, enabling the use of `predict()`, `predict_proba()`, and `best_estimator_` after the search.
    • C. The `refit` parameter does not accept a list of strings. It must be a single boolean, a single string name of a scorer, or a callable function to determine the best parameters for the final refit.
    • D. Setting `refit=False` prevents the estimator from being refitted on the full training set after the hyperparameter search is complete. Consequently, the GridSearchCV object will not have a `best_estimator_` attribute and will be unable to make predictions using `predict()` or `predict_proba()`.

    Want the full experience?

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