Loading…
DS · Model evaluation · Program 14 · In the record
Model selection using train-test split and cross-validation.
1from sklearn.datasets import make_classification2from sklearn.model_selection import train_test_split, cross_val_score3from sklearn.linear_model import LogisticRegression4from sklearn.neighbors import KNeighborsClassifier5from sklearn.tree import DecisionTreeClassifier6 7X, y = make_classification(n_samples=500, n_features=8, n_informative=5, n_redundant=2, random_state=42)8X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)9 10models = {'Logistic Regression': LogisticRegression(), 'kNN': KNeighborsClassifier(),11 'Decision Tree': DecisionTreeClassifier(random_state=42)}12cv = {}13for name, m in models.items():14 test = m.fit(X_train, y_train).score(X_test, y_test)15 cv[name] = cross_val_score(m, X, y, cv=5).mean()16 print(f"{name:20s} Test Accuracy: {test:.4f} 5-Fold CV: {cv[name]:.4f}")17print("Best model:", max(cv, key=cv.get))Logistic Regression Test Accuracy: 0.8480 5-Fold CV: 0.8440 kNN Test Accuracy: 0.9120 5-Fold CV: 0.9180 Decision Tree Test Accuracy: 0.8720 5-Fold CV: 0.9000 Best model: kNN

Run program 14 in your browser
Python 3.14 · Pyodide. Change the code or the input, run it, break it, and see what happens.