Skip to content

Commit 7c3087f

Browse files
📝 Update Random Forest and K-Means documentation with new content and visualizations
- Enhanced the Random Forest section with detailed explanations of decision tree generation and classification processes, including handling of outliers. - Added a new section on Gradient Boosting, explaining its principles, working mechanism, and providing code examples. - Updated K-Means documentation to include an interactive animation for better visualization of the clustering process, along with a new section on DBSCAN, detailing its algorithm and applications. - Improved overall clarity and structure of the documentation to facilitate understanding of clustering algorithms.
1 parent 28ad3de commit 7c3087f

File tree

2 files changed

+234
-11
lines changed

2 files changed

+234
-11
lines changed

docs/docs/机器学习/传统算法/K均值算法.md

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,19 @@ $
4646

4747
以此类推
4848

49+
### 动画演示
50+
51+
下面的动画使用10*10的网格模拟图片,通过修改网格颜色表示分类。
52+
53+
通过绿色表示样本分类1,深绿色表示其簇中心点,蓝色表示样本分类2,深蓝色表示其簇中心点。
54+
55+
初始簇中心点1在左上角,簇中心点2在中间。
56+
57+
每次迭代停顿5秒。
58+
4959
<details>
5060
<summary>点击查看动画</summary>
51-
``` jsx live
61+
``` jsx live
5262
function KMeansAnimation() {
5363
const gridSize = 10;
5464

@@ -59,6 +69,7 @@ function KMeansAnimation() {
5969
]);
6070
const [step, setStep] = React.useState(0);
6171
const [iteration, setIteration] = React.useState(0);
72+
const [ready, setReady] = React.useState(false);
6273

6374
React.useEffect(() => {
6475
const generateAllGridPoints = () => {
@@ -76,14 +87,21 @@ function KMeansAnimation() {
7687
};
7788

7889
setDataPoints(generateAllGridPoints());
90+
91+
// 初始化后等待5秒再开始第一次迭代
92+
const initialTimer = setTimeout(() => {
93+
setReady(true);
94+
}, 5000);
95+
96+
return () => clearTimeout(initialTimer);
7997
}, []);
8098

8199
const distance = (point1, point2) => {
82100
return Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2));
83101
};
84102

85103
React.useEffect(() => {
86-
if (dataPoints.length === 0) return;
104+
if (dataPoints.length === 0 || !ready) return;
87105

88106
const timer = setTimeout(() => {
89107
if (step === 0) {
@@ -116,11 +134,17 @@ function KMeansAnimation() {
116134

117135
setStep(0);
118136
setIteration(prev => prev + 1);
137+
138+
// 每次迭代完成后暂停5秒
139+
setReady(false);
140+
setTimeout(() => {
141+
setReady(true);
142+
}, 5000);
119143
}
120144
}, 1000);
121145

122146
return () => clearTimeout(timer);
123-
}, [step, dataPoints, centroids]);
147+
}, [step, dataPoints, centroids, ready]);
124148

125149
const renderGrid = () => {
126150
const grid = [];
@@ -167,7 +191,10 @@ function KMeansAnimation() {
167191
return (
168192
<div style={{display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '16px'}}>
169193
<h2 style={{fontSize: '1.25rem', fontWeight: 'bold', marginBottom: '16px'}}>K-Means 聚类算法可视化</h2>
170-
<div style={{marginBottom: '16px'}}>迭代次数: {iteration}</div>
194+
<div style={{marginBottom: '16px'}}>
195+
迭代次数: {iteration}
196+
{!ready && <span style={{marginLeft: '10px', color: '#718096'}}>等待中...</span>}
197+
</div>
171198
<div style={{
172199
display: 'grid',
173200
gridTemplateColumns: 'repeat(10, 1fr)',
@@ -197,8 +224,6 @@ function KMeansAnimation() {
197224
</div>
198225
);
199226
}
200-
201-
export default KMeansAnimation;
202227
```
203228
</details>
204229

@@ -380,3 +405,22 @@ plt.title('Quantized image (64 colors, Random)')
380405
plt.imshow(recreate_image(codebook_random, labels_random, w, h))
381406

382407
```
408+
409+
### DBscan
410+
411+
[DBSCAN (Density-Based Spatial Clustering of Applications with Noise) ](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html#)
412+
413+
是一种流行的密度聚类算法。它的主要特点是:
414+
415+
1. 基于密度的聚类方法,能够发现任意形状的聚类
416+
2. 不需要预先指定聚类数量
417+
3. 能够识别噪声点
418+
4. 通过两个参数控制:邻域半径ε和最小点数MinPts
419+
420+
DBSCAN的基本原理是找出密度连接的区域,形成聚类。它将数据点分为三类:
421+
- 核心点:在其ε-邻域内至少有MinPts个点
422+
- 边界点:在某个核心点的ε-邻域内,但其自身ε-邻域内的点数少于MinPts
423+
- 噪声点:既不是核心点也不是边界点的点
424+
425+
DBSCAN算法特别适合处理包含噪声和形状不规则聚类的数据集,广泛应用于空间数据库、地理信息系统、图像处理等领域。
426+

docs/docs/机器学习/传统算法/随机森林.md

Lines changed: 184 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,22 @@ title: 随机森林
77

88
随机森林是对决策树集合的特有名称。
99

10-
随机森林里我们有多个决策树(所以叫“森林”)。
10+
随机森林里我们有多个决策树(所以叫"森林")。
1111

12-
为了给一个新的观察值分类,根据它的特征,每一个决策树都会给出一个分类
12+
传统决策树很容易受到个别异常数据的影响构造出奇怪的树,为了避免这种情况,我们假设有100条数据,其中有2条数据异常
1313

14-
随机森林算法选出投票最多的分类作为分类结果。
15-
16-
怎样生成决策树:
14+
生成决策树:
1715

1816
1. 如果训练集中有 N 种类别,则有重复地随机选取 N 个样本。这些样本将组成培养决策树的训练集。
1917

2018
2. 如果有 M 个特征变量,那么选取数`m << M`,从而在每个节点上随机选取 m 个特征变量来分割该节点。m 在整个森林养成中保持不变。
2119

2220
3. 每个决策树都最大程度上进行分割,没有剪枝。
2321

22+
- 对于分类问题:每一个决策树都会给出一个分类。随机森林算法选出投票最多的分类作为分类结果。对于这2条数据异常所在的决策树会给出错误结果,正常数据会给出正确的结果,少数服从多数,最终分类正确。
23+
24+
- 对于回归问题:每一个决策树都会给出一个结果,随机森林对不同树取平均。对于这2条数据异常所在的决策树会给出偏差较大的结果,正常数据会给出偏差较小的结果,取平均之后,最终偏差较小。
25+
2426
```python showLineNumbers
2527

2628
from sklearn.ensemble import RandomForestClassifier
@@ -231,3 +233,180 @@ plt.ylim(-0.05, 1.05)
231233

232234
plt.show()
233235
```
236+
237+
### Gradient Boosting
238+
239+
梯度提升(Gradient Boosting)是另一种强大的集成学习方法,与随机森林相似,它也是基于决策树的集成,但构建方式不同。
240+
241+
梯度提升的基本思想是通过迭代地训练一系列弱学习器(通常是浅层决策树),每个新的学习器都试图纠正前面学习器的错误。与随机森林并行建立独立树不同,梯度提升是顺序建立树,每棵树都依赖于之前树的结果。
242+
243+
#### 工作原理
244+
245+
1. 从一个简单的模型(例如只有一个节点的决策树)开始
246+
2. 计算当前模型的残差(实际值与预测值的差)
247+
3. 训练一个新的弱学习器来预测这些残差
248+
4. 将新学习器添加到模型中(通常乘以一个学习率)
249+
5. 重复步骤2-4,直到达到指定的迭代次数或误差不再显著减少
250+
251+
:::info
252+
253+
什么是残差?
254+
255+
假设我们有一个简单的回归问题:
256+
真实值:[10, 20, 30, 40]
257+
258+
第一棵树预测结果:[8, 18, 28, 38]
259+
则残差为**真实值**-**第一棵树预测结果**
260+
[2, 2, 2, 2]
261+
262+
第二棵树会尝试预测这个残差[2, 2, 2, 2]
263+
264+
如果第二棵树预测结果为[1.8, 1.8, 1.8, 1.8]
265+
266+
则新的残差为:[0.2, 0.2, 0.2, 0.2]
267+
268+
最终预测 = 第一棵树预测 + 第二棵树预测 = [9.8, 19.8, 29.8, 39.8]
269+
270+
最终预测更加接近真实值,损失更小。
271+
:::
272+
273+
#### 简单代码示例
274+
275+
```python showLineNumbers
276+
from sklearn.ensemble import GradientBoostingClassifier
277+
import numpy as np
278+
from sklearn.datasets import make_classification
279+
from sklearn.model_selection import train_test_split
280+
281+
# 创建数据集
282+
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5,
283+
n_redundant=2, random_state=42)
284+
285+
# 分割数据集
286+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
287+
288+
# 创建梯度提升模型
289+
'''
290+
主要参数说明:
291+
n_estimators: 弱学习器的数量
292+
learning_rate: 学习率,控制每个弱学习器的贡献
293+
max_depth: 决策树的最大深度
294+
subsample: 用于拟合基学习器的样本比例,<1.0表示采用随机梯度提升
295+
'''
296+
gbm = GradientBoostingClassifier(n_estimators=100,
297+
learning_rate=0.1,
298+
max_depth=3,
299+
subsample=0.8,
300+
random_state=42)
301+
302+
# 训练模型
303+
gbm.fit(X_train, y_train)
304+
305+
# 评估模型
306+
accuracy = gbm.score(X_test, y_test)
307+
print(f"模型准确率: {accuracy:.4f}")
308+
309+
# 进行预测
310+
y_pred = gbm.predict(X_test)
311+
y_proba = gbm.predict_proba(X_test)
312+
```
313+
314+
#### XGBoost
315+
316+
XGBoost(eXtreme Gradient Boosting)是梯度提升的高效实现,具有以下优势:
317+
318+
- 加入了正则化项防止过拟合
319+
- 支持并行计算
320+
- 可以处理缺失值
321+
- 内置交叉验证
322+
- 提供树剪枝机制
323+
324+
```python showLineNumbers
325+
import xgboost as xgb
326+
from sklearn.datasets import make_classification
327+
from sklearn.model_selection import train_test_split
328+
329+
# 创建数据集
330+
X, y = make_classification(n_samples=1000, n_features=10, random_state=42)
331+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
332+
333+
# 创建DMatrix对象(XGBoost的数据格式)
334+
dtrain = xgb.DMatrix(X_train, label=y_train)
335+
dtest = xgb.DMatrix(X_test, label=y_test)
336+
337+
# 设置参数
338+
params = {
339+
'objective': 'binary:logistic', # 目标函数
340+
'max_depth': 3, # 树的最大深度
341+
'eta': 0.1, # 学习率
342+
'subsample': 0.8, # 样本采样比例
343+
'colsample_bytree': 0.8, # 特征采样比例
344+
'eval_metric': 'logloss' # 评估指标
345+
}
346+
347+
# 训练模型
348+
num_rounds = 100
349+
model = xgb.train(params, dtrain, num_rounds)
350+
351+
# 预测
352+
preds = model.predict(dtest)
353+
pred_labels = [1 if p > 0.5 else 0 for p in preds]
354+
accuracy = sum(pred_labels == y_test) / len(y_test)
355+
print(f"XGBoost模型准确率: {accuracy:.4f}")
356+
```
357+
358+
#### LightGBM
359+
360+
LightGBM是另一种高效的梯度提升实现,专注于提高训练速度和内存效率:
361+
362+
- 使用基于直方图的算法加速训练
363+
- 采用叶子优先的生长策略
364+
- 支持类别特征的直接处理
365+
- 对大规模数据和高维特征友好
366+
367+
```python showLineNumbers
368+
import lightgbm as lgb
369+
from sklearn.datasets import make_classification
370+
from sklearn.model_selection import train_test_split
371+
from sklearn.metrics import accuracy_score
372+
373+
# 创建数据集
374+
X, y = make_classification(n_samples=1000, n_features=10, random_state=42)
375+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
376+
377+
# 创建数据集格式
378+
train_data = lgb.Dataset(X_train, label=y_train)
379+
380+
# 设置参数
381+
params = {
382+
'objective': 'binary', # 目标函数
383+
'metric': 'binary_logloss', # 评估指标
384+
'max_depth': 3, # 树的最大深度
385+
'learning_rate': 0.1, # 学习率
386+
'feature_fraction': 0.8, # 特征采样比例
387+
'bagging_fraction': 0.8, # 样本采样比例
388+
'bagging_freq': 5 # 样本采样频率
389+
}
390+
391+
# 训练模型
392+
num_rounds = 100
393+
model = lgb.train(params, train_data, num_rounds)
394+
395+
# 预测
396+
y_pred_proba = model.predict(X_test)
397+
y_pred = [1 if p > 0.5 else 0 for p in y_pred_proba]
398+
accuracy = accuracy_score(y_test, y_pred)
399+
print(f"LightGBM模型准确率: {accuracy:.4f}")
400+
```
401+
402+
#### 梯度提升与随机森林的比较
403+
404+
| 特性 | 梯度提升 | 随机森林 |
405+
|------|----------|----------|
406+
| 训练方式 | 顺序(每棵树依赖前面的树) | 并行(树独立训练) |
407+
| 对过拟合的敏感性 | 较高 | 较低 |
408+
| 参数调优难度 | 较高 | 较低 |
409+
| 处理大型数据集 | 可能较慢 | 较快(可并行) |
410+
| 预测性能 | 通常更高(合理调参后) | 很好但通常低于梯度提升 |
411+
| 模型解释性 | 较低 | 中等 |
412+
| 对异常值的敏感性 | 较高 | 较低 |

0 commit comments

Comments
 (0)