一、16 大 AI 算法总览

  1. 线性回归(Linear Regression)
  2. 逻辑回归(Logistic Regression)
  3. 朴素贝叶斯(Naive Bayes)
  4. K 近邻 KNN
  5. 支持向量机 SVM
  6. 决策树 Decision Tree
  7. 随机森林 Random Forest
  8. XGBoost(梯度提升)
  9. K-Means 聚类
  10. DBSCAN 密度聚类
  11. PCA 主成分分析(降维)
  12. CNN 卷积神经网络
  13. LSTM 长短期记忆网络
  14. Transformer
  15. DQN 深度 Q 网络(强化学习)
  16. GCN 图卷积网络

AI 16 大算法【原理详解 + 完整可运行 Python 编程方案】

环境统一:Python3.8+,依赖:numpy pandas scikit-learn xgboost torch torchvision torch_geometric stable-baselines3 matplotlib 安装命令:

pip install numpy pandas scikit-learn xgboost torch matplotlib stable-baselines3 gym

说明:代码为最小可用 demo,可直接复制运行;工业项目在此基础上增加交叉验证、特征工程、日志、模型保存部署。

1. 线性回归 Linear Regression(监督 - 回归)

原理

拟合 \(y=w_0 + w_1x_1+...+w_nx_n\),最小化 MSE 均方误差,用于连续值预测;可加入 L1 (Lasso)/L2 (Ridge) 正则防过拟合。

适用:销量、房价预测

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# 构造数据
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2,4,5,7,8])

# 训练
model = LinearRegression()
model.fit(X, y)
y_pred = model.predict(X)

print(f"系数w: {model.coef_}, 截距b: {model.intercept_}")
print(f"MSE: {mean_squared_error(y,y_pred):.2f}, R2: {r2_score(y,y_pred):.2f}")

2. 逻辑回归 Logistic Regression(监督 - 二分类)

原理

线性结果送入 sigmoid 转为 0~1 概率,损失交叉熵;常用于二分类基线,金融风控首选可解释模型。

适用:违约预测、点击预估

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score

X = np.array([[1], [2], [3], [4], [5], [6]])
y = np.array([0,0,0,1,1,1])

model = LogisticRegression()
model.fit(X, y)
y_pred_prob = model.predict_proba(X)[:,1]

print(f"AUC: {roc_auc_score(y, y_pred_prob):.2f}")
print("预测类别:", model.predict(X))

3. 朴素贝叶斯 Naive Bayes(监督 - 分类)

原理

贝叶斯公式 \(P(Y|X)=\frac{P(X|Y)P(Y)}{P(X)}\),假设特征独立;文本场景多用多项式朴素贝叶斯。

适用:垃圾短信、文本情感分类

from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer

texts = ["购买理财产品","中奖请转账","正常聊天","汇款领奖"]
y = [0,1,0,1]

vec = CountVectorizer()
X = vec.fit_transform(texts)
model = MultinomialNB()
model.fit(X,y)

test = vec.transform(["恭喜您获得大奖"])
print("预测类别(1垃圾):", model.predict(test))

4. K 近邻 KNN(监督 - 分类 / 回归)

原理

计算样本距离 (欧氏),取最近 K 个样本投票;惰性学习,无训练过程,预测慢。

适用:小样本分类

from sklearn.neighbors import KNeighborsClassifier
import numpy as np

X = np.array([[1,2],[2,3],[3,4],[8,9],[9,10]])
y = np.array([0,0,0,1,1])

model = KNeighborsClassifier(n_neighbors=3)
model.fit(X,y)
print(model.predict([[4,5]]))

5. SVM 支持向量机(监督 - 分类)

原理

寻找最大间隔超平面,核函数 (RBF) 映射高维解决非线性;中小样本高维数据效果好。

适用:文本分类、图像小样本识别

from sklearn.svm import SVC
import numpy as np

X = np.array([[1,2],[2,1],[3,4],[4,3]])
y = np.array([0,0,1,1])

model = SVC(kernel="rbf")
model.fit(X,y)
print(model.predict([[2.5,2.5]]))

6. 决策树 Decision Tree(监督 - 分类 / 回归)

原理

基于信息增益 / 基尼系数递归分裂节点,规则透明;极易过拟合,必须剪枝。

适用:规则挖掘、可解释需求场景

from sklearn.tree import DecisionTreeClassifier
import numpy as np

X = np.array([[1,2],[2,3],[5,6],[7,8]])
y = np.array([0,0,1,1])

model = DecisionTreeClassifier(max_depth=2) # 限制深度防过拟合
model.fit(X,y)
print(model.predict([[4,5]]))

7. 随机森林 Random Forest(Bagging 集成)

原理

并行训练多棵独立决策树,样本 + 特征随机采样,投票输出结果;可输出特征重要度。

适用:表格数据分类回归

from sklearn.ensemble import RandomForestClassifier
import numpy as np

X = np.array([[1,2],[2,3],[3,4],[6,7],[8,9]])
y = np.array([0,0,0,1,1])

model = RandomForestClassifier(n_estimators=10, max_depth=2, random_state=1)
model.fit(X,y)
print("特征重要性:", model.feature_importances_)
print(model.predict([[5,6]]))

8. XGBoost(Boosting 梯度提升,工业表格标杆)

原理

串行训练,每棵树拟合残差,二阶泰勒展开优化损失,内置正则;表格数据竞赛首选。

适用:风控、推荐排序、销量预测

import xgboost as xgb
import numpy as np
from sklearn.metrics import accuracy_score

X = np.array([[1,2],[2,3],[3,4],[7,8],[8,9]])
y = np.array([0,0,0,1,1])

model = xgb.XGBClassifier(n_estimators=5, max_depth=2, use_label_encoder=False, eval_metric="logloss")
model.fit(X,y)
pred = model.predict(X)
print(f"准确率:{accuracy_score(y,pred):.2f}")

9. K-Means(无监督聚类)

原理

预先指定 K,迭代更新质心,最小化簇内距离;肘部法则 / 轮廓系数选 K。

适用:用户分群、商品聚类

from sklearn.cluster import KMeans
import numpy as np

X = np.array([[1,2],[2,2],[8,9],[9,8],[3,2]])
model = KMeans(n_clusters=2, random_state=0, n_init="auto")
model.fit(X)
print("聚类标签:", model.labels_)
print("聚类中心:", model.cluster_centers_)

10. DBSCAN(密度聚类,无监督)

原理

基于样本密度自动成团,自动识别噪声点,不需要预先指定聚类数量;适合不规则簇。

适用:异常检测、地理点聚类

from sklearn.cluster import DBSCAN
import numpy as np

X = np.array([[1,2],[2,3],[3,2],[10,11],[11,10],[50,50]])
model = DBSCAN(eps=3, min_samples=2)
model.fit(X)
# -1代表噪声点
print("聚类标签(-1=噪声):", model.labels_)

11. PCA 主成分分析(无监督降维)

原理

正交变换,保留数据最大方差,压缩特征维度,消除多重共线性。

适用:高维特征压缩、数据可视化

from sklearn.decomposition import PCA
import numpy as np

X = np.array([[1,2,3],[2,3,4],[3,4,5],[8,9,10]])
pca = PCA(n_components=2)
X_new = pca.fit_transform(X)
print("降维后数据:\n", X_new)
print("各主成分方差占比:", pca.explained_variance_ratio_)

12. CNN 卷积神经网络(深度学习 - 视觉)

原理

卷积核提取局部空间特征、池化降采样、参数共享;适合图像网格结构数据。

适用:图像分类、OCR、目标检测骨干网络

import torch
import torch.nn as nn
import torch.nn.functional as F

class SimpleCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 16, 3, 1)
        self.pool = nn.MaxPool2d(2,2)
        self.fc1 = nn.Linear(16*13*13, 10)
    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = x.view(x.size(0), -1)
        return self.fc1(x)

model = SimpleCNN()
# 模拟输入:batch=2,通道1,28*28灰度图
dummy_img = torch.randn(2,1,28,28)
out = model(dummy_img)
print("CNN输出shape:", out.shape)

13. LSTM 长短期记忆网络(深度学习 - 时序)

原理

输入门、遗忘门、输出门,解决传统 RNN 梯度消失,捕捉长期时序依赖。

适用:时序预测、文本序列建模

import torch
import torch.nn as nn

class SimpleLSTM(nn.Module):
    def __init__(self, input_dim=1, hidden_dim=32):
        super().__init__()
        self.lstm = nn.LSTM(input_dim, hidden_dim, batch_first=True)
        self.linear = nn.Linear(hidden_dim,1)
    def forward(self, x):
        out, _ = self.lstm(x)
        return self.linear(out[:,-1,:])

model = SimpleLSTM()
# batch=3,序列长度10,特征维度1
seq = torch.randn(3,10,1)
pred = model(seq)
print("LSTM预测输出shape:", pred.shape)

14. Transformer(深度学习,自注意力)

原理

多头自注意力建模全局依赖,不再依赖时序循环;BERT/GPT/ViT 基础骨架。

下面是极简 Encoder 示例(完整大模型在此扩展)

import torch
import torch.nn as nn

# 极简Transformer Encoder示例
encoder_layer = nn.TransformerEncoderLayer(d_model=64, nhead=8, batch_first=True)
trans_encoder = nn.TransformerEncoder(encoder_layer, num_layers=2)

# batch=2,序列长15,特征64
src = torch.randn(2,15,64)
out = trans_encoder(src)
print("Transformer输出shape:", out.shape)

15. DQN 深度 Q 网络(强化学习)

原理

神经网络拟合 Q 价值函数,经验回放 + 目标网络,解决 Q-learning 高维状态问题;离散动作决策。

依赖:stable-baselines3,内置成熟 DQN 实现

import gym
from stable_baselines3 import DQN

env = gym.make("CartPole-v1")
model = DQN("MlpPolicy", env, learning_rate=1e-3, verbose=0)
model.learn(total_timesteps=10000)

obs, _ = env.reset()
for _ in range(200):
    action, _ = model.predict(obs)
    obs, reward, done, _, info = env.step(action)
    if done: break
env.close()
print("DQN 训练完成,完成CartPole平衡任务")

16. GCN 图卷积网络(图深度学习)

原理

聚合邻居节点特征,学习拓扑结构 + 节点属性;处理图结构数据(社交网络、知识图谱、团伙风控)

依赖:torch_geometric

pip install torch_geometric
import torch
import torch.nn as nn
from torch_geometric.nn import GCNConv

class SimpleGCN(nn.Module):
    def __init__(self, in_dim=3, hid_dim=16, out_dim=2):
        super().__init__()
        self.conv1 = GCNConv(in_dim, hid_dim)
        self.conv2 = GCNConv(hid_dim, out_dim)
    def forward(self, x, edge_index):
        x = torch.relu(self.conv1(x, edge_index))
        return self.conv2(x, edge_index)

model = SimpleGCN()
# 4个节点,每个节点3维特征
x = torch.randn(4,3)
# 边索引:无向图 0<->1,1<->2,2<->3
edge_index = torch.tensor([[0,1,2], [1,2,3]], dtype=torch.long)
out = model(x, edge_index)
print("GCN节点输出shape:", out.shape)

配套落地补充方案

通用工程化标准动作(所有算法都要加)

  1. 数据集划分:train_test_split,时序数据禁止随机打乱
  2. 标准化:StandardScaler / MinMaxScaler,训练集拟合,测试集 transform,杜绝数据泄露
  3. 交叉验证:GridSearchCV / Optuna超参寻优
  4. 模型持久化:
    • sklearn/xgb:joblib.dump(model, "model.pkl")
    • pytorch:torch.save(model.state_dict(), "model.pth")
  5. 推理封装:FastAPI 提供 http 接口,ONNX 做跨平台部署

选型 & 调优速记

  1. 表格业务优先:XGBoost/LightGBM,基线用逻辑回归 / 随机森林
  2. 图像任务:CNN → ViT(Transformer)
  3. 文本长序列:Transformer (BERT/GPT)
  4. 时序预测:LSTM / Temporal Transformer
  5. 关系网络、团伙识别:GCN/GraphSAGE
  6. 自动决策调度:DQN/PPO

更多推荐