文本聚类分析

Reads: 753 Edit

1 问题描述

为了演示文本聚类模型,我们将从网站下载了8篇新闻文字稿,采用文本聚类方法将这8篇新闻进行聚类。

2 中文预处理

安装加载用到的包

> install.packages("SnowballC")
> library(SnowballC)
> install.packages("topicmodels")
> library(topicmodels)
> library(Rwordseg)
> library(tm)
> library(tidyverse) 
> library(wordcloud2)
> install.packages("tidytext")
> library(tidytext)

读取文本数据

> setwd("D:/Desktop/news")
> filenames=list.files(getwd(),pattern="txt")
> filenames
[1] "10万预算的新款小型SUV 这4款很快就登场.txt"         
[2] "高校毕业生就业:“两头”抢手“中间”冷.txt"            
[3] "科技革新 BMW 全新7系与创新纯电动i7发布.txt"        
[4] "科学好故事小行星和彗星撞击地球的几率有多大?.txt"  
[5] "篮网惨遭翻盘0-2落后 杜兰特27分欧文大失水准.txt"    
[6] "老板电器业绩14年以来首降,百亿里程碑蒙尘.txt"      
[7] "雷克萨斯RZ全球首发 专属纯电平台打造.txt"           
[8] "疫情零售面临艰难挑战,国内服饰集团股价全面下跌.txt"

说明:读取了news文件夹下面的8个txt文件!

> files=lapply(filenames,readLines)
> files=files[!is.na(files)]         ## 去除空行

中文分词

> words=segmentCN(as.character(files),returnType="tm")  ## 注意加returnType="tm"

生成语料库

> words_corpus=Corpus(VectorSource(words))

生成DTM文件

> words_dtm=DocumentTermMatrix(words_corpus,control = list(wordLengths=c(1,Inf)))

3 层次聚类

> distance=dist(as.matrix(words_dtm))
> groups <- hclust(distance,method="ward.D")
> plot(groups)
> plot(groups, hang=-1)

说明:层次聚类,第一次第5篇文档和第7篇文档聚成1类;第二层第8篇文档并入5和7的类别中;其他层同理。

r-114

4 K-means聚类

> fit_kmeans = kmeans(distance, 3, nstart=100)
> library(cluster)
> clusplot(as.matrix(distance), fit_kmeans$cluster, color=T, shade=T, labels=2, lines=0)

说明:这里聚成3类(kmeans()函数设置为3),1,2,5,6,7,8聚成一类,3单独聚成1类,4单独聚成1类。

r-115



获取案例数据,请关注微信公众号并回复:R_dt18


Comments

Make a comment