Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Sklearn Machine Learning Models

Sklearn Machine Learning Models

Machine learning models are the core tools for automated data analysis, pattern recognition, and prediction.

Depending on the task type, machine learning models are usually divided into:

This section will introduce these common machine learning models in detail and explain how to evaluate and optimize them.


1. Classification models

Classification is one of the most common problems in machine learning, whose goal is to map input data to discrete class labels.

Common classification models include:

Logistic Regression

Although the name Logistic Regression contains "regression", its essence isa probabilistic classification model, commonly used for binary classification problems.

Its core idea is:

It can be expressed in the form:

The core formula of logistic regression is:

scikit-learn implementation:

Example

from

sklearn.

linear_model

import

LogisticRegression

from

sklearn.

model_selection

import

train_test_split

Assume X is the feature matrix and y is the label

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

model

=

LogisticRegression

(

)

model.

fit

(

X_train

,

y_train

)

Predict

y_pred

=

model.

predict

(

X_test

)

K-Nearest Neighbors (KNN)

K-Nearest Neighbors (KNN) is an instance-based learning method. When predicting, it calculates the distance between the sample to be predicted and all samples in the training set, selects the K nearest neighbors, and predicts based on the labels of the neighbors.

Main parameters:

scikit-learn implementation:

Example

from

sklearn.

neighbors

import

KNeighborsClassifier

from

sklearn.

model_selection

import

train_test_split

Assume X is the feature matrix and y is the label

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

model

=

KNeighborsClassifier

(

n_neighbors

=

3

)

model.

fit

(

X_train

,

y_train

)

Predict

y_pred

=

model.

predict

(

X_test

)

Support Vector Machine (SVM)

Support Vector Machine is a powerful classification model, especially suitable for high-dimensional data.

The basic idea of SVM is to find a hyperplane that maximizes the margin between sample points of different classes. For non-linearly separable data, SVM uses the kernel trick to map the data into a high-dimensional space and find a separating hyperplane.

Kernel functions:

scikit-learn implementation:

Example

from

sklearn.

svm

import

SVC

from

sklearn.

model_selection

import

train_test_split

Assume X is the feature matrix and y is the label

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

model

=

SVC

(

kernel

=

'linear'

)

 

Use the linear kernel

model.

fit

(

X_train

,

y_train

)

Predict

y_pred

=

model.

predict

(

X_test

)

Decision Tree and Random Forest

A decision tree is a tree-structured classification model that splits data to finally divide it into different categories. Random forest builds multiple decision trees and decides the final prediction result through voting or averaging.

Decision TreeBy selecting the optimal feature for data partitioning, the selection criterion is usually information gain or Gini coefficient.

Random ForestEnsemble of multiple decision trees reduces overfitting and improves model accuracy. It increases model diversity by introducing randomness (such as randomly selecting features and randomly selecting data subsets).

scikit-learn implementation:

Example

from

sklearn.

tree

import

DecisionTreeClassifier

from

sklearn.

ensemble

import

RandomForestClassifier

from

sklearn.

model_selection

import

train_test_split

Assume X is the feature matrix and y is the label

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

Decision Tree

dt_model

=

DecisionTreeClassifier

(

)

dt_model.

fit

(

X_train

,

y_train

)

Random Forest

rf_model

=

RandomForestClassifier

(

n_estimators

=

100

)

rf_model.

fit

(

X_train

,

y_train

)

Predict

dt_pred

=

dt_model.

predict

(

X_test

)

rf_pred

=

rf_model.

predict

(

X_test

)


2. Regression models

The goal of a regression problem is to predict a continuous output variable. Common regression models include linear regression, ridge regression, and Lasso regression.

Linear Regression

Linear regression predicts the target variable by fitting a straight line. Its core assumption is that there is a linear relationship between the features and the target variable.

For a simple linear regression problem, the model can be expressed as:

scikit-learn implementation:

Example

from

sklearn.

linear_model

import

LinearRegression

from

sklearn.

model_selection

import

train_test_split

Suppose X is the feature matrix and y is the target variable

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

model

=

LinearRegression

(

)

model.

fit

(

X_train

,

y_train

)

Predict

y_pred

=

model.

predict

(

X_test

)

Ridge Regression

Ridge regression is a variant of linear regression that uses L2 regularization to constrain model complexity and avoid overfitting. By penalizing the magnitude of regression coefficients, ridge regression better handles multicollinearity.

scikit-learn implementation:

Example

from

sklearn.

linear_model

import

Ridge

model

=

Ridge

(

alpha

=

1.0

)

 

alpha is the regularization parameter

model.

fit

(

X_train

,

y_train

)

Predict

y_pred

=

model.

predict

(

X_test

)

Lasso Regression

Lasso regression is also a form of linear regression that uses L1 regularization to penalize the regression coefficients. Unlike ridge regression, Lasso compresses some regression coefficients to zero, thereby achieving feature selection.

scikit-learn implementation:

Example

from

sklearn.

linear_model

import

Lasso

model

=

Lasso

(

alpha

=

0.1

)

 

alpha is the regularization parameter

model.

fit

(

X_train

,

y_train

)

Predict

y_pred

=

model.

predict

(

X_test

)


3. Clustering models

Clustering is an unsupervised learning method whose goal is to divide objects in a dataset into different groups (or clusters) so that objects in the same cluster are as similar as possible, while objects in different clusters are as different as possible.

K-Means

K-Means is a common clustering algorithm whose goal is to divide data into K clusters and optimize the cluster partition by minimizing the distance between each data point and its cluster center.

scikit-learn implementation:

Example

from

sklearn.

cluster

import

KMeans

Suppose X is the feature matrix

model

=

KMeans

(

n_clusters

=

3

)

model.

fit

(

X

)

Get cluster labels

labels

=

model.

predict

(

X

)

DBSCAN (Density-Based Clustering)

DBSCAN (Density-Based Spatial Clustering of Applications with Noise) is a density-based clustering algorithm that clusters by finding regions of relatively high density and does not require specifying the number of clusters in advance.

scikit-learn implementation:

Example

from

sklearn.

cluster

import

DBSCAN

Suppose X is the feature matrix

model

=

DBSCAN

(

eps

=

0.5

,

min_samples

=

5

)

model.

fit

(

X

)

Get cluster labels

labels

=

model.

labels_

Hierarchical Clustering

Hierarchical clustering is a clustering method that recursively merges or splits clusters. Common hierarchical clustering methods include agglomerative clustering(Agglomerative) and divisive clustering (Divisive).

scikit-learn implementation:

Example

from

sklearn.

cluster

import

AgglomerativeClustering

Suppose X is the feature matrix

model

=

AgglomerativeClustering

(

n_clusters

=

3

)

labels

=

model.

fit_predict

(

X

)


4. Model evaluation and selection

In machine learning, after model training is completed, reasonable evaluation methods are needed to judge the model's generalization ability and select the best-performing model.

Common evaluation methods include:

Classification evaluation metrics

In classification problems, commonly used evaluation metrics include:

They reflect model performance from different perspectives.

Explanation of each metric:

F1 score

The harmonic mean of Precision and Recall:

Used to balance precision and recall.

scikit-learn implementation:

Example

from

sklearn.

metrics

import

accuracy_score

,

precision_score

,

recall_score

,

f1_score

accuracy

=

accuracy_score

(

y_test

,

y_pred

)

precision

=

precision_score

(

y_test

,

y_pred

)

recall

=

recall_score

(

y_test

,

y_pred

)

f1

=

f1_score

(

y_test

,

y_pred

)

print

(

f

"Accuracy: {accuracy}"

)

print

(

f

"Precision: {precision}"

)

print

(

f

"Recall: {recall}"

)

print

(

f

"F1 Score: {f1}"

)

Holdout evaluation (training set / test set split)

The most common and intuitive evaluation method is to divide the dataset into:

This method is simple and efficient, suitable for understanding model effects at the introductory stage.

Cross Validation

Cross validation trains and tests by dividing the dataset multiple times, thereby obtaining more stable and reliable model performance evaluation results.

A common approach is K-fold cross validation:

Example

from

sklearn.

model_selection

import

cross_val_score

from

sklearn.

linear_model

import

LogisticRegression

model

=

LogisticRegression

(

)

scores

=

cross_val_score

(

model

,

X

,

y

,

cv

=

5

)

print

(

"Cross-validation scores:"

,

scores

)

print

(

"Mean score:"

,

scores.

mean

(

)

)

In real projects, either the holdout method or cross validation is usually used; there is no need to mix both.

Grid search tuning (GridSearchCV)

Model performance is often greatly affected by hyperparameter settings.
Grid search automatically finds the optimal configuration by traversing parameter combinations.

Combined with cross validation, the tuning results become more robust.

Example

from

sklearn.

model_selection

import

GridSearchCV

from

sklearn.

svm

import

SVC

parameters

=

{

   

'kernel'

:

[

'linear'

,

'rbf'

]

,

   

'C'

:

[

1

,

10

,

100

]

}

model

=

SVC

(

)

grid_search

=

GridSearchCV

(

    model

,

    parameters

,

    cv

=

5

)

grid_search.

fit

(

X

,

y

)

print

(

"Best parameters:"

,

grid_search.

best_params_

)

print

(

"Best score:"

,

grid_search.

best_score_

)