楼主: Lisrelchen
2332 15

Data Science with R Naive Bayes Clasification [推广有奖]

  • 0关注
  • 62粉丝

VIP

院士

67%

还不是VIP/贵宾

-

TA的文库  其他...

Bayesian NewOccidental

Spatial Data Analysis

东西方数据挖掘

威望
0
论坛币
49957 个
通用积分
79.5487
学术水平
253 点
热心指数
300 点
信用等级
208 点
经验
41518 点
帖子
3256
精华
14
在线时间
766 小时
注册时间
2006-5-4
最后登录
2022-11-6

相似文件 换一批

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币

Data Science with R Naive Bayes Clasification

The required packages for this chapter include:
  • library(rattle) # weather and normVarNames()
  • library(randomForest) # na.roughfix()
  • library(e1071) # naiveBayes()
  • library(ROCR) # prediction()

As we work through this chapter, new R commands will be introduced. Be sure to review the command’s documentation and understand what the command does. You can ask for help using
the ? command as in:
?read.csv
We can obtain documentation on a particular package using the help= option of library():
library(help=rattle)
This chapter is intended to be hands on. To learn effectively, you are encouraged to have R running (e.g., RStudio) and to run all the commands as they appear here. Check that you get the same output, and you understand the output. Try some variations.

本帖隐藏的内容

Data Science with R Naive Bayes Clasification.rar (188.79 KB) 本附件包括:
  • Data Science with R Naive Bayes Clasification.pdf




二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Data Science Science cation Bayes ATION

本帖被以下文库推荐

沙发
Lisrelchen 发表于 2015-6-13 07:58:14 |只看作者 |坛友微信交流群
  1. ## ----module, echo=FALSE, results="asis"----------------------------------
  2. Module <- "BayesO"
  3. cat(paste0("\\newcommand{\\Module}{", Module, "}"))


  4. ## ----setup, child="mycourse.Rnw"-----------------------------------------

  5. ## ----setup_options, include=FALSE----------------------------------------
  6. library(knitr)
  7. library(xtable)

  8. opts_chunk$set(cache=FALSE)

  9. opts_chunk$set(out.width='0.8\\textwidth')
  10. opts_chunk$set(fig.align='center')

  11. opts_chunk$set(src.top=NULL)
  12. opts_chunk$set(src.bot=NULL)
  13. opts_chunk$set(out.lines=4)
  14. opts_chunk$set(out.truncate=80)

  15. opts_chunk$set(fig.path=sprintf("figures/%s/", Module))
  16. opts_chunk$set(cache.path=sprintf("cache/%s/", Module))
  17. opts_chunk$set(bib.file=paste0(Module, ".bib"))

  18. # Leave code as I have formatted it.

  19. opts_chunk$set(tidy=FALSE)

  20. # Hooks

  21. # Allow auto crop of base graphics plots when crop=TRUE.

  22. knit_hooks$set(crop=hook_pdfcrop)

  23. # Truncate long lines and long output

  24. hook_output <- knit_hooks$get("output")
  25. hook_source <- knit_hooks$get("source")
  26. knit_hooks$set(output=function(x, options)
  27. {
  28.   if (options$results != "asis")
  29.   {
  30.     # Split string into separate lines.
  31.     x <- unlist(stringr::str_split(x, "\n"))
  32.     # Trim to the number of lines specified.
  33.     if (!is.null(n <- options$out.lines))
  34.     {
  35.       if (length(x) > n)
  36.       {
  37.         # Truncate the output.
  38.         x <- c(head(x, n), "....\n")
  39.       }
  40.     }
  41.     # Truncate each line to length specified.
  42.     if (!is.null(m <- options$out.truncate))
  43.     {
  44.       len <- nchar(x)
  45.       x[len>m] <- paste0(substr(x[len>m], 0, m-3), "...")
  46.     }
  47.     # Paste lines back together.
  48.     x <- paste(x, collapse="\n")
  49.     # Replace ' = ' with '=' - my preference. Hopefully won't
  50.     # affect things inappropriately.
  51.     x <- gsub(" = ", "=", x)
  52.   }
  53.   hook_output(x, options)
  54. },
  55. source=function(x, options)
  56. {
  57.   # Split string into separate lines.
  58.   x <- unlist(stringr::str_split(x, "\n"))
  59.   # Trim to the number of lines specified.
  60.   if (!is.null(n <- options$src.top))
  61.   {
  62.     if (length(x) > n)
  63.     {
  64.       # Truncate the output.
  65.       if (is.null(m <-options$src.bot)) m <- 0
  66.       x <- c(head(x, n+1), "\n....\n", tail(x, m+2))
  67.    }
  68.   }
  69.   # Paste lines back together.
  70.   x <- paste(x, collapse="\n")
  71.   hook_source(x, options)
  72. })

  73. # Optionally allow R Code chunks to be environments so we can refer to them.

  74. knit_hooks$set(rcode=function(before, options, envir)
  75. {
  76.   if (before)
  77.     sprintf('\\begin{rcode}\\label{%s}\\hfill{}', options$label)
  78.   else
  79.     '\\end{rcode}'
  80. })



  81. ## ----load_packages, message=FALSE----------------------------------------
  82. library(rattle)       # weather and normVarNames()
  83. library(randomForest) # na.roughfix()
  84. library(e1071)        # naiveBayes()
  85. library(ROCR)         # prediction()


  86. ## ----common_intro, child='documentation.Rnw', eval=TRUE------------------


  87. ## ----help_library, eval=FALSE, tidy=FALSE--------------------------------
  88. ## ?read.csv


  89. ## ----help_package, eval=FALSE--------------------------------------------
  90. ## library(help=rattle)


  91. ## ----record_start_time, echo=FALSE---------------------------------------
  92. start.time <- proc.time()


  93. ## ----generate_bib, echo=FALSE, message=FALSE, warning=FALSE--------------
  94. # Write all packages in the current session to a bib file
  95. if (is.null(opts_chunk$get("bib.file"))) opts_chunk$set(bib.file="Course.bib")
  96. write_bib(sub("^.*/", "", grep("^/", searchpaths(), value=TRUE)),
  97.           file=opts_chunk$get("bib.file"))
  98. system(paste("cat extra.bib >>", opts_chunk$get("bib.file")))
  99. # Fix up specific issues.
  100. # R-randomForest
  101. system(paste("perl -pi -e 's|Fortran original by Leo Breiman",
  102.              "and Adele Cutler and R port by|Leo Breiman and",
  103.              "Adele Cutler and|'", opts_chunk$get("bib.file")))
  104. # R-C50
  105. system(paste("perl -pi -e 's|. C code for C5.0 by R. Quinlan|",
  106.              " and J. Ross Quinlan|'", opts_chunk$get("bib.file")))
  107. # R-caret
  108. system(paste("perl -pi -e 's|. Contributions from|",
  109.              " and|'", opts_chunk$get("bib.file")))
  110. # Me
  111. system(paste("perl -pi -e 's|Graham Williams|",
  112.              "Graham J Williams|'", opts_chunk$get("bib.file")))




  113. ## ----bayes_prepare_data_weather, message=FALSE---------------------------
  114. library(rattle)                # Normalise names normVarNames() and weather dataset.
  115. library(randomForest)        # Impute missing using na.roughfix().

  116. dsname     <- "weather"
  117. ds         <- get(dsname)
  118. names(ds)  <- normVarNames(names(ds))
  119. vars       <- names(ds)
  120. target     <- "rain_tomorrow"
  121. risk       <- "risk_mm"
  122. id         <- c("date", "location")

  123. ignore     <- union(id, if (exists("risk")) risk)
  124. vars       <- setdiff(vars, ignore)

  125. inputs     <- setdiff(vars, target)
  126. numi       <- which(sapply(ds[inputs], is.numeric))
  127. numc       <- names(numi)
  128. cati       <- which(sapply(ds[inputs], is.factor))
  129. catc       <- names(cati)

  130. ds[numc]   <- na.roughfix(ds[numc]) # Impute missing values, roughly.
  131. ds[target] <- as.factor(ds[[target]])        # Ensure the target is categoric.

  132. nobs       <- nrow(ds)

  133. form       <- formula(paste(target, "~ ."))

  134. set.seed(42)

  135. train      <- sample(nobs, 0.7*nobs)
  136. test       <- setdiff(seq_len(nobs), train)
  137. actual     <- ds[test, target]
  138. risks      <- ds[test, risk]


  139. ## ----check_dataset, out.lines=5------------------------------------------
  140. dim(ds)
  141. names(ds)
  142. head(ds)
  143. tail(ds)
  144. str(ds)
  145. summary(ds)


  146. ## ----build_nb_model, out.lines=26----------------------------------------
  147. library(e1071)
  148. model      <- naiveBayes(form, data=ds[train, vars])
  149. model


  150. ## ----evaluate_nb_model, message=FALSE, out.lines=NULL--------------------
  151. classes    <- predict(model, ds[test, vars], type="class")
  152. acc        <- sum(classes == actual, na.rm=TRUE)/length(actual)
  153. err        <- sum(classes != actual, na.rm=TRUE)/length(actual)
  154. predicted  <- predict(model, ds[test, vars], type="raw")[,2]
  155. pred       <- prediction(predicted, ds[test, target])
  156. ate        <- attr(performance(pred, "auc"), "y.values")[[1]]
  157. riskchart(predicted, actual, risks)
  158. round(table(actual, classes, dnn=c("Actual", "Predicted"))/length(actual), 2)


  159. ## ----common_outtro, child="finale.Rnw", eval=TRUE------------------------


  160. ## ----syinfo, child="sysinfo.Rnw", eval=TRUE------------------------------

  161. ## ----echo=FALSE, message=FALSE-------------------------------------------
  162. require(Hmisc)
  163. pkg <- "knitr"
  164. pkg.version <- installed.packages()[pkg, 'Version']
  165. pkg.date <- installed.packages(fields="Date")[pkg, 'Date']
  166. pkg.info <- paste(pkg, pkg.version, pkg.date)

  167. rev <- system("bzr revno", intern=TRUE)
  168. cpu <- system(paste("cat /proc/cpuinfo | grep 'model name' |",
  169.                     "head -n 1 | cut -d':' -f2"), intern=TRUE)
  170. ram <- system("cat /proc/meminfo | grep MemTotal: | awk '{print $2}'",
  171.               intern=TRUE)
  172. ram <- paste0(round(as.integer(ram)/1e6, 1), "GB")
  173. user <- Sys.getenv("LOGNAME")
  174. node <- Sys.info()[["nodename"]]
  175. user.node <- paste0(user, "@", node)
  176. gcc.version <- system("g++ -v 2>&1 | grep 'gcc version' | cut -d' ' -f1-3",
  177.                       intern=TRUE)
  178. os <- system("lsb_release -d | cut -d: -f2 | sed 's/^[ \t]*//'", intern=TRUE)
复制代码

使用道具

藤椅
Elena3 发表于 2015-6-13 08:02:03 |只看作者 |坛友微信交流群

使用道具

板凳
bingyang1008 发表于 2015-6-13 08:10:31 |只看作者 |坛友微信交流群
感谢分享

使用道具

报纸
duoduoduo 在职认证  发表于 2015-6-13 08:25:04 |只看作者 |坛友微信交流群
en
好像还不错你发的

使用道具

地板
fengyg 企业认证  发表于 2015-6-13 08:32:09 |只看作者 |坛友微信交流群
kankan

使用道具

7
lhf8059 发表于 2015-6-13 09:22:49 |只看作者 |坛友微信交流群
看看!

使用道具

8
YONGHU33 发表于 2015-6-13 11:03:45 |只看作者 |坛友微信交流群
看看,谢谢!

使用道具

9
mike68097 发表于 2015-6-13 12:06:29 |只看作者 |坛友微信交流群

使用道具

10
nieqiang110 学生认证  发表于 2015-6-13 19:36:58 |只看作者 |坛友微信交流群
ccccccccccccccccccccccccccccccccc

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-4-20 08:30