1. Basic workflow of machine learning
Typical supervised learning process:
Raw Data
↓
Data Cleaning
↓
Feature / Target Selection
↓
Train / Validation / Test Split
↓
Preprocessing
↓
Model Training
↓
Prediction
↓
Evaluation
↓
Hyperparameter Tuning
↓
Final Model
Note: Split the data before fitting any preprocessing steps that learn statistics from the data, to prevent test-set information leakage.
core concepts
| concept | meaning |
|---|---|
| Sample | a sample record |
| Feature(X) | Input features |
| Target / Label(y) | predicted target |
| Training Set | Training model |
| Validation Set | Model selection and parameter adjustment |
| Test Set | Final assessment of generalization ability |
| Parameter | Parameters learned during training |
| Hyperparameter | Configuration set up before training |
| Fit | Fit a model using data |
| Predict | Make predictions on new samples |
| Generalization | Model performance on unseen data |
scikit-learn Usually agreed:
X.shape # (n_samples, n_features)
y.shape # (n_samples,)
For example:
import numpy as np
X = np.array([
[25, 5000],
[30, 7000],
[35, 9000],
])
y = np.array([0, 1, 1])
Here each row is a sample, each column is a feature, and y is the corresponding classification label.
2. Estimator API: Unified model interface
One of the most important designs of scikit-learn is to provide relatively unified API for different algorithms.
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
Common methods:
| method | Purpose |
|---|---|
fit(X, y) | Learn model parameters |
predict(X) | Predict labels or values |
predict_proba(X) | Predict class probability, supported by some classifiers |
decision_function(X) | Returns decision score, supported by some models |
transform(X) | Transform data |
fit_transform(X) | Convert after fitting |
fit_predict(X) | Fit and return prediction results, supported by some algorithms |
score(X, y) | Return model default rating |
get_params() | Get model hyperparameters |
set_params() | Modify model hyperparameters |
Special distinction is required:
- Estimator: An object capable of learning data via
fit(). - Transformer: Data conversion object that implements
transform(). - Predictor: Implements the prediction model of
predict().
For example:
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
scaler = StandardScaler()
model = LinearRegression()
X_scaled = scaler.fit_transform(X)
model.fit(X_scaled, y)
Parameter and Hyperparameter
Take linear regression as an example:
coef_,intercept_: parameters obtained by training.alpha,max_depth,n_estimators, etc.: hyperparameters of different models.
scikit-learn agrees that many attributes obtained after training end with _:
model.coef_
model.intercept_
3. Data splitting: train_test_split
After training the model, you cannot only use the training data to evaluate its effect, otherwise it is easy to overestimate the generalization ability.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
)
Important parameters:
test_size: test set proportion.random_state: Controls the reproducibility of random splits.shuffle: Whether to scramble the data.stratify: Stratified sampling proportionally to the target category.
Classification problems often use:
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
stratify=y,
random_state=42,
)
Different data require different splitting methods
| data type | Recommended method |
|---|---|
| Ordinary independent sample | Random Split |
| Class Imbalanced Classification | Stratified Split |
| Multiple records for the same user | Group-based Split |
| time series | Time-based Split |
Time series cannot be simply randomly disrupted, otherwise it may be possible to use future data to predict the past.
If multiple pieces of data from the same user are distributed into the training set and test set, it may also lead to unrealistically high scores.
4. Data preprocessing: Preprocessing
Real business data usually cannot be fed directly into all machine learning models.
Common preprocessing:
Raw Features
↓
Missing Value Imputation
↓
Categorical Encoding
↓
Scaling / Normalization
↓
Feature Transformation
↓
Model
Missing value: SimpleImputer
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(strategy="median")
X_train_imputed = imputer.fit_transform(X_train)
X_test_imputed = imputer.transform(X_test)
Common strategies:
| strategy | meaning |
|---|---|
mean | mean imputation |
median | median padding |
most_frequent | mode imputation |
constant | Fixed value padding |
Key principles:
can only be executed using training data fit(), and test data can only be executed transform().
Standardization: StandardScaler
Standardized formula:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
After normalization, training data typically has a mean close to 0 and a standard deviation of 1.
Normalization: MinMaxScaler
Scale features to a specified range:
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
Common differences:
| method | Main function |
|---|---|
StandardScaler | Return the mean to zero and standard deviation to one |
MinMaxScaler | Zoom to specified range |
RobustScaler | Use medians and quantiles to reduce the impact of outliers |
Normalizer | Norm normalize each sample vector |
StandardScaler, MinMaxScaler usually operate on feature columns, while Normalizer usually normalizes by sample.
Which models need standardization?
Usually more sensitive to:
- Logistic Regression。
- Linear Regression (especially the regularized version).
- SVM。
- KNN。
- K-Means。
- PCA。
Usually less sensitive to:
- Decision Tree。
- Random Forest。
- Gradient Boosting Trees。
The reason is that tree models mainly rely on feature threshold partitioning, while distance and linear models are usually more affected by numerical scales.
5. Categorical Encoding: Categorical feature encoding
Machine learning models generally cannot handle ordinary string categories directly.
OneHotEncoder
For example:
City
Tokyo
Osaka
Kyoto
Converts to:
Tokyo Osaka Kyoto
1 0 0
0 1 0
0 0 1
Code:
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(
handle_unknown="ignore",
sparse_output=False,
)
X_encoded = encoder.fit_transform(
[["Tokyo"], ["Osaka"], ["Kyoto"]]
)
handle_unknown="ignore" can handle categories that did not appear in training when predicting.
OrdinalEncoder
Map categories to integers:
from sklearn.preprocessing import OrdinalEncoder
encoder = OrdinalEncoder()
X_encoded = encoder.fit_transform(
[["low"], ["medium"], ["high"]]
)
Note: For categories that have no natural order, integer encoding may introduce size relationships that do not exist.
LabelEncoder is mainly used for the target label y, rather than the general input feature X.
6. Pipeline and ColumnTransformer
This is one of the most important parts of the actual development of scikit-learn.
Pipeline
Combine preprocessing and model training into one object:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([
("scaler", StandardScaler()),
("model", LogisticRegression(max_iter=1000)),
])
pipeline.fit(X_train, y_train)
y_pred = pipeline.predict(X_test)
Advantages:
- Automatically perform preprocessing in the correct order.
- Training and prediction use consistent data transformation logic.
- Reduce Data Leakage.
- Supports cross-validation and hyperparameter search.
- Easily save and deploy complete processes.
ColumnTransformer
Real DataFrame often contains both numerical and categorical features.
For example:
Age Salary City
25 5000 Tokyo
30 7000 Osaka
35 9000 Kyoto
Different preprocessing methods need to be used for different columns.
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
preprocessor = ColumnTransformer([
("numeric", StandardScaler(), ["age", "salary"]),
("categorical", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
A more complete workflow:
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
numeric_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler()),
])
categorical_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="most_frequent")),
("encoder", OneHotEncoder(handle_unknown="ignore")),
])
preprocessor = ColumnTransformer([
("num", numeric_pipeline, ["age", "salary"]),
("cat", categorical_pipeline, ["city"]),
])
model = Pipeline([
("preprocessor", preprocessor),
("classifier", LogisticRegression(max_iter=1000)),
])
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
Pipeline allows the preprocessing in cross-validation to only learn the data corresponding to the training fold, which is an important tool to avoid Data Leakage.
7. Regression: Regression analysis
Regression is used to predict continuous numerical values.
For example:
- house prices.
- sales.
- temperature.
- User consumption amount.
- demand.
Linear Regression
Linear regression:
Basic example:
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
X, y = make_regression(
n_samples=500,
n_features=5,
noise=10,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
Important attributes:
model.coef_ # Characteristic coefficient
model.intercept_ # intercept
Ridge / Lasso / ElasticNet
Regularization is added to linear regression to limit model complexity.
| model | regularization | Features |
|---|---|---|
| LinearRegression | None | Basic linear regression |
| Ridge | L2 | Shrinkage coefficient to alleviate overfitting |
| Lasso | L1 | Can make some coefficients become 0 |
| ElasticNet | L1 + L2 | Combining two regularizations |
from sklearn.linear_model import Ridge, Lasso, ElasticNet
ridge = Ridge(alpha=1.0)
lasso = Lasso(alpha=0.1)
elastic = ElasticNet(alpha=0.1, l1_ratio=0.5)
alpha controls the regularization strength; usually the larger it is, the more obvious the coefficient shrinkage is.
Polynomial Regression
Fit nonlinear relationships by constructing polynomial features:
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
model = make_pipeline(
PolynomialFeatures(degree=2, include_bias=False),
LinearRegression(),
)
model.fit(X_train, y_train)
The essence is still to perform linear regression on the expanded features.
Tree-based Regression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import HistGradientBoostingRegressor
| model | Features |
|---|---|
| Decision Tree | Rule division, easy to explain, but prone to overfitting |
| Random Forest | Integrate multiple trees to reduce the instability of a single tree |
| Gradient Boosting | Build tree models incrementally to reduce prediction errors |
For ordinary tabular data, Random Forest and Gradient Boosting are commonly used nonlinear baseline models.
Regression indicator
| indicator | meaning | Trend |
|---|---|---|
| MAE | mean absolute error | The lower the better |
| MSE | mean squared error | The lower the better |
| RMSE | root mean square error | The lower the better |
| R² | coefficient of determination | Higher is usually better |
| MAPE | mean absolute percentage error | The lower the better |
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
root_mean_squared_error,
r2_score,
)
print(mean_absolute_error(y_test, y_pred))
print(mean_squared_error(y_test, y_pred))
print(root_mean_squared_error(y_test, y_pred))
print(r2_score(y_test, y_pred))
MAE and RMSE
RMSE is more sensitive to larger errors.
R² can be less than 0, indicating that the model's performance on the test set may be worse than directly predicting the test set mean.
MAPE may be unstable when the true value is 0 or close to 0.
8. Classification: Classification
Classification predicts discrete labels.
For example:
Spam / Not Spam
Fraud / Normal
Churn / Retained
Category A / B / C
Common classification algorithms
| model | Features |
|---|---|
| Logistic Regression | Simple, interpretable linear classifier |
| Decision Tree | Rule-based classification |
| Random Forest | Multiple tree integration |
| Gradient Boosting | Commonly used for table classification tasks |
| SVM | Classification based on decision boundaries |
| KNN | Classify based on nearby samples |
| Naive Bayes | Probabilistic model, commonly used in text classification |
Logistic Regression
Although the name contains Regression, it is mainly used for classification.
In the second category:
Among them:
Example:
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
X, y = make_classification(
n_samples=1000,
n_features=10,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
stratify=y,
random_state=42,
)
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_proba = model.predict_proba(X_test)
Among them:
y_pred # Prediction category
y_proba # Predicted probabilities for each category
For two categories:
positive_proba = y_proba[:, 1]
predict() outputs classes based on decision rules, while predict_proba() returns class probabilities.
Decision Threshold
In binary classification, a common threshold is 0.5:
y_pred = (positive_proba >= 0.5).astype(int)
However, actual business may need to adjust the threshold.
For example:
- Fraud detection: Hope to improve Recall.
- High-cost false positive scenario: Want to improve Precision.
Thresholds should be determined using validation data rather than iteratively adjusting based on the test set.
9. Classification model evaluation
Confusion Matrix
Two-class confusion matrix:
| Prediction Negative | Prediction Positive | |
|---|---|---|
| Actual Negative | TN | FP |
| Actual Positive | FN | TP |
Core indicators:
scikit-learn Metrics
from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score,
confusion_matrix,
classification_report,
)
accuracy_score(y_test, y_pred)
precision_score(y_test, y_pred)
recall_score(y_test, y_pred)
f1_score(y_test, y_pred)
confusion_matrix(y_test, y_pred)
print(classification_report(y_test, y_pred))
ROC-AUC and PR-AUC
from sklearn.metrics import (
roc_auc_score,
average_precision_score,
)
roc_auc_score(y_test, positive_proba)
average_precision_score(y_test, positive_proba)
- ROC-AUC: Measures the model's ability to distinguish positive and negative classes at different thresholds.
- Average Precision (AP): An indicator based on the Precision-Recall curve, often used for tasks that focus on a few positive classes.
AP is not exactly the same as PR-AUC calculated by trapezoidal integration.
Category imbalance
Assumptions:
normal transaction:99%
Fraudulent transactions:1%
All model predictions are normal:
Accuracy = 99%
Fraud Recall = 0%
Therefore, imbalanced classification cannot only look at Accuracy.
Common measures:
- Use Precision, Recall, F1, AP.
- Use
class_weight="balanced". - Adjust the classification threshold.
- Use appropriate sampling methods.
- Ensure that the validation set and test set are representative.
10. Clustering: Clustering
Clustering is unsupervised learning and does not require category labels to be provided in advance.
Mainly used for:
- Customer segmentation.
- Sample structure exploration.
- Spatial data grouping.
- Anomaly data exploration.
- Classification of experimental results.
K-Means
K-Means divides the sample into K clusters so that the sample is as close as possible to the center of the cluster it belongs to.
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)
model = KMeans(
n_clusters=3,
random_state=42,
n_init=10,
)
labels = model.fit_predict(X_scaled)
Common properties:
model.cluster_centers_
model.inertia_
model.labels_
n_clusters: Number of clusters.cluster_centers_: cluster center.inertia_: The sum of square distances from the sample to the cluster center to which it belongs.
K-Means is more suitable for compact, approximately spherical clusters.
DBSCAN
DBSCAN is a density-based clustering method.
from sklearn.cluster import DBSCAN
model = DBSCAN(
eps=0.5,
min_samples=5,
)
labels = model.fit_predict(X_scaled)
Main parameters:
eps: Neighborhood distance threshold.min_samples: The number of neighborhood samples required for the core point.
Features:
- K does not need to be specified in advance.
- Can identify some non-spherical clusters.
- The noise points can be labeled
-1. - Sensitive to distance scale and parameters.
Agglomerative Clustering
Hierarchical clustering:
from sklearn.cluster import AgglomerativeClustering
model = AgglomerativeClustering(n_clusters=3)
labels = model.fit_predict(X_scaled)
Building clusters based on hierarchical merging is suitable for exploring the hierarchical structure of data.
Comparison of common clustering algorithms
| algorithm | Whether to specify the number of clusters | Main features |
|---|---|---|
| K-Means | Yes | Fast and suitable for regular clusters |
| DBSCAN | No | Density clustering, supporting noise |
| HDBSCAN | No | The ability to adapt to different density structures is usually greater |
| Agglomerative | usually | hierarchical clustering |
Cluster evaluation
from sklearn.metrics import silhouette_score
score = silhouette_score(X_scaled, labels)
Silhouette Score measures how close a sample is to its cluster and how separated it is from other clusters.
The range is usually:
- Close to 1: tightness within clusters and separation between clusters.
- Close to 0: There may be overlap between clusters.
- Less than 0: Some samples may be closer to other clusters.
However, Silhouette Score cannot determine the best clustering solution alone, and it also needs to be combined with business significance.
11. Dimensionality Reduction: Dimensionality reduction
Dimensionality reduction is mainly used to reduce the number of features, remove some redundant information, and visualize high-dimensional data.
PCA
Principal Component Analysis: Principal component analysis.
PCA looks for the orthogonal direction that explains the maximum variance in the data.
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X_scaled)
Common properties:
pca.components_
pca.explained_variance_ratio_
For example:
pca.explained_variance_ratio_.sum()
Indicates the proportion of total variance explained by the retained principal components.
PCA is a linear dimensionality reduction method that is sensitive to input feature scale.
t-SNE
from sklearn.manifold import TSNE
X_2d = TSNE(
n_components=2,
random_state=42,
).fit_transform(X_scaled)
t-SNE is mainly used for two-dimensional or three-dimensional visualization of high-dimensional data.
Need to pay attention to:
- The inter-cluster distances on the t-SNE graph do not necessarily have direct interpretive meaning.
- The results depend on parameters and randomness.
- All relationships in real high-dimensional spaces should not be judged directly from two-dimensional projections.
12. Cross-validation: Cross Validation
The result of a single Train/Test Split may be affected by random partitioning.
K-Fold Cross-validation divides the training data into K parts, and selects one part in turn as the verification set.
Fold 1: [Validation] [Train] [Train] [Train] [Train]
Fold 2: [Train] [Validation] [Train] [Train] [Train]
Fold 3: [Train] [Train] [Validation] [Train] [Train]
...
Example:
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(random_state=42)
scores = cross_val_score(
model,
X_train,
y_train,
cv=5,
scoring="f1",
)
print(scores.mean())
print(scores.std())
Common cross-validation methods
| method | Applicable scenarios |
|---|---|
| KFold | Ordinary sample |
| StratifiedKFold | Classification, maintaining category proportions |
| GroupKFold | The same set of samples cannot span training and validation |
| TimeSeriesSplit | time series |
Cross-validation should be performed on the training data, with an independent test set retained until the final evaluation stage.
13. Hyperparameter Tuning: Hyperparameter optimization
Hyperparameters include:
Random Forest:
n_estimators
max_depth
min_samples_leaf
SVM:
C
gamma
kernel
K-Means:
n_clusters
GridSearchCV
Traverse the specified parameter combinations:
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(random_state=42)
param_grid = {
"n_estimators": [100, 200],
"max_depth": [5, 10, None],
}
search = GridSearchCV(
model,
param_grid,
cv=5,
scoring="f1",
n_jobs=-1,
)
search.fit(X_train, y_train)
print(search.best_params_)
print(search.best_score_)
RandomizedSearchCV
Randomly sample from a parametric distribution:
from sklearn.model_selection import RandomizedSearchCV
search = RandomizedSearchCV(
model,
param_distributions={
"n_estimators": [100, 200, 300],
"max_depth": [5, 10, 20, None],
},
n_iter=8,
cv=5,
scoring="f1",
random_state=42,
)
Difference:
| method | Features |
|---|---|
| GridSearchCV | Iterate through all specified combinations |
| RandomizedSearchCV | Randomly try a limited number of combinations |
When the parameter space is large, random search usually saves computational budget.
Parameters in Pipeline are accessed using double underscores:
param_grid = {
"classifier__C": [0.1, 1, 10]
}
14. Overfitting, Underfitting and Data Leakage
Underfitting: Underfitting
The model is too simple and cannot learn data patterns.
Performance:
Train Score: Low
Validation Score: Low
Possible reasons:
- Not enough features.
- Model complexity is too low.
- Regularization is too strong.
Overfitting: Overfitting
The model over-adapts to the training samples and has poor generalization ability.
Performance:
Train Score: High
Validation Score: Low
Common solution directions:
- Add valid data.
- Reduce model complexity.
- Use regularization.
- Limit decision tree depth.
- Use cross validation.
- Improve feature and data quality.
Data Leakage: Data leakage
Data Leakage is a very serious problem in machine learning practice.
For example, execute before splitting the data:
# Error example
X_scaled = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y,
)
StandardScaler Statistics have been calculated using the entire data set, including future test data.
The correct way is to split first and then fit the preprocessing only on the training data.
It is more recommended to use Pipeline automatic management.
Also avoid:
- Use future information as current predictive features.
- Use the target variable to derive predictive features.
- The same user's data was leaked to different collections.
- Iteratively select models using the test set.
- Feature selection is performed on the entire data in advance outside of Cross-validation.
The official documentation lists inconsistent preprocessing and data leakage as important FAQs for scikit-learn.
15. Feature Selection and Feature Importance
Feature selection
Common methods:
| method | Purpose |
|---|---|
| VarianceThreshold | Remove low variance features |
| SelectKBest | Select features based on statistical scores |
| RFE | Recursively delete unimportant features |
| SelectFromModel | Select based on feature importance of the trained model |
For example:
from sklearn.feature_selection import SelectKBest, f_classif
selector = SelectKBest(
score_func=f_classif,
k=5,
)
X_selected = selector.fit_transform(X_train, y_train)
Feature selection must also be placed within the training data, and Pipeline should be included in cross-validation.
Feature Importance
Tree models typically provide:
model.feature_importances_
But this importance metric may be biased toward certain feature types.
A more general way is Permutation Importance:
from sklearn.inspection import permutation_importance
result = permutation_importance(
model,
X_test,
y_test,
n_repeats=10,
random_state=42,
)
It measures the dependence of a feature on the current prediction by scrambling a feature and observing the degree to which the model score drops.
Note: Feature Importance does not equal causal impact.
16. Model saving and loading
After training is completed, the model can be saved using joblib.
import joblib
joblib.dump(model, "model.joblib")
Loading:
model = joblib.load("model.joblib")
If using Pipeline, the entire Pipeline should be saved:
joblib.dump(pipeline, "pipeline.joblib")
This avoids missing preprocessing steps when making predictions.
Note:
- Only load model files from trusted sources.
joblibis based on the Pickle mechanism and may execute arbitrary code by loading malicious files.- Model files are not guaranteed to be completely compatible between different scikit-learn versions.
- The training data version, feature structure, dependency version and model parameters should also be recorded.
17. Complete example: Classification model training
Below is a complete example including data splitting, preprocessing, training, cross-validation and evaluation.
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import (
train_test_split,
cross_val_score,
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
classification_report,
roc_auc_score,
)
# 1. Load data
dataset = load_breast_cancer(as_frame=True)
X = dataset.data
y = dataset.target
# 2. Split training set and test set
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
stratify=y,
random_state=42,
)
# 3. Definition Pipeline
pipeline = Pipeline([
("scaler", StandardScaler()),
("classifier", LogisticRegression(max_iter=1000)),
])
# 4. cross validation
scores = cross_val_score(
pipeline,
X_train,
y_train,
cv=5,
scoring="roc_auc",
)
print("CV ROC-AUC:", scores.mean())
# 5. Train the final model
pipeline.fit(X_train, y_train)
# 6. Forecast
y_pred = pipeline.predict(X_test)
y_proba = pipeline.predict_proba(X_test)[:, 1]
# 7. Assessment
print(classification_report(y_test, y_pred))
print("ROC-AUC:", roc_auc_score(y_test, y_proba))
# 8. save
import joblib
joblib.dump(pipeline, "classifier.joblib")
This example reflects standard practice for scikit-learn:
Data
↓
Train/Test Split
↓
Pipeline
├── StandardScaler
└── LogisticRegression
↓
Cross-validation
↓
Final Fit
↓
Prediction
↓
Metrics
↓
Save Model
18. How to choose common models
| Task | It is recommended to try it first | Try further |
|---|---|---|
| continuous numerical prediction | LinearRegression / Ridge | RandomForestRegressor、Gradient Boosting |
| Two categories | LogisticRegression | RandomForest、Gradient Boosting |
| Multiple categories | LogisticRegression、RandomForest | SVM、Gradient Boosting |
| Customer segmentation | KMeans | DBSCAN、HDBSCAN |
| Anomaly detection | IsolationForest | LocalOutlierFactor |
| Dimensionality reduction | PCA | t-SNE (visualization) |
| Time series feature modeling | Regression model + Lag Features | Specialized time series models |
These are just common starting points, there is no best algorithm for all data sets.
For tabular supervised learning in data analysis, it is recommended to always build a simple Baseline first, and then compare whether the complex model really brings improvement.
Summary
scikit-learn The most important knowledge can be divided into six groups:
| Classification | core content |
|---|---|
| Basic interface | Estimator、fit、predict、transform、score |
| Data processing | Imputer、Scaler、Encoder、ColumnTransformer |
| Model training | Regression、Classification、Clustering |
| Evaluation indicators | MAE、RMSE、R²、Precision、Recall、F1、ROC-AUC |
| Model selection | Train/Test Split、Cross-validation、GridSearchCV |
| engineering practice | Pipeline、Data Leakage、Overfitting、Model Persistence |
Need to focus on mastering:
- Pipeline: Organize data preprocessing and model training into reusable processes to avoid data leakage.
- Regression / Classification / Clustering: Understand the goals, common algorithms and outputs of the three tasks.
- Metrics: Different tasks use different indicators, you cannot just look at Accuracy or R².
- Cross-validation: Estimate model generalization performance and assist in hyperparameter selection.
- Data Leakage: Ensure that the test set and future information are not involved in model training and parameter selection.
- model comparison: Build a simple Baseline first, and then determine whether the complex model is worth using.