
前言今天的机器学习课程主要围绕两个经典算法展开DBSCAN聚类算法和TF-IDF文本向量化。DBSCAN作为一种基于密度的聚类方法能够自动发现任意形状的簇并识别噪声点而TF-IDF则是文本挖掘中最基础的特征提取方式用于衡量词语在文档中的重要性。本文将结合三个实战案例详细讲解这两个算法的原理、代码实现和应用场景。一、DBSCAN密度聚类实战啤酒数据1.1 算法原理简述DBSCANDensity-Based Spatial Clustering of Applications with Noise的核心思想是聚类由高密度区域生长而成。核心点半径eps内至少包含min_samples个样本边界点在核心点邻域内但自身不满足核心点条件噪声点既不是核心点也不是边界点1.2 代码详解fromsklearn.clusterimportDBSCANimportpandasaspdfromsklearnimportmetricsfromsklearn.preprocessingimportMinMaxScalerimportnumpyasnp# 读取啤酒数据包含卡路里、钠、酒精、成本四个特征beerpd.read_table(data.txt,sep ,encodingutf-8,enginepython)X_rawbeer[[calories,sodium,alcohol,cost]]# 0-1归一化消除量纲影响scalerMinMaxScaler(feature_range(0,1))Xscaler.fit_transform(X_raw)# 交叉验证选取最优eps邻域半径scores[]e_param[0.1,0.2,0.3,0.4,0.5,0.6,0.7]foriine_param:dbDBSCAN(epsi,min_samples2)db.fit(X)labelsdb.labels_# 使用轮廓系数评估聚类效果-1~1越高越好scoremetrics.silhouette_score(X,labels)scores.append(score)print(feps{i}, score{score})# 选择轮廓系数最大的epsbest_ee_param[np.argmax(scores)]print(f最优eps为{best_e})# 用最优参数重新建模dbDBSCAN(epsbest_e,min_samples2)db.fit(X)labelsdb.labels_# 将聚类结果添加回原数据框beer[cluster_db]labels beer.sort_values(cluster_db)# 最终轮廓系数评分scoremetrics.silhouette_score(X,labels)print(f最终轮廓系数{score})1.3 关键知识点参数含义调优建议eps邻域半径过小导致大量噪声过大则合并不同簇min_samples核心点最小邻域样本数通常设为2~4数据量大时可适当增加轮廓系数评估聚类内聚度和分离度越接近1表示聚类效果越好二、TF-IDF文本向量化2.1 原理说明TF-IDF 词频TF × 逆文档频率IDFTF某词在文档中出现的频率IDFlog(总文档数 / 包含该词的文档数)核心思想一个词在文档中出现越多在其他文档中出现越少则其重要性越高。2.2 基础代码实现fromsklearn.feature_extraction.textimportTfidfVectorizerimportpandasaspd# 读取语料每行一个文档inFileopen(r.\task2_1.txt,r)corpusinFile.readlines()# 创建TF-IDF向量化器vectorizerTfidfVectorizer()tfidfvectorizer.fit_transform(corpus)# 获取所有特征词wordlistvectorizer.get_feature_names_out()print(词表,wordlist)# 转为DataFrame格式词为行文档为列dfpd.DataFrame(tfidf.T.todense(),indexwordlist)print(df)# 输出每个文档中词的TF-IDF按值降序排列forjinrange(len(corpus)):featurelistdf.iloc[:,j].to_list()resdict{}foriinrange(0,len(wordlist)):resdict[wordlist[i]]featurelist[i]resdictsorted(resdict.items(),keylambdax:x[1],reverseTrue)print(f文档{j1}关键词排序{resdict})三、项目实战红楼梦120回关键词提取3.1 第一步分词与预处理demo02importpandasaspdimportosimportjieba# 1. 读取分卷文件filePaths[]fileContents[]forroot,dirs,filesinos.walk(r.\红楼梦\分卷):fornameinfiles:filePathos.path.join(root,name)filePaths.append(filePath)fopen(filePath,r,encodingutf-8)linesf.readlines()text.join(lines[1:])# 跳过第一行卷名fileContents.append(text)f.close()corpospd.DataFrame({filePath:filePaths,fileContent:fileContents})# 2. 加载自定义词典和停用词jieba.load_userdict(r./红楼梦/红楼梦词库.txt)stopwordspd.read_csv(r./红楼梦分析/StopwordsCN.txt,encodingutf-8,enginepython,index_colFalse)# 3. 逐回分词并过滤停用词file_to_jiebaopen(r./红楼梦/分词后汇总.txt,w,encodingutf-8)forindex,rowincorpos.iterrows():juan_cifileContentrow[fileContent]segsjieba.cut(fileContent)forseginsegs:ifsegnotinstopwords.stopword.valuesandlen(seg.strip())0:juan_ciseg file_to_jieba.write(juan_ci\n)file_to_jieba.close()3.2 第二步计算每回TF-IDFdemo03fromsklearn.feature_extraction.textimportTfidfVectorizerimportpandasaspd# 读取分词后的结果每行一回inFileopen(r.\红楼梦\分词后汇总.txt,r,encodingutf-8)corpusinFile.readlines()# 计算TF-IDFvectorizerTfidfVectorizer()tfidfvectorizer.fit_transform(corpus)wordlistvectorizer.get_feature_names_out()# 转为DataFramedfpd.DataFrame(tfidf.T.todense(),indexwordlist)# 输出每回Top10关键词forjinrange(len(corpus)):featurelistdf.iloc[:,j].to_list()resdict{}foriinrange(0,len(wordlist)):resdict[wordlist[i]]featurelist[i]resdictsorted(resdict.items(),keylambdax:x[1],reverseTrue)print(f第{j1}回的核心关键词{resdict[0:10]})3.3 运行结果示例第1回第1回的核心关键词[(甄士隐, 0.45), (英莲, 0.38), (僧人, 0.32), (道人, 0.30), (石头, 0.28), (太虚, 0.25), ...]四、知识点总结算法应用场景核心优势注意事项DBSCAN客户分群、异常检测、地理信息聚类无需预设簇数、可识别噪声eps和min_samples需调参TF-IDF搜索引擎、关键词提取、文本分类简单高效、可解释性强需结合分词和停用词过滤五、进阶学习建议DBSCAN可尝试使用k-distance图辅助选取最优epsTF-IDF可结合CountVectorizer对比词袋模型效果六、结语今天的内容涵盖了无监督聚类和文本特征提取两大机器学习核心领域。DBSCAN让我们能够从数据中发现自然形成的群体结构而TF-IDF则为文本数据提供了量化的分析基础。