Interview prep

28 scikit-learn interview questions, with answers.

The scikit-learn questions interviewers actually ask: the estimator API, pipelines and leakage, cross-validation, tuning, and the practical traps that separate people who've used it from people who've read about it.

Scikit-learn questions come up in almost every data scientist and ML engineer interview, because the library's design mirrors good machine learning practice. An interviewer isn't checking whether you remember argument names. They want to know if you understand why a pipeline prevents leakage, when accuracy is the wrong score and what predict_proba really returns.

Answer each question out loud before opening the answer. If you can explain the trade-off, not just the definition, you're ready.

These 28 questions are free. SchoolWhool's Foundations of AI course places 650+ interview questions right after the lessons they test, with a mock interview with Gaurav. See also the machine learning interview questions.

The estimator API

What is the estimator API in scikit-learn?
Every estimator learns from data with fit(X, y) and stores what it learned in attributes ending in an underscore, such as coef_ or classes_. Predictors add predict (and often predict_proba or decision_function); transformers add transform. Because every model follows the same interface, you can swap one for another without changing the code around it.
What's the difference between fit, transform, fit_transform and predict?
fit learns parameters from data, for example the mean and standard deviation in StandardScaler. transform applies them, fit_transform does both on the same data (sometimes more efficiently), and predict maps features to outputs with a fitted model. The classic mistake is calling fit_transform on the test set, which re-learns the statistics from test data and leaks information.
Why do fitted attributes end with an underscore?
It's a convention that separates learned state (coef_, n_features_in_, feature_names_in_) from hyperparameters passed to the constructor. Reading a fitted attribute before calling fit raises NotFittedError. The constructor should only store its arguments, with no validation or logic, so that cloning and parameter search work.
What do get_params, set_params and clone do, and why do they matter?
get_params returns an estimator's hyperparameters, set_params changes them (including nested ones such as model__C), and clone makes an unfitted copy with the same settings. Cross-validation and GridSearchCV rely on clone to fit a fresh model on every fold. That's why a custom estimator must store its __init__ arguments unchanged.
What shapes should X and y have?
X is two-dimensional, (n_samples, n_features), and y is usually one-dimensional, (n_samples,). A single feature needs X.reshape(-1, 1) or df[['x']] with double brackets. Passing a column vector y of shape (n, 1) triggers a DataConversionWarning; use y.ravel().
How do you write a custom transformer?
Subclass BaseEstimator and TransformerMixin, store parameters unchanged in __init__, learn any state in fit (and return self), and apply it in transform. For a stateless function, FunctionTransformer is simpler. Implementing get_feature_names_out keeps column names flowing through a pipeline.

Preprocessing and pipelines

Why use a Pipeline?
A pipeline chains preprocessing steps and a model into one estimator, so fit learns every step from the training data only and predict applies exactly the same steps to new data. The main benefit is preventing leakage in cross-validation: scalers, imputers and encoders are re-fitted inside each fold. It also gives you one object to tune, save and deploy.
What does ColumnTransformer do?
It applies different transformers to different columns, for example StandardScaler on numeric columns and OneHotEncoder on categorical ones, then concatenates the results. remainder='passthrough' or 'drop' controls the columns you didn't mention, and make_column_selector can pick columns by dtype. It's usually the first step of a real-world pipeline.
How do you encode categorical features?
Use OneHotEncoder for nominal categories, with handle_unknown='ignore' so an unseen category at prediction time doesn't crash the model. OrdinalEncoder suits ordered categories, or tree models where one-hot encoding would create too many columns. For high-cardinality features, TargetEncoder (scikit-learn 1.3+) uses internal cross-fitting to limit leakage.
How do you handle missing values?
Use SimpleImputer (mean, median, most frequent or a constant), KNNImputer or IterativeImputer, always inside the pipeline so they're fitted on training folds only. add_indicator=True adds a was-missing column, which helps when missingness itself carries information. HistGradientBoostingClassifier and HistGradientBoostingRegressor handle NaN natively.
Which models need feature scaling, and which don't?
Distance- and gradient-based models do: k-nearest neighbours, SVMs, regularised linear and logistic regression, PCA and neural networks. Tree-based models (decision trees, random forests, gradient boosting) don't care about monotonic rescaling. With regularisation, scaling also makes the penalty treat every coefficient fairly.
StandardScaler, MinMaxScaler or RobustScaler: which and when?
StandardScaler gives zero mean and unit variance and is the usual default. MinMaxScaler maps to a fixed range such as 0 to 1 but is very sensitive to outliers. RobustScaler uses the median and interquartile range, so outliers barely affect it. None of them changes the shape of a skewed distribution; use a log transform or PowerTransformer for that.
What is data leakage in a scikit-learn workflow, and how do you prevent it?
Leakage is when information from validation or test data shapes training. Typical causes: scaling, imputing, selecting features or oversampling on the full dataset before splitting, or using a feature that's only known after the outcome. Put every data-dependent step in a Pipeline and pass the whole pipeline to cross-validation.

Model selection and evaluation

In train_test_split, what do stratify and random_state do?
stratify=y keeps class proportions the same in both splits, which matters for imbalanced classes. random_state makes the split reproducible. For time series, don't shuffle at all: split by date or use TimeSeriesSplit.
How is cross_validate different from cross_val_score?
cross_val_score returns one score per fold for a single metric. cross_validate can return several metrics, fit and score times, training scores (return_train_score=True) and the fitted estimators. For classifiers, the default is stratified 5-fold cross-validation.
When would you use GroupKFold or TimeSeriesSplit?
GroupKFold when rows aren't independent, such as several rows per patient or customer: a group never appears in both training and validation, so the score isn't inflated. TimeSeriesSplit when order matters: it always trains on the past and validates on the future. Plain KFold gives optimistic scores in both cases.
GridSearchCV or RandomizedSearchCV?
Grid search tries every combination, which is fine for two or three parameters with a few values each. Randomized search samples a fixed number of combinations from distributions and usually finds good settings faster when only some parameters matter. Both refit the best model on all the training data by default (refit=True), available as best_estimator_.
How do you tune a parameter of a step inside a pipeline?
Use step__parameter names in the grid, for example {'clf__C': [0.1, 1, 10], 'prep__num__strategy': ['mean', 'median']}. You can even search over whole steps by putting different estimators in the grid. Tuning the pipeline, not the bare model, keeps preprocessing inside each fold.
What can you pass to the scoring parameter?
A string such as 'accuracy', 'f1', 'roc_auc' or 'neg_mean_absolute_error' (errors are negated so that higher is always better), or a custom scorer built with make_scorer. For imbalanced classification prefer 'average_precision', 'f1' or a cost-based scorer over accuracy.
What's the difference between predict, predict_proba and decision_function?
predict returns labels using a default threshold, 0.5 for a probabilistic binary classifier. predict_proba returns class probabilities, and decision_function returns unbounded scores (SVMs, linear models). Use scores or probabilities for ROC AUC and for choosing a threshold; TunedThresholdClassifierCV (1.5+) picks the threshold by cross-validation.
Are the outputs of predict_proba calibrated?
Not necessarily. Logistic regression is often reasonably calibrated, while random forests, boosted trees, naive Bayes and SVMs frequently aren't. Check with a calibration curve (CalibrationDisplay) and fix with CalibratedClassifierCV, using sigmoid or isotonic calibration. It matters whenever the probability itself drives a decision.
How do you handle imbalanced classes in scikit-learn?
Use stratified splits, a metric that reflects the minority class, class_weight='balanced' where available, and tune the decision threshold. If you oversample (for example SMOTE from imbalanced-learn), do it inside the cross-validation pipeline, never before splitting. Class weights plus a tuned threshold often beat resampling.

Models in practice

Why does LogisticRegression give a ConvergenceWarning?
The solver didn't converge within max_iter, usually because features aren't scaled. Scale the features, raise max_iter or change the solver. Also remember it applies L2 regularisation by default (C=1.0), so coefficients are shrunk even if you didn't ask.
Random forest or HistGradientBoosting: how do you choose?
A random forest is a robust default with few hyperparameters, and adding trees doesn't overfit. Histogram gradient boosting is usually more accurate on tabular data, fast on large datasets, handles missing values and categorical features natively and supports early stopping, but needs more tuning (learning rate, iterations, leaf count). Try both against a simple baseline.
How do you get feature importance, and what's the catch?
Tree models expose feature_importances_, which is impurity-based, computed on training data and biased towards continuous or high-cardinality features. permutation_importance on a held-out set is more reliable but splits credit between correlated features. Linear coefficients are only comparable when features are on the same scale, and none of these measure causation.
How do you save and load a trained model?
Save the whole fitted pipeline with joblib.dump and load it with joblib.load, so preprocessing comes with the model. Pickle files are tied to the library versions that wrote them and can execute code, so only load files you trust. Record the versions, or use skops or ONNX when you need portability.
What does set_output(transform='pandas') do?
It makes transformers and pipelines return DataFrames with column names instead of NumPy arrays (scikit-learn 1.2+). That makes intermediate steps much easier to inspect and debug alongside get_feature_names_out. It doesn't work with sparse output, such as OneHotEncoder(sparse_output=True).
Should you tune random_state?
No. It controls randomness (bootstrapping, feature subsampling, initialisation) so results are reproducible; picking the best seed is just overfitting to noise. If scores swing a lot between seeds, the model or the evaluation is unstable, so report the mean and spread across folds or seeds.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.

Learn it properly, then the interview is the easy part.

Foundations of AI teaches scikit-learn and the rest of machine learning from first principles, with notebooks that check your work.