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?
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?
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?
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?
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?
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?
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?
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?
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?
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?
refit=True), available as best_estimator_.How do you tune a parameter of a step inside a pipeline?
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?
'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?
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?
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?
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?
How do you get feature importance, and what's the catch?
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?
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?
get_feature_names_out. It doesn't work with sparse output, such as OneHotEncoder(sparse_output=True).Should you tune random_state?
Keep preparing
scikit-learn fit, transform and predict: what each method does
fit learns from training data, transform applies that learning, predict outputs answers. See a table, runnable code and why test data gets transform only.
ArticleData leakage in machine learning: how a model looks brilliant and fails on day one
What data leakage is, the five ways it sneaks in, and the habits that keep your validation scores honest.
ArticleAccuracy is lying to you: baselines, imbalance, precision and recall
Why a model that's right 89% of the time can be almost useless, and the three questions to ask before you trust any accuracy score.
Interview prep26 pandas interview questions
pandas interview questions on indexing, cleaning, groupby, merges, reshaping and performance, including the warnings and silent bugs interviewers love to ask about.
Interview prep24 NumPy interview questions
NumPy interview questions on arrays, dtypes, views and copies, broadcasting, vectorisation and linear algebra: the foundations every data science library is built on.
Interview prep28 Python interview questions
Python interview questions for data science, ML and backend roles: mutability, data structures, functions and scope, classes, generators, errors and the GIL, with the pitfalls interviewers probe.
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.