r - R 中的 Dictionary() 函数的问题

标签 r dictionary

根据 Lantz 题为“Machine Learning with R”的书,我一直在关注贝叶斯分类器的一个例子。案例是一个垃圾邮件分类器,它使用以下链接的数据:

http://www.dt.fee.unicamp.br/~tiago/smsspamcollection/

在代码中,我在这部分遇到了问题:

sms_train<-DocumentTermMatrix(sms_corpus_train,list(dictionary=sms_dict))
sms_test<-DocumentTermMatrix(sms_corpus_test,list(dictionary=sms_dict))

因为它说我应该使用以下指令:
sms_dict <- Dictionary(findFreqTerms(sms_dtm_train, 5))

问题在于新版本的 tm 已弃用 Dictionary() 函数。我应该怎么做才能完成书中所说的:

A dictionary is a data structure allowing us to specify which words should appear in a document term matrix. To limit our training and test matrixes to only the words in the preceding dictionary, use the following command



我做了以下工作:
sms_dict<-findFreqTerms(sms_dtm_train,5)
sms_train<-DocumentTermMatrix(sms_corpus_train,list(dictionary=sms_dict))
sms_test<-DocumentTermMatrix(sms_corpus_test,list(dictionary=sms_dict))

但我确信我并没有限制书中所说的测试矩阵。即使代码正在运行,它也没有给我正确的结果。在这种情况下我可以修改什么?

用于跟踪的完整代码如下:
sms_raw<-read.csv("sms_spam.csv",stringsAsFactors=FALSE)
install.packages("tm")
library(tm)
sms_corpus<-Corpus(VectorSource(sms_raw$text))
corpus_clean<-tm_map(sms_corpus,content_transformer(tolower))
corpus_clean<-tm_map(corpus_clean,removeNumbers)
corpus_clean<-tm_map(corpus_clean,removeWords,stopwords())
corpus_clean<-tm_map(corpus_clean,stripWhitespace)
sms_dtm<-DocumentTermMatrix(corpus_clean)
sms_raw_train<-sms_raw[1:4169,]
sms_raw_test<-sms_raw[4170:5559,]
sms_dtm_train<-sms_dtm[1:4169,]
sms_dtm_test<-sms_dtm[4170:5559,]
sms_corpus_train<-corpus_clean[1:4169]
sms_corpus_test<-corpus_clean[4170:5559]
sms_dict<-findFreqTerms(sms_dtm_train,5)
sms_train<-DocumentTermMatrix(sms_corpus_train,list(dictionary=sms_dict))
sms_test<-DocumentTermMatrix(sms_corpus_test,list(dictionary=sms_dict))
convert_counts<-function(x){
x<-ifelse(x>0,1,0)
x<-factor(x,levels=c(0,1),labels=c("No","Yes"))
return(x)
}
sms_train<-apply(sms_train,MARGIN=2,convert_counts)
sms_test<-apply(sms_test,MARGIN=2,convert_counts)
library(e1071)
sms_classifier<-naiveBayes(sms_train,sms_raw_train$type)
sms_test_pred<-predict(sms_classifier,sms_test)
install.packages("gmodels")
library(gmodels)
CrossTable(sms_test_pred,sms_raw_test$type,prop.chisq=FALSE,prop.t=FALSE,dnn=c('predicted','actual'))

谢谢

最佳答案

我遇到了同样的问题并通过执行以下操作解决了它:

CrossTable(sms_test_pred[["class"]], sms_raw_test$Type, prop.chisq = FALSE, prop.t = FALSE, dnn = c('predicted','actual'))

关于r - R 中的 Dictionary() 函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47141436/

相关文章:

r - 如何在 R 中运行 lmer 诊断图?

r - 使用 NA 的时间序列填充

dictionary - 为什么 map 值变得不存在?

pointers - 从结构指针数组创建映射

python - 读取 CSV 文件的每一列作为字典的键

c# - 使用列表条目作为字典的键

从函数 R 中的列表列表中删除 NA

r - ggvis 中的图例方向

r - R 中的数据帧 "expand"程序?

python - 如何展开基于键值 "pairs"的 python 列表字典?