Editor

Compare Three Classifiers

Intermediate · Write the code · from Python Classification: Build a Classifier with scikit-learn

From the lesson: Python Classification: Build a Classifier with scikit-learn

Your email inbox sorts messages into "spam" or "not spam." A bank flags transactions as "fraudulent" or "legitimate." A doctor classifies a tumor as "benign" or "malignant." These are all classification problems - the model predicts which category something belongs to.

Read the lesson

Train LogisticRegression, DecisionTreeClassifier(max_depth=4), and KNeighborsClassifier(n_neighbors=5) on the scaled data. Print each model's accuracy on the test set in the format "ModelName: X.XXXX" on separate lines. Use names: "LR", "DT", "KNN". All models use random_state=42 where applicable.

from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
X, y = make_classification(n_samples=300, n_features=6,
random_state=42)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Train and compare all three classifiers

More Classification exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz