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

Machine Learning Algorithms

Machine Learning Algorithms

Machine learning algorithms can be divided into categories such as supervised learning, unsupervised learning, and reinforcement learning.

Supervised Learning Algorithms:

Unsupervised Learning Algorithms:

Each algorithm has its suitable scenarios; in practice, the most appropriate machine learning algorithm can be chosen based on the characteristics of the data (such as whether labels exist and the dimensionality of the data).

Classification dimension Category Core Definition Typical algorithms Key Pros and Cons Applicable scenarios
Learning Method Supervised Learning Learn the input-to-output mapping from labeled data Logistic regression, SVM, decision tree, CNN, LSTM Pros: high prediction accuracy; cons: depends on high-quality labeled data Classification, regression, image recognition, text translation
Unsupervised learning Discover the inherent patterns in unlabeled data K-Means, PCA, DBSCAN, autoencoders Pros: no labeling needed; cons: weak interpretability of results Data clustering, dimensionality reduction, anomaly detection, user segmentation
Semi-supervised learning Train with a small amount of labeled data and a large amount of unlabeled data Semi-supervised SVM, label propagation algorithms Pros: lower labeling cost; cons: complex model design Medical image analysis, low-resource language NLP
Reinforcement Learning The model optimizes its policy through reward signals by interacting with the environment Q-Learning、DQN、PPO Pros: suitable for dynamic decision-making; cons: long training cycles Game AI, robot control, recommendation strategy optimization
Task objective Classification algorithms Predict discrete class labels Logistic regression, random forest, CNN Advantages: suitable for classification scenarios; Disadvantages: sensitive to class imbalance Spam detection, image classification, disease diagnosis
Regression algorithms Predict continuous numeric outputs Linear regression, ridge regression, XGBoost Advantages: outputs continuous values; Disadvantages: sensitive to outliers House price prediction, sales forecasting, temperature prediction
Clustering algorithms Group similar data into one cluster without labels K-Means, hierarchical clustering, DBSCAN Advantages: automatic grouping; Disadvantages: clustering quality depends on the distance metric Market segmentation, user profiling, anomaly detection
Dimensionality reduction algorithms Reduce feature dimensionality while preserving core information PCA、t-SNE、LDA Advantages: lower computational cost; Disadvantages: may lose some information Visualization of high-dimensional data, feature preprocessing
Model structure Linear models Assume a linear relationship between input and output Linear regression, logistic regression, ridge regression Advantages: highly interpretable and fast to train; Disadvantages: hard to fit nonlinear relationships Simple classification and regression, baseline model building
Tree Model Built on decision trees, handle nonlinear relationships Decision Tree, Random Forest, XGBoost, LightGBM Advantages: no feature normalization needed; Disadvantages: overly deep trees easily overfit Industrial-grade classification and regression, competition-level tasks
Neural network models Multi-layer neuron structures that automatically extract complex features ANN、CNN、RNN、Transformer Advantages: fit complex relationships; Disadvantages: require large amounts of data and computing power Image recognition, NLP, speech synthesis
Probabilistic models Based on probability and statistics theory, compute probability distributions Naive Bayes, Hidden Markov Model Advantages: solid theoretical foundation; Disadvantages: rely on strong assumptions Text classification, speech recognition, sequence labeling

Supervised Learning Algorithms

Linear Regression

Linear regression is an algorithm used for regression problems. It predicts a continuous output by learning the linear relationship between input features and the target value.

**Application scenarios:** predicting house prices, stock prices, etc.

The goal of linear regression is to find the best linear equation:

Next we use sklearn for a simple house price prediction:

Example

from

sklearn.

linear_model

import

LinearRegression

from

sklearn.

model_selection

import

train_test_split

import

pandas

as

pd

Suppose we have a simple house price dataset

data

=

{

   

'Area'

:

[

50

,

60

,

80

,

100

,

120

]

,

   

'House Price'

:

[

150

,

180

,

240

,

300

,

350

]

}

df

=

pd.

DataFrame

(

data

)

Features and labels

X

=

df

[

[

'Area'

]

]

y

=

df

[

'House Price'

]

Data splitting

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Train the linear regression model

model

=

LinearRegression

(

)

model.

fit

(

X_train

,

y_train

)

Predict

y_pred

=

model.

predict

(

X_test

)

print

(

f

"Predicted house price: {y_pred}"

)

The output is:

预测的房价: [180.8411215]

Logistic Regression

Logistic regression is an algorithm used for classification problems. Although its name contains "regression", it is used to handle binary classification problems.

Logistic regression predicts a class label by learning the relationship between input features and classes.

**Application scenarios:** spam classification, disease diagnosis (whether a disease is present).

The output of logistic regression is a probability value, indicating the probability that a sample belongs to a certain class.

The Sigmoid function is usually used:

Use logistic regression for a binary classification task:

Example

from

sklearn.

linear_model

import

LogisticRegression

from

sklearn.

datasets

import

load_iris

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

metrics

import

accuracy_score

Load the Iris dataset

iris

=

load_iris

(

)

X

=

iris.

data

y

=

iris.

target

Take only the first two classes for the binary classification task

X

=

X

[

y

!=

2

]

y

=

y

[

y

!=

2

]

Data splitting

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Train the logistic regression model

model

=

LogisticRegression

(

)

model.

fit

(

X_train

,

y_train

)

Predict

y_pred

=

model.

predict

(

X_test

)

Evaluate the model

print

(

f

"Classification accuracy: {accuracy_score(y_test, y_pred):.2f}"

)

The output is:

分类准确率: 1.00

Support Vector Machine (SVM)

Support Vector Machine is a commonly used classification algorithm. It maximizes the margin (Margin) between classes by constructing a hyperplane, minimizing classification error.

**Application scenarios:** text classification, face recognition, etc.

Use SVM for an iris classification task:

Example

from

sklearn.

svm

import

SVC

from

sklearn.

datasets

import

load_iris

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

metrics

import

accuracy_score

Load the Iris dataset

iris

=

load_iris

(

)

X

=

iris.

data

y

=

iris.

target

Data splitting

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

Train the SVM model

model

=

SVC

(

kernel

=

'linear'

)

model.

fit

(

X_train

,

y_train

)

Predict

y_pred

=

model.

predict

(

X_test

)

Evaluate the model

print

(

f

"SVM classification accuracy: {accuracy_score(y_test, y_pred):.2f}"

)

The output is:

SVM 分类准确率: 1.00

Decision Tree (Decision Tree)

A decision tree is a classification and regression method that makes decisions based on a tree structure. It uses a series of "judgment conditions" to determine which class a sample belongs to.

**Application scenarios:** customer classification, credit scoring, etc.

Use a decision tree for a classification task:

Example

from

sklearn.

tree

import

DecisionTreeClassifier

from

sklearn.

datasets

import

load_iris

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

metrics

import

accuracy_score

Load the Iris dataset

iris

=

load_iris

(

)

X

=

iris.

data

y

=

iris.

target

Data splitting

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)

Train the decision tree model

model

=

DecisionTreeClassifier

(

random_state

=

42

)

model.

fit

(

X_train

,

y_train

)

Predict

y_pred

=

model.

predict

(

X_test

)

Evaluate the model

print

(

f

"Decision tree classification accuracy: {accuracy_score(y_test, y_pred):.2f}"

)

The output is:



决策树分类准确率: 1.00


Unsupervised Learning Algorithms

K-means Clustering (K-means Clustering)

K-means is a centroid-based clustering algorithm that continuously adjusts the center of each cluster so that data points in each cluster are as close as possible to the cluster center.

**Application scenarios:** customer segmentation, market analysis, image compression.

Use K-means for customer segmentation:

Example

from

sklearn.

cluster

import

KMeans

from

sklearn.

datasets

import

make_blobs

import

matplotlib.

pyplot

as

plt

Generate a simple two-dimensional dataset

X

,

_

=

make_blobs

(

n_samples

=

300

,

centers

=

4

,

cluster_std

=

0.60

,

random_state

=

0

)

Train the K-means model

model

=

KMeans

(

n_clusters

=

4

)

model.

fit

(

X

)

Predict the clustering result

y_kmeans

=

model.

predict

(

X

)

Visualize the clustering result

plt.

scatter

(

X

[

:

,

0

]

,

X

[

:

,

1

]

,

c

=

y_kmeans

,

s

=

50

,

cmap

=

'viridis'

)

plt.

show

(

)

The output plot is shown below:

Principal Component Analysis (PCA)

PCA is a dimensionality reduction technique that uses linear transformation to convert data into a new coordinate system, so that most of the variance is concentrated in the first few principal components.

**Application scenarios:** image dimensionality reduction, feature selection, data visualization.

Use PCA to reduce dimensionality and visualize high-dimensional data:

Example

from

sklearn.

decomposition

import

PCA

from

sklearn.

datasets

import

load_iris

import

matplotlib.

pyplot

as

plt

Load the Iris dataset

iris

=

load_iris

(

)

X

=

iris.

data

y

=

iris.

target

Reduce to 2 dimensions

pca

=

PCA

(

n_components

=

2

)

X_pca

=

pca.

fit_transform

(

X

)

Visualize the result

plt.

scatter

(

X_pca

[

:

,

0

]

,

X_pca

[

:

,

1

]

,

c

=

y

,

cmap

=

'viridis'

)

plt.

title

(

'PCA of Iris Dataset'

)

plt.

show

(

)

The output plot is shown below:


Machine Learning Algorithms

Chinese Full Name Full English name Shorthand Core Application Scenarios
Traditional Machine Learning Algorithms
Decision Tree Decision Tree DT Classification, regression, feature importance analysis
Random Forest Random Forest RF Classification, regression, anomaly detection, feature selection
Logistic Regression Logistic Regression LR Binary classification tasks, probability prediction, credit scoring
Support Vector Machine Support Vector Machine SVM Classification, high-dimensional small-sample data, text classification
Naive Bayes Naive Bayes NB Text classification, spam detection, sentiment analysis
Gradient Boosted Trees Gradient Boosting Decision Tree GBDT Classification, regression, ranking tasks
Extreme Gradient Boosting Extreme Gradient Boosting XGBoost High-precision classification and regression, competition-level tasks, click-through rate prediction
Light Gradient Boosting Machine Light Gradient Boosting Machine LightGBM Large-scale data classification and regression, real-time prediction, recommendation systems
K-Nearest Neighbors algorithm K-Nearest Neighbor KNN Simple classification and regression, recommendation systems, anomaly detection
K-means clustering K-Means Clustering K-Means Data clustering, user segmentation, image segmentation
Principal Component Analysis Principal Component Analysis PCA Data dimensionality reduction, high-dimensional data visualization, feature denoising
Deep Learning Algorithms
Artificial Neural Network Artificial Neural Network ANN Simple classification and regression, baseline model validation
Convolutional neural networks Convolutional Neural Network CNN Image recognition, object detection, video analysis, medical image diagnosis
Recurrent neural networks Recurrent Neural Network RNN Sequence data processing, text generation, speech recognition
Long Short-Term Memory network Long Short-Term Memory LSTM Long-sequence text translation, speech synthesis, time series prediction
Gated Recurrent Unit Gated Recurrent Unit GRU Sequence classification, sentiment analysis, dialogue systems
Generative adversarial network Generative Adversarial Network GAN Image generation, style transfer, data augmentation, super-resolution reconstruction
Transformer Transformer Transformer Natural language translation, text summarization, multimodal tasks, large model infrastructure
Autoencoders Autoencoder AE Data compression, anomaly detection, feature extraction
Variational autoencoder Variational Autoencoder VAE Generative tasks, data denoising, image generation
Graph Neural Network Graph Neural Network GNN Social network analysis, molecular structure prediction, knowledge graph reasoning