传统机器学习算法

&emsp’机器学习算法有很多种,常用的包括线性回归、逻辑回归、决策树、支持向量机、K-近邻、朴素贝叶斯以及神经网络等。下面,我们分别介绍这些算法及其公式,并提供应用示例代码。

1. 线性回归(Linear Regression)

公式
y = β 0 + β 1 x 1 + β 2 x 2 + ⋯ + β n x n + ϵ y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_n x_n + \epsilon y=β0+β1x1+β2x2++βnxn+ϵ

其中, y y y 是目标变量, x i x_i xi 是特征, β i \beta_i βi 是回归系数, ϵ \epsilon ϵ 是误差项。

解释
线性回归用于预测一个连续值,它通过找到特征和目标变量之间的线性关系来做出预测。

应用例子

import numpy as np
from sklearn.linear_model import LinearRegression

# 生成模拟数据
X = np.random.rand(100, 1)
y = 2 * X + np.random.randn(100, 1)

# 训练线性回归模型
model = LinearRegression()
model.fit(X, y)

# 预测新数据
X_new = np.array([[0.5]])
y_pred = model.predict(X_new)

# 设置阈值
threshold = 1

# 分类
if y_pred > threshold:
    print("正类")
else:
    print("负类")

2. 逻辑回归(Logistic Regression)

公式
P ( y = 1 ∣ x ) = 1 1 + e − ( β 0 + β 1 x 1 + β 2 x 2 + ⋯ + β n x n ) P(y=1|x) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_n x_n)}} P(y=1∣x)=1+e(β0+β1x1+β2x2++βnxn)1

解释
逻辑回归用于二分类问题,通过逻辑函数将线性回归的输出映射到 (0, 1) 区间。

应用例子

import numpy as np
from sklearn.linear_model import LogisticRegression

# 示例数据
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([0, 0, 0, 1, 1])

# 训练模型
model = LogisticRegression()
model.fit(X, y)

# 预测
y_pred = model.predict(X)
print(y_pred)

3. 决策树(Decision Tree)

公式
决策树没有具体的公式,它通过一系列条件判断来对数据进行分类或回归。

解释
决策树是一种树形结构的模型,它通过一系列的决策规则将数据分成不同的组。

应用例子

from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
from sklearn import tree

# 示例数据
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([0, 0, 0, 1, 1])

# 训练模型
model = DecisionTreeClassifier()
model.fit(X, y)

# 可视化
fig, ax = plt.subplots(figsize=(10, 10))
tree.plot_tree(model, filled=True, ax=ax)
plt.show()

4. 支持向量机(Support Vector Machine, SVM)

公式
对于线性 SVM,决策边界是:
w ⋅ x + b = 0 w \cdot x + b = 0 wx+b=0

解释
SVM 通过找到一个最优超平面来将数据点分成不同的类别,最大化支持向量到超平面的最小距离。

应用例子

from sklearn import svm

# 示例数据
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([0, 0, 0, 1, 1])

# 训练模型
model = svm.SVC(kernel='linear')
model.fit(X, y)

# 预测
y_pred = model.predict(X)
print(y_pred)

5. K-近邻(K-Nearest Neighbors, KNN)

公式
没有具体公式,KNN 通过计算测试点与训练点之间的距离来进行分类。

解释
KNN 是一种基于实例的学习方法,通过多数表决来决定测试点的类别。

应用例子

from sklearn.neighbors import KNeighborsClassifier

# 示例数据
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([0, 0, 0, 1, 1])

# 训练模型
model = KNeighbors
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值