scikit-learn 1 cheatsheet
scikit-learn 1: Training models
7 common scikit-learn 1 tasks.
Train and predict
Every estimator has fit and predict. Train on the training set, then predict labels for new rows.
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=200, random_state=42)
clf.fit(X_train, y_train)
predictions = clf.predict(X_test)
Get class probabilities
Return the predicted probability of each class instead of just the label.
probabilities = clf.predict_proba(X_test)
Fit a linear regression
Fit a least-squares line for a numeric target, then read the learned coefficients.
from sklearn.linear_model import LinearRegression
reg = LinearRegression().fit(X_train, y_train)
print(reg.intercept_, reg.coef_)
Fit a logistic regression
A fast, interpretable baseline for classification.
from sklearn.linear_model import LogisticRegression
logit = LogisticRegression(max_iter=1000).fit(X_train, y_train)
Use gradient boosting
A strong, fast model for tabular data that handles missing values natively.
from sklearn.ensemble import HistGradientBoostingClassifier
boost = HistGradientBoostingClassifier(random_state=42).fit(X_train, y_train)
Cluster data
Group rows into k clusters without labels.
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=3, n_init=10, random_state=42).fit(X)
clusters = kmeans.labels_
Reduce dimensions
Project the data onto its two main directions of variance, for plotting or compression.
from sklearn.decomposition import PCA
pca = PCA(n_components=2).fit(X)
X_2d = pca.transform(X)
print(pca.explained_variance_ratio_)