Why do we use cross-validation when comparing machine learning models?
Think about how to check if a model will work well on new data.
Cross-validation splits data into several parts to train and test models multiple times. This helps estimate how well the model will perform on new, unseen data.
You have a classification problem with very imbalanced classes. Which metric is best to compare models fairly?
Think about a metric that balances false positives and false negatives.
F1-score balances precision and recall, making it suitable for imbalanced datasets where accuracy can be misleading.
What is the output of the following Python code?
from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import cross_val_score iris = load_iris() X, y = iris.data, iris.target model = DecisionTreeClassifier(random_state=42) scores = cross_val_score(model, X, y, cv=5) print(round(scores.mean(), 2))
Decision trees usually perform well on iris dataset; cross-validation averages accuracy over 5 folds.
The DecisionTreeClassifier on iris dataset with 5-fold cross-validation typically achieves around 95% accuracy.
What is the main effect of increasing the number of folds (cv) in k-fold cross-validation?
More folds mean training on more data each time but testing on fewer samples.
Increasing folds reduces bias because models train on more data each time, but variance increases because test sets are smaller and results vary more.
What error does the following code raise when trying to compare two models using cross-validation?
from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import cross_val_score iris = load_iris() X, y = iris.data, iris.target model1 = LogisticRegression(max_iter=200) model2 = DecisionTreeClassifier() scores1 = cross_val_score(model1, X, y, cv=5) scores2 = cross_val_score(model2, X, y, cv=5) print(scores1.mean()) print(scores2.mean())
Check if LogisticRegression needs extra parameters for convergence.
LogisticRegression by default has max_iter=100 which may be too low for convergence on iris data, causing a ConvergenceWarning.
