99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀R文本挖掘之tm包
R文本挖掘之tm包
2017-05-08
收藏

R文本挖掘之tm包

tm包是R文本挖掘方面不可不知也不可不用的一個package。它提供了文本挖掘中的綜合處理功能。如:數(shù)據(jù)載入,語料庫處理,數(shù)據(jù)預(yù)處理,元數(shù)據(jù)管理以及建立“文檔-詞條”矩陣。
下面,即從tm包提供的各項功能函數(shù)的探索出發(fā),一起開始我們的文本挖掘奇幻之旅。

首先,運(yùn)行下面的幾行代碼,即可看到介紹tm包的小品文:Introduction to the tm Package:Text Mining in R(https://cran.r-project.org/web/packages/tm/vignettes/tm.pdf).
install.packages("tm")

library(tm)

vignette("tm")

tm包重要函數(shù)初探


數(shù)據(jù)載入及語料庫創(chuàng)建


載入數(shù)據(jù)的格式要求

tm包支持多種格式的數(shù)據(jù)。用getreaders()函數(shù)可以獲得tm包支持的數(shù)據(jù)文件格式。

library(tm)

## Loading required package: NLP

getReaders()

##  [1] "readDOC"                 "readPDF"                
##  [3] "readPlain"               "readRCV1"               
##  [5] "readRCV1asPlain"         "readReut21578XML"       
##  [7] "readReut21578XMLasPlain" "readTabular"            
##  [9] "readTagged"              "readXML"

載入數(shù)據(jù)的方式


tm包中主要管理文件的數(shù)據(jù)結(jié)構(gòu)稱為語料庫(Corpus),它表示一系列文檔的集合。

語料庫又分為動態(tài)語料庫(Volatile Corpus)和靜態(tài)語料庫(Permanent Corpus)。

動態(tài)語料庫將作為R對象保存在內(nèi)存中,可以使用VCorpus()或者Corpus()生成。

而動態(tài)語料庫則作為R外部文件保存,可以使用PCorpus()函數(shù)生成。

先來看一下VCorpus()函數(shù)的使用。

VCorpus(x, readerControl = list(reader = reader(x), language = "en"))

as.VCorpus(x)

第一個參數(shù)x即文本數(shù)據(jù)來源。對于as.VCorpus()中的x,指定的是一個R對象;對于VCorpus(),可以使用以下幾種方式載入x。

    DirSource():從本地文件目錄夾導(dǎo)入

    VectorSource():輸入文本構(gòu)成的向量

    DataframeSource():輸入文本構(gòu)成的data frame

對于第二個參數(shù)readerControl,即指定文件類型的對應(yīng)的讀入方式。默認(rèn)使用tm支持的(即getReaders()中羅列的)一系列函數(shù)。language即文件的語言類型。似乎不能支持中文。這個問題稍后解釋如何解決。

這里,使用tm包自帶的一個數(shù)據(jù)集進(jìn)行語料庫創(chuàng)建的測試。

    DirSource()方式:

txt<-system.file("texts","txt",package = 'tm')

(docs<-Corpus(DirSource(txt,encoding = "UTF-8")))

## <<VCorpus>>
## Metadata:  corpus specific: 0, document level (indexed): 0
## Content:  documents: 5

    VectorSource()方式:

docs<-c("this is a text","And we create a vector.")

VCorpus(VectorSource(docs))

## <<VCorpus>>
## Metadata:  corpus specific: 0, document level (indexed): 0
## Content:  documents: 2

下面,導(dǎo)入一個數(shù)據(jù)集『冰與火之歌』全五部(沒錯,我就是來劇透的~~),作為后面練習(xí)的例子。

IceAndSongs<-VCorpus(DirSource(directory = "D:/my_R_workfile/RPROJECT/textming/data/IceAndSongs",encoding = "UTF-8"))

數(shù)據(jù)導(dǎo)出

將語料庫導(dǎo)出至本地硬盤上,可以使用writeCorpus()函數(shù).

writeCorpus(IceAndSongs,path = "D:/my_R_workfile/RPROJECT/textming/data/Corpus")

語料庫的查看及提取

可以使用print()和summary()查看語料庫的部分信息。而完整信息的提取則需要使用inspect()函數(shù)。

inspect(IceAndSongs[1:2])

## <<VCorpus>>
## Metadata:  corpus specific: 0, document level (indexed): 0
## Content:  documents: 2
##
## [[1]]
## <<PlainTextDocument>>
## Metadata:  7
## Content:  chars: 1745859
##
## [[2]]
## <<PlainTextDocument>>
## Metadata:  7
## Content:  chars: 2018112

文件太大,而沒有打印出來。我們可以使用writeLines()函數(shù)進(jìn)行完全打印查看。

writeLines(as.character(IceAndSongs[[1]]))

對于單個文檔的提取,可以類型列表取元素子集一樣使用 [[ 操作。

identical(IceAndSongs[[1]],IceAndSongs[["冰與火之歌1.txt"]])

## [1] TRUE

數(shù)據(jù)轉(zhuǎn)換

創(chuàng)建好語料庫之后,一般還需要做進(jìn)一步的處理,如:消除空格(Whitespace),大小寫轉(zhuǎn)換,去除停止詞,詞干化等。

所有的這些處理都可以使用tm_map()函數(shù),通過map的方式將轉(zhuǎn)化函數(shù)應(yīng)用到每一個文檔語料上。

消除空格

IceAndSongs<-tm_map(IceAndSongs,stripWhitespace)

去除數(shù)字

IceAndSongs<-tm_map(IceAndSongs,removeNumbers)

去除標(biāo)點(diǎn)符號

IceAndSongs<-tm_map(IceAndSongs,removePunctuation)

大小寫轉(zhuǎn)換

IceAndSongs<-tm_map(IceAndSongs,tolower)

消除停止詞

tm包中自帶了停止詞集。

IceAndSongs<-tm_map(IceAndSongs,removeWords,stopwords("english"))

當(dāng)然,也可以指定你自己設(shè)定的停止詞集,將stopwords("english")替換成你自己的停止詞集對象即可。


詞干化


詞干化,即詞干提取。指的是去除詞綴得到詞根的過程─—得到單詞最一般的寫法。

如以單復(fù)數(shù)等多種形式存在的詞,或多種時態(tài)形式存在的同一個詞,它們代表的其實是同一個意思。因此需要通過詞干化將它們的形式進(jìn)行統(tǒng)一。

tm_map(IceAndSongs,stemDocument)

## <<VCorpus>>
## Metadata:  corpus specific: 0, document level (indexed): 0
## Content:  documents: 5

去除特殊字符

for(i in seq(IceAndSongs)){
  IceAndSongs[[i]]<-gsub("/"," ",IceAndSongs[[i]])
  IceAndSongs[[i]]<-gsub("@"," ",IceAndSongs[[i]])
  IceAndSongs[[i]]<-gsub("-"," ",IceAndSongs[[i]])
}

過濾

過濾功能能夠選擇出符合我們需要的文檔。

idx<-meta(IceAndSongs,"id") == "冰與火之歌1.txt"

IceAndSongs[idx]

也可以進(jìn)行全文搜索匹配。如含有”winter is coming”的文檔。

tm_filter(IceAndSongs,FUN = function(x){ any(grep("winter is coming",content(x)))})

元數(shù)據(jù)管理

元數(shù)據(jù)指的是對文檔進(jìn)行標(biāo)簽化的附加信息??梢酝ㄟ^meta()函數(shù)進(jìn)行元數(shù)據(jù)管理。

DublinCore()函數(shù)提供了一套介于Simple Dublin Core元數(shù)據(jù)和tm元數(shù)據(jù)之間的映射機(jī)制,用于獲得或設(shè)置文檔的元數(shù)據(jù)信息。

DublinCore(IceAndSongs[[1]],tag = "creator") <- "R.R.Martin"

DublinCore(IceAndSongs[[1]])

meta(IceAndSongs[[1]])

以上操作示例主要是針對文檔級別的元數(shù)據(jù)管理。而元數(shù)據(jù)標(biāo)簽其實對應(yīng)了兩個級別:

    整個語料庫級別:文檔的集合

    單個文檔級別

而文檔級別的標(biāo)簽,可以用于文檔分類(classification)。

下面演示一下語料庫級別的元數(shù)據(jù)管理。

meta(IceAndSongs,tag = "test",type = "corpus")<-"test meta"

meta(IceAndSongs,type = "corpus")

創(chuàng)建詞條-文檔矩陣

詞條-文檔矩陣是一個非常重要的對象,它是后續(xù)建立文本分類,文本聚類等模型的基礎(chǔ)。

詞條-文檔矩陣指的是詞條作為行,文檔標(biāo)簽作為列的稀疏矩陣。當(dāng)然,也可以建立“文檔-詞條矩陣”。對應(yīng)的兩個操作函數(shù)為:TermDocumentMatrix()和DocumentTermMatrix().

dtm<-DocumentTermMatrix(IceAndSongs)

inspect(dtm[1:5,100:105])

默認(rèn)情況下,矩陣的元素是詞的頻率。而我們還有一個重要參數(shù)可以設(shè)置??梢詫⒕仃嚨脑剞D(zhuǎn)化為TF-IDF值。

dtm_2<-DocumentTermMatrix(IceAndSongs,
                        control = list(removePunctuation = TRUE,stopwords = FALSE,weighting =
              function(x)weightTfIdf(x,normalize = TRUE)))

inspect(dtm[1:5,10:15])
對文檔詞條矩陣操作
tm包提供的文檔-詞條矩陣操作有:詞頻過濾;詞語之間的相關(guān)性計算;去除稀疏詞等。
findFreqTerms(dtm,10)
findAssocs(dtm,"winter",0.5)
inspect(removeSparseTerms(dtm,0.4))
字典
字典是一個字符集。它可以作為一個控制參數(shù)傳入DocumentTermMatrix(),從而選擇我們需要的詞條建立文檔-詞條矩陣。
inspect(DocumentTermMatrix(IceAndSongs,
                           list(dictionary = c("winter","power","ice"))))

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }