Machine Learning
Classification
Train and predict with common classifiers.
By EZ4Code Team
classificationclassifier
Code
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import make_classification
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=500, n_features=10, random_state=42)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=42)
models = {
"logreg": LogisticRegression(max_iter=1000),
"rf": RandomForestClassifier(n_estimators=100, random_state=42),
"gb": GradientBoostingClassifier(random_state=42),
"svc": SVC(kernel="rbf", probability=True),
"knn": KNeighborsClassifier(n_neighbors=5),
}
for name, m in models.items():
m.fit(X_tr, y_tr)
acc = accuracy_score(y_te, m.predict(X_te))
print(f"{name}: {acc:.4f}")Explanation
scikit-learn exposes a uniform fit/predict API across classifiers, so swapping models requires only changing the class. Random forests and gradient boosting are strong tabular-data baselines, while logistic regression and SVMs work well on linearly separable data. Comparing accuracy across several models is a fast first pass.
More Machine Learning Snippets
Data Preprocessing
Scale, encode, and impute features with sklearn.
Train Test Split
Split data into training and evaluation sets.
Regression
Fit regressors and evaluate with RMSE and R2.
Clustering
Cluster with KMeans and DBSCAN.
Metrics
Evaluate classifiers with confusion matrix and reports.
Pipeline
Chain preprocessing and modeling with Pipeline.