Scikit-learn interview questions and answers for data scientists and ML engineers

Scikit-learn interview questions test whether you can use the library's estimator API without leaking information: fit on training data only, chain preprocessing and model in a Pipeline, pick the right cross-validation splitter, and tune hyperparameters with a search that refits everything per fold. Senior candidates also get questions on persistence, large datasets and custom transformers. Most failures in these rounds are not wrong algorithms but a scaler or feature selector fitted on the full dataset.

By Published 8 min read

How scikit-learn appears in interviews

Scikit-learn is the default toolkit for classical machine learning in Python, so it shows up in data scientist, ML engineer, quantitative analyst and analytics engineer interviews. Questions sit in three places: quick API checks in a screen, a live notebook task where you train and evaluate a model on a small table, and a code review where you are shown someone else's notebook and asked what is wrong with the evaluation. Interviewers use it to see whether your modeling habits are sound, so they listen to how you split and validate as much as to which model you pick.

  1. API screenA handful of questions on fit and transform, probabilities, encoders and splitters.
  2. Notebook taskClean a small dataset, build a baseline, improve it, and report a metric with an honest validation scheme.
  3. Evaluation reviewSpot leakage, a wrong splitter, a mismatched metric or a test set used for tuning in a prepared notebook.
  4. Production follow-upsHow you would save, version, retrain and serve the pipeline, and what changes when data grows.

Scikit-learn fundamentals questions

API questions for freshers and the opening of a notebook round
QuestionWhat it testsWhat a strong answer shows
What is the estimator API?Library designEvery estimator has fit; predictors add predict and often predict_proba; transformers add transform. Constructor arguments are hyperparameters, and anything learned during fit ends in an underscore, such as coef_.
Why call fit_transform on train but only transform on test?Leakage basicsThe transformer must learn its statistics, such as means or vocabularies, from training data only. Refitting on test data quietly uses information you would not have in production.
predict versus predict_proba versus decision_function?OutputsLabels at a default cut-off, class probabilities, and raw signed scores. Ranking metrics such as ROC-AUC need scores or probabilities, not labels.
Why scale features for some models but not others?Model behaviorDistance and gradient-based models such as KNN, SVMs and regularized linear models are sensitive to feature scale. Tree models split on thresholds and do not care.
What does stratify=y in train_test_split do?SplittingKeeps class proportions the same in both parts, which matters for rare classes. Setting random_state makes the split repeatable.
OneHotEncoder or OrdinalEncoder?CategoricalsOne-hot for unordered categories with linear models; ordinal codes are fine for tree models or truly ordered levels. handle_unknown="ignore" stops new categories in production from crashing.
What is LabelEncoder for?API trapEncoding the target, not input features. For features, use OrdinalEncoder or OneHotEncoder inside a ColumnTransformer.
What does model.score return?DefaultsAccuracy for classifiers and R squared for regressors, which may not be the metric the business cares about. Name your metric explicitly with scoring.
What does cross_val_score do that a single split does not?ValidationIt trains and scores on several folds, so you see the spread as well as the mean and depend less on one lucky split.
What does random_state control, and when does it not save you?ReproducibilitySeeds for shuffling and randomized models. Results can still vary with different library versions or data order, so record versions with results.
API questions for freshers and the opening of a notebook round. Scroll sideways on a small screen.

Pipelines, preprocessing and tuning

A pipeline is the answer interviewers hope to hear for many questions. It keeps preprocessing inside cross-validation so each fold fits its own imputer, scaler and encoder, and it gives you one object to tune, save and deploy. ColumnTransformer routes numeric and categorical columns to different steps. In a grid search, parameters are addressed as the step name, two underscores, then the parameter name.

import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

rng = np.random.default_rng(0)
n = 600
df = pd.DataFrame({
    "tenure": rng.integers(1, 60, n).astype(float),
    "spend": rng.normal(50, 15, n),
    "plan": rng.choice(["basic", "plus", "pro"], n),
})
df.loc[rng.choice(n, 30, replace=False), "spend"] = np.nan
y = ((df["tenure"] < 12) & (df["plan"] == "basic")).astype(int)
y = np.where(rng.random(n) < 0.1, 1 - y, y)   # flip about 10% of labels as noise

prep = ColumnTransformer([
    ("num", Pipeline([("impute", SimpleImputer(strategy="median")),
                      ("scale", StandardScaler())]), ["tenure", "spend"]),
    ("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
])
pipe = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])

search = GridSearchCV(
    pipe,
    {"clf__C": [0.1, 1.0, 10.0]},           # step name, two underscores, parameter
    cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=0),
    scoring="roc_auc",
)
search.fit(df, y)                            # imputer and scaler refit inside every fold
print(search.best_params_, round(search.best_score_, 3))
ColumnTransformer inside a Pipeline, tuned with GridSearchCV. On this synthetic data it prints the chosen C (10.0) and a mean ROC-AUC of about 0.64.
  • GridSearchCV or RandomizedSearchCV? Grid search for a few discrete values; randomized search when there are many parameters or continuous ranges, since it covers the space with a fixed budget. Successive halving variants exist too but are flagged experimental in recent releases.
  • What does `refit=True` do after a search? Retrains the best configuration on all the data passed to fit, so search.predict uses that final model. With several metrics you must say which one picks the winner.
  • Which splitter would you use for repeat customers? GroupKFold, so the same customer never appears in both training and validation folds.
  • And for data over time? TimeSeriesSplit, which always trains on the past and validates on the future. Random shuffling of time-ordered rows inflates scores.
  • How do you handle class imbalance with scikit-learn alone? class_weight="balanced" on models that accept it, stratified splits, a metric that suits rare positives such as average precision, and a tuned decision threshold. Resampling methods like SMOTE live in the separate imbalanced-learn package.
  • How do you get calibrated probabilities? Wrap the model in CalibratedClassifierCV with sigmoid or isotonic calibration and check a reliability curve. Trees and SVM scores are often poorly calibrated out of the box.
  • How do you choose a threshold other than 0.5? From validation data, using costs of false positives and negatives or a target precision. Recent versions also add a tuned-threshold classifier that does this inside cross-validation.
  • Impurity-based importance or permutation importance? Impurity importance from trees is biased toward high-cardinality features and is computed on training data. Permutation importance on held-out data is slower but closer to what the model relies on.
  • How do you write a custom transformer? Subclass BaseEstimator and TransformerMixin, store constructor arguments unchanged, learn in fit and return self, and apply in transform. Then it works inside pipelines, clone and grid search.
  • `Pipeline` or `make_pipeline`? The same object; make_pipeline names steps after their lowercased class names, which changes the prefixes you use in a parameter grid.
  • How do you add a free-text column to a ColumnTransformer? Give TfidfVectorizer the column name as a plain string, not a one-item list. The vectorizer expects a one-dimensional sequence of documents; handed a one-column table, it iterates over the column labels instead of the rows and the output is wrong.
  • What does `clone` do, and why does cross-validation rely on it? It builds a fresh, unfitted copy with the same hyperparameters, so each fold starts clean. It is also why custom estimators must not change their constructor arguments.
  • How do you keep column names through a pipeline? Call set_output(transform="pandas") on the pipeline or transformer, and use get_feature_names_out to map coefficients back to features.

Senior and scenario questions

The classic senior question is a notebook with an impressive score that turns out to be leakage. The demonstration below is worth knowing by heart: select features on all rows before cross-validation and random noise looks predictive; do the same selection inside a pipeline and the score falls back to chance.

import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(0)
X = rng.normal(size=(100, 5000))     # pure noise features
y = rng.integers(0, 2, 100)          # random labels: true accuracy is about 0.5

# Leaky: choose features on all rows, then cross-validate
X_leaky = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_leaky, y, cv=5).mean()

# Honest: selection happens inside each training fold
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
honest = cross_val_score(pipe, X, y, cv=5).mean()
print(f"leaky {leaky:.2f}  honest {honest:.2f}")
Feature selection leakage on pure noise. This run printed: leaky 0.85 honest 0.48.
Scenarios for experienced candidates
ScenarioWhat it testsWhat a strong answer shows
A colleague reports 0.97 AUC on a churn model built last week.Leakage huntingCheck for features recorded after the outcome, preprocessing fitted before the split, duplicate customers across folds and a test set used during tuning.
Report an unbiased score after hyperparameter tuning.Nested CVRun the search inside an outer cross-validation loop, or keep a final untouched test set. The search's best score is optimistic.
The training data no longer fits in memory.ScaleUse estimators with partial_fit, such as SGDClassifier, on chunks; switch to HistGradientBoosting for large tabular data; or sample carefully and check the learning curve before buying more hardware.
Save the model and load it in a service.PersistencePersist the whole pipeline with joblib, pin the scikit-learn version, and never load pickles from untrusted sources because loading can run arbitrary code. Mention formats such as skops or ONNX if the team needs safer or cross-language loading.
Unpickling fails or warns after an upgrade.VersioningModels are not guaranteed to load across scikit-learn versions. Retrain under the new version, or keep the old version in the serving image until you do.
Gradient boosting in scikit-learn or a separate library?Tool choiceHistGradientBoosting handles large tables, missing values and native categorical support in recent versions. XGBoost, LightGBM or CatBoost may add speed or features; compare on your validation scheme, not on reputation.
Grid search is too slow.ComputeRandomize the search, narrow ranges from a coarse pass, cache pipeline transformers with the memory argument, and use n_jobs while watching memory per worker.
Your linear model's coefficients look unstable between runs.InterpretationCorrelated features share weight unpredictably. Scale features, regularize, check variance across folds, and explain why coefficients are not causal effects.
Scenarios for experienced candidates. Scroll sideways on a small screen.

Fictional example

Answering "this model scores 0.97 AUC, should we ship it?"
Interviewer
A teammate built a churn model with 0.97 AUC in cross-validation. Would you ship it?
Candidate
Not before I see how the score was produced, because churn models that good usually leak. I would read the notebook top down. First, where the split happens: if the scaler, imputer or target encoding ran on the full table before cross_val_score, I would move them into a Pipeline. Second, the features: anything like days since last login measured after the churn date, or a cancellation-reason field, gives the answer away. Third, the rows: if customers appear several times, KFold puts the same person on both sides, so I would switch to GroupKFold by customer id. In a similar review I ran, fixing those three dropped the score to around 0.78, which was still useful and, more importantly, held up on the next month of data.

A one-week scikit-learn practice plan

  • Day 1: take a public tabular dataset and build a baseline with a Pipeline and ColumnTransformer, no tuning.
  • Day 2: compare KFold, StratifiedKFold, GroupKFold and TimeSeriesSplit on data where the choice matters, and write down why.
  • Day 3: tune with GridSearchCV and RandomizedSearchCV, then evaluate honestly with nested cross-validation.
  • Day 4: reproduce the leakage demo above and invent two more leaks to find in your own notebook.
  • Day 5: write a custom transformer, test it with clone and inside a grid search, and keep pandas output.
  • Day 6: calibrate a classifier, pick a threshold from costs, and compare permutation and impurity importance.
  • Day 7: a timed 45-minute mock: from CSV to a validated, saved pipeline, explaining each step aloud.

Scikit-learn usually sits next to a deep learning framework in the same loop, so pair this page with PyTorch interview questions or TensorFlow interview questions, and see machine learning scientist interview questions if the role is research-heavy. For the theory behind the metrics, machine learning interview questions goes deeper.

Notebook rounds are judged on how you justify a split or a metric, which is easy to rush when someone is watching. Natively, an AI interview assistant for Mac and Windows, keeps a transcript of a practice session on your computer, so afterwards you can check whether you named the splitter and explained why. While you rehearse, it can read a notebook cell or an error from a screenshot and suggest a cleaner pipeline, and with Pro or the free trial it uses the résumé and job description you add when it drafts answers. The notes stay in your history for the next review.

Questions people ask

What scikit-learn questions are asked in interviews?

The fit, transform and predict API, why test data is only transformed, Pipeline and ColumnTransformer, choosing a cross-validation splitter, GridSearchCV parameter naming, class imbalance, calibration and saving models.

Why do interviewers care so much about pipelines?

A pipeline keeps preprocessing inside each cross-validation fold, which prevents leakage, and it gives one object to tune, save and deploy.

What is data leakage in scikit-learn?

Using information from validation or test rows while training, for example fitting a scaler or feature selector on the full dataset before cross-validation. It inflates scores that then fail on new data.

How should I practice for a scikit-learn coding round?

Go from a raw CSV to a tuned, validated and saved pipeline in under an hour, then explain your splitter, metric and leakage checks aloud.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP