news 2026/4/21 22:49:10

数据挖掘算法之随机森林分类器和K-means聚类算法

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
数据挖掘算法之随机森林分类器和K-means聚类算法

数据挖掘算法之随机森林分类器和K-means聚类算法

  • 随机森林分类器原理详解
    • 1. ‌集成思想‌
    • 2. ‌双重随机性‌
    • 3. ‌训练流程‌
    • 4. ‌优势机制‌
    • 5. ‌数学基础‌
  • K-means聚类算法
    • 算法步骤
  • 实例展示
  • 总结

随机森林分类器原理详解

随机森林(Random Forest)是一种集成学习方法,通过构建多棵决策树并综合其预测结果来提升分类性能。其核心原理包括:

1. ‌集成思想‌

随机森林由多棵决策树组成,每棵树独立训练,最终通过投票机制决定分类结果。这种“集体智慧”机制(“三个臭皮匠胜过诸葛亮”)显著提升模型的准确性和鲁棒性。

2. ‌双重随机性‌

随机森林通过以下两个关键随机操作实现多样性:

‌样本随机性‌:每棵树从原始数据中有放回地随机抽取子集进行训练(自助采样法),确保数据多样性。 ‌特征随机性‌:在每个节点分裂时,随机选择特征子集(如特征数量的平方根),避免特征同质化。

3. ‌训练流程‌

‌数据采样‌:从原始数据中抽取多个子集(如100个)。 ‌树构建‌:每棵树独立训练,使用随机子集和特征子集。 ‌预测集成‌:对新样本,所有树投票决定最终分类(多数表决)。

4. ‌优势机制‌

‌抗过拟合‌:随机性降低单树方差,提升泛化能力。 ‌鲁棒性‌:对噪声和异常值不敏感,适用于非线性问题。 ‌特征重要性‌:通过分析各特征在决策树中的使用频率,评估其对分类的贡献。

5. ‌数学基础‌

随机森林的预测函数为所有树预测结果的加权平均(分类时为投票):
y=argmaxc∑i=1mI(yi=c)y​=argmaxc​∑i=1m​I(yi​=c)
其中 mm 为树的数量,II 为指示函数。

K-means聚类算法

K-means是一种基于距离的经典聚类算法,通过迭代优化将数据划分为K个簇,其核心是使每个数据点到所属簇中心的距离平方和最小化。

算法步骤

‌初始化‌:随机选择K个数据点作为初始簇中心 ‌分配‌:计算每个数据点到各中心的距离,将其分配到最近的中心 ‌更新‌:重新计算每个簇的均值作为新中心 ‌迭代‌:重复2-3步直至中心不再变化或达到最大迭代次数

该算法采用欧氏距离衡量相似性,通过不断调整簇中心来优化目标函数。其优点在于实现简单、计算高效,尤其适合大规模数据集。但需预先指定K值,且对初始中心敏感,可能陷入局部最优解。

实例展示

import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, classification_report from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans import matplotlib.pyplot as plt import seaborn as sns class DataMiningAlgorithms: def __init__(self): self.model = None self.scaler = StandardScaler() self.kmeans_model = None def load_sample_data(self): """加载示例数据集""" from sklearn.datasets import load_iris iris = load_iris() X = pd.DataFrame(iris.data, columns=iris.feature_names) y = pd.Series(iris.target, name='target') return X, y def preprocess_data(self, X, y=None): """数据预处理""" # 标准化特征 X_scaled = self.scaler.fit_transform(X) X_scaled = pd.DataFrame(X_scaled, columns=X.columns) if y is not None: return X_scaled, y return X_scaled def random_forest_classification(self, X, y): """随机森林分类""" # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y ) # 训练随机森林模型 self.model = RandomForestClassifier( n_estimators=100, max_depth=10, random_state=42, n_jobs=-1 ) self.model.fit(X_train, y_train) # 预测 y_pred = self.model.predict(X_test) # 评估 accuracy = accuracy_score(y_test, y_pred) return { 'model': self.model, 'accuracy': accuracy, 'predictions': y_pred, 'actual': y_test, 'report': classification_report(y_test, y_pred) } def kmeans_clustering(self, X, n_clusters=3): """K-means聚类""" # 标准化数据 X_scaled = self.preprocess_data(X) # 训练K-means模型 self.kmeans_model = KMeans(n_clusters=n_clusters, random_state=42) cluster_labels = self.kmeans_model.fit_predict(X_scaled) return { 'model': self.kmeans_model, 'labels': cluster_labels, 'centers': self.kmeans_model.cluster_centers_ } def feature_importance(self): """获取特征重要性""" if self.model is None: return None importances = self.model.feature_importances_ return importances def plot_feature_importance(self, feature_names): """绘制特征重要性图""" importances = self.feature_importance() if importances is None: return indices = np.argsort(importances)[::-1] plt.figure(figsize=(10, 6)) plt.title("特征重要性") plt.bar(range(len(importances)), importances[indices]) plt.xticks(range(len(importances)), [feature_names[i] for i in indices], rotation=45) plt.tight_layout() plt.show() def plot_clusters(self, X, labels): """绘制聚类结果""" plt.figure(figsize=(10, 6)) plt.scatter(X.iloc[:, 0], X.iloc[:, 1], c=labels, cmap='viridis') plt.title("K-means聚类结果") plt.xlabel(X.columns[0]) plt.ylabel(X.columns[1]) plt.colorbar() plt.show() def main(): """主函数""" print("数据挖掘算法演示") print("=" * 30) # 创建数据挖掘对象 dm = DataMiningAlgorithms() # 加载数据 X, y = dm.load_sample_data() print(f"数据集大小: {X.shape}") print(f"特征名称: {list(X.columns)}") # 随机森林分类 print("\n1. 随机森林分类:") classification_result = dm.random_forest_classification(X, y) print(f"准确率: {classification_result['accuracy']:.4f}") print("分类报告:") print(classification_result['report']) # 特征重要性 print("\n2. 特征重要性:") importances = dm.feature_importance() for i, feature in enumerate(X.columns): print(f"{feature}: {importances[i]:.4f}") # 绘制特征重要性 dm.plot_feature_importance(X.columns.tolist()) # K-means聚类 print("\n3. K-means聚类:") clustering_result = dm.kmeans_clustering(X, n_clusters=3) print(f"聚类标签: {clustering_result['labels'][:10]}...") # 显示前10个标签 # 绘制聚类结果 dm.plot_clusters(X, clustering_result['labels']) if __name__ == "__main__": main()

总结

实现了完整的数据挖掘算法框架,包含随机森林分类和K-means聚类两种核心算法
集成数据加载、预处理、模型训练、评估和可视化功能模块
使用鸢尾花数据集作为示例,展示算法的实际应用效果
提供特征重要性分析功能,帮助理解模型决策过程
包含结果可视化功能,直观展示分类和聚类效果
采用面向对象设计,代码结构清晰,易于扩展和维护
依赖配置文件包含所有必要的Python库,确保项目可直接运行

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/18 10:54:05

如何用Batchplot 3.6.1实现CAD图纸批量打印?终极效率提升指南

如何用Batchplot 3.6.1实现CAD图纸批量打印?终极效率提升指南 【免费下载链接】Batchplot_3.6.1批量打印插件-基于秋枫版修改 Batchplot_3.6.1是一款基于秋枫版优化的批量打印插件,专为提升打印效率而设计。经过精心修改,界面更加简洁易用&am…

作者头像 李华
网站建设 2026/4/19 5:36:17

Captura视频防抖实战:5步打造专业级稳定画面

Captura视频防抖实战:5步打造专业级稳定画面 【免费下载链接】Captura Capture Screen, Audio, Cursor, Mouse Clicks and Keystrokes 项目地址: https://gitcode.com/gh_mirrors/ca/Captura 问题场景:为什么你的屏幕录制总是不够稳定&#xff1f…

作者头像 李华
网站建设 2026/4/21 7:26:18

BlenderMCP:AI驱动的3D建模革命,让复杂操作变得简单

BlenderMCP:AI驱动的3D建模革命,让复杂操作变得简单 【免费下载链接】blender-mcp 项目地址: https://gitcode.com/GitHub_Trending/bl/blender-mcp 在3D建模领域,手动调整相机参数、处理镜头畸变往往是最耗时耗力的环节。现在&#…

作者头像 李华
网站建设 2026/4/15 10:22:14

基于微信小程序的校园水电费缴纳系统毕业设计源码

博主介绍:✌ 专注于Java,python,✌关注✌私信我✌具体的问题,我会尽力帮助你。一、研究目的本研究旨在设计并实现一款基于微信小程序的校园水电费缴纳系统,以解决传统校园水电费缴纳方式存在的诸多问题。具体研究目的如下: 首先&a…

作者头像 李华
网站建设 2026/4/19 13:45:58

广州Sohong AI,办公落地进行时!

传统认知中,企业规模与响应速度常呈反比。Sohong AI办公软件正在改写这一规则。Sohong AI智慧办公正通过部署AI数字员工,构建了“人类创意官数字执行团”的混合团队。当设计师完成核心创意后,Sohong AI系统可自动将其转化为多语言视频脚本&am…

作者头像 李华