best_score: best_score, best_C = score, C # K-fold cross-validation approach (slower, more reliable signal) param_grid = {'C': [0.1, 1, 10, 100]} grid_search = GridSearchCV(SVC(), param_grid, cv=5, scoring='accuracy') grid_search.fit(X_train_full, y_train_full) print('Best C:', grid_search.best_params_) print('CV score:', grid_search.best_score_) # Nested CV for unbiased performance estimate after tuning: # outer loop estimates generalization, inner loop tunes hyperparameters from sklearn.model_selection import cross_val_score nested_scores = cross_val_score(grid_search, X, y, cv=5)"> best_score: best_score, best_C = score, C # K-fold cross-validation approach (slower, more reliable signal) param_grid = {'C': [0.1, 1, 10, 100]} grid_search = GridSearchCV(SVC(), param_grid, cv=5, scoring='accuracy') grid_search.fit(X_train_full, y_train_full) print('Best C:', grid_search.best_params_) print('CV score:', grid_search.best_score_) # Nested CV for unbiased performance estimate after tuning: # outer loop estimates generalization, inner loop tunes hyperparameters from sklearn.model_selection import cross_val_score nested_scores = cross_val_score(grid_search, X, y, cv=5)" />

Prev Next

Python / Python Mathematical Intuition and Scikit Learn Interview Questions

What is the difference between a single train/validation/test split and k-fold cross-validation for hyperparameter tuning, statistically?

A single validation split estimates a hyperparameter's performance using just one specific subset of data — this estimate has high variance because it depends entirely on which particular samples happened to land in the validation fold. If you tune hyperparameters against this single estimate, you risk overfitting to the quirks of that specific split (sometimes called "validation set overfitting").

K-fold cross-validation produces k separate performance estimates by rotating which fold serves as validation, then averages them. The variance of this average is mathematically lower than the variance of a single estimate (by a factor related to the correlation between folds, as discussed in the bias-variance tradeoff of CV), giving a more statistically reliable signal for comparing hyperparameter choices, at the cost of k times the computation.

from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.svm import SVC

# Single validation split approach (faster, noisier)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2)
best_score, best_C = 0, None
for C in [0.1, 1, 10, 100]:
    model = SVC(C=C).fit(X_train, y_train)
    score = model.score(X_val, y_val)
    if score > best_score:
        best_score, best_C = score, C

# K-fold cross-validation approach (slower, more reliable signal)
param_grid = {'C': [0.1, 1, 10, 100]}
grid_search = GridSearchCV(SVC(), param_grid, cv=5, scoring='accuracy')
grid_search.fit(X_train_full, y_train_full)
print('Best C:', grid_search.best_params_)
print('CV score:', grid_search.best_score_)

# Nested CV for unbiased performance estimate after tuning:
# outer loop estimates generalization, inner loop tunes hyperparameters
from sklearn.model_selection import cross_val_score
nested_scores = cross_val_score(grid_search, X, y, cv=5)
Why does a single train/validation split have higher variance than k-fold cross-validation for hyperparameter selection?
What is the purpose of nested cross-validation when both tuning hyperparameters and estimating final model performance?

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.

Invest now!!! Get Free equity stock (US, UK only)!

Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.

The Robinhood app makes it easy to trade stocks, crypto and more.


Webull! Receive free stock by signing up using the link: Webull signup.

More Related questions...

Why does linear regression minimise the sum of squared errors instead of, say, absolute errors? Explain the mathematical intuition behind gradient descent and why the learning rate matters. Why do you need to scale features before using gradient descent-based models or distance-based algorithms like KNN? Explain the bias-variance tradeoff mathematically and how it relates to model complexity. What is the mathematical difference between L1 (Lasso) and L2 (Ridge) regularization, and why does L1 produce sparse solutions? How does maximum likelihood estimation connect to the logistic regression cost function? How do decision trees decide which feature and threshold to split on? Explain Gini impurity and entropy. Why does a random forest reduce variance compared to a single decision tree, and what role does feature randomness play? What is the mathematical intuition behind gradient boosting? How does it differ from random forests? Explain the mathematical foundation of PCA. What do eigenvectors and eigenvalues represent in this context? What is the mathematical concept of the margin in Support Vector Machines, and why does maximizing it improve generalization? What is the kernel trick in SVMs and why does it avoid explicitly computing high-dimensional feature mappings? Why does K-Nearest Neighbors suffer from the curse of dimensionality, mathematically? What is the mathematical objective function K-Means optimises, and why can it converge to a local minimum? What is the statistical rationale behind k-fold cross-validation, and why are k=5 or k=10 commonly used? What does the ROC-AUC score mathematically represent, and why is it threshold-independent? Explain the mathematical tradeoff between precision and recall, and why F1 score is the harmonic mean rather than the arithmetic mean. What is the 'naive' independence assumption in Naive Bayes, and why does it still work well in practice despite being unrealistic? Why is a log transformation commonly applied to skewed numerical features before modeling, mathematically? What is multicollinearity, mathematically, and how does the Variance Inflation Factor (VIF) detect it? Why must features be standardized before applying Ridge or Lasso regularization, mathematically? What is the mathematical relationship between learning_rate and n_estimators in gradient boosting? How does the softmax function generalize logistic regression to multiclass classification, mathematically? Why does fitting a scaler or transformer on the entire dataset (before train/test split) cause data leakage, mathematically? How does the class_weight parameter mathematically address class imbalance in scikit-learn classifiers? Why does using simple label encoding (integers) for nominal categorical features mislead most machine learning models, mathematically? What is the difference between a single train/validation/test split and k-fold cross-validation for hyperparameter tuning, statistically? Why is PCA sensitive to feature scaling while decision tree feature importance is not, mathematically? Why is the decision boundary of standard logistic regression always a straight line (or hyperplane), mathematically? Why can R-squared be a misleading metric for model comparison, and how does adjusted R-squared address this? Derive mathematically why bagging (bootstrap aggregating) reduces variance, and under what condition it does NOT help. Why does convexity of the loss function matter for optimization algorithms like gradient descent, mathematically? Mathematically, why does RobustScaler handle outliers better than StandardScaler? What does it mean for a classifier's predicted probabilities to be 'well-calibrated', and why don't all models produce calibrated probabilities naturally? Mathematically, why does stochastic gradient descent (SGD) scale to large datasets better than batch gradient descent? Beyond scaling, why must feature selection methods also be included inside a cross-validation pipeline rather than applied beforehand?
Show more question and Answers...

Python Deep Learning and Neural Networks Interview Questions

Comments & Discussions