[英]Converting rpart output into JSON Format in R
我必須以交互模式繪制決策樹,這可以在JavaScript中完成,但是要做到這一點,我需要使用Json格式的rpart對象。
所以我想使用某些庫將rpart輸出轉換為JSON格式。
model <- rpart(formula=Species~Sepal.Length+Sepal.Width+Petal.Length+
Petal.Width,data=iris,na.action = na.rpart, method = "class",
parms = list(split="gini"),
control = rpart.control(minsplit= 10, cp= 0.005))
print(model)
產量
n= 150
node), split, n, loss, yval, (yprob)
* denotes terminal node
1) root 150 100 setosa (0.33333333 0.33333333 0.33333333)
2) PetalLength< 2.45 50 0 setosa (1.00000000 0.00000000 0.00000000) *
3) PetalLength>=2.45 100 50 versicolor (0.00000000 0.50000000 0.50000000)
6) PetalWidth< 1.75 54 5 versicolor (0.00000000 0.90740741 0.09259259)
12) PetalLength< 4.95 48 1 versicolor (0.00000000 0.97916667 0.02083333) *
13) PetalLength>=4.95 6 2 virginica (0.00000000 0.33333333 0.66666667) *
7) PetalWidth>=1.75 46 1 virginica (0.00000000 0.02173913 0.97826087) *
誰能告訴我如何將rpart對象轉換為Json?
在此先感謝您的幫助!
我們可以使用遞歸函數手動編寫JSON解析器。 這是一個小例子。 請注意以下事項;
與“ rpart”對象相比,“ party”對象編寫解析器要容易得多。 幸運的是,我們可以使用as.party()將任何“ rpart”對象轉換為“ party”
這只是顯示功能的簡單實現。 我們可以在每個節點上添加其他功能,例如node_size,node_parent等。
install.packages('partykit') json_prsr <- function(tree, node = 1, node_stats = NULL){ # Checking the decision tree object if(!is(tree, c("constparty","party"))) tree <- partykit::as.party(tree) # Parsing into json format str <- "" rule <- partykit:::.list.rules.party(tree, node) if(is.null(node_stats)) node_stats <- table(tree$fitted[1]) children <- partykit::nodeids(tree, node) if (length(children) == 1) { ct <- node_stats[as.character(children)] str <- paste("{","'name': '",children,"','size':",ct,",'rule':'",rule,"'}", sep='') } else { str <- paste("{","'name': '", node,"', 'rule': '", rule, "', 'children': [", sep='') for(child in children){ check <- paste("{'name': '", child, "'", sep='') if(child != node & ( !grepl(check, str, fixed=TRUE) ) ) { child_str <- json_prsr(tree, child, node_stats) str <- paste(str, child_str, ',', sep='') } } str <- substr(str, 1, nchar(str)-1) #Remove the comma str <- paste(str,"]}", sep='') } return(str) }
通過將json字符串粘貼到http://jsonlint.com/來檢查輸出JSON的有效性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.