如何在 R 中做决策树?
How to do decision trees in R?
我通常在 SPSS 中做决策树以从 DDBB 获取目标,我做了一些研究,发现有三个包:tree、party 和 rpart 可用于 R,但哪个更好任务?
谢谢!
之前用过rpart,很好用。我通过拆分训练和测试集来进行预测建模。这是代码。希望这会给你一些想法......
library(rpart)
library(rattle)
library(rpart.plot)
### Build the training/validate/test...
data(iris)
nobs <- nrow(iris)
train <- sample(nrow(iris), 0.7*nobs)
test <- setdiff(seq_len(nrow(iris)), train)
colnames(iris)
### The following variable selections have been noted.
input <- c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width")
numeric <- c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width")
categoric <- NULL
target <-"Species"
risk <- NULL
ident <- NULL
ignore <- NULL
weights <- NULL
#set.seed(500)
# Build the Decision Tree model.
rpart <- rpart(Species~.,
data=iris[train, ],
method="class",
parms=list(split="information"),
control=rpart.control(minsplit=12,
usesurrogate=0,
maxsurrogate=0))
# Generate a textual view of the Decision Tree model.
print(rpart)
printcp(rpart)
# Decision Tree Plot...
prp(rpart)
dev.new()
fancyRpartPlot(rpart, main="Decision Tree Graph")
我通常在 SPSS 中做决策树以从 DDBB 获取目标,我做了一些研究,发现有三个包:tree、party 和 rpart 可用于 R,但哪个更好任务?
谢谢!
之前用过rpart,很好用。我通过拆分训练和测试集来进行预测建模。这是代码。希望这会给你一些想法......
library(rpart)
library(rattle)
library(rpart.plot)
### Build the training/validate/test...
data(iris)
nobs <- nrow(iris)
train <- sample(nrow(iris), 0.7*nobs)
test <- setdiff(seq_len(nrow(iris)), train)
colnames(iris)
### The following variable selections have been noted.
input <- c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width")
numeric <- c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width")
categoric <- NULL
target <-"Species"
risk <- NULL
ident <- NULL
ignore <- NULL
weights <- NULL
#set.seed(500)
# Build the Decision Tree model.
rpart <- rpart(Species~.,
data=iris[train, ],
method="class",
parms=list(split="information"),
control=rpart.control(minsplit=12,
usesurrogate=0,
maxsurrogate=0))
# Generate a textual view of the Decision Tree model.
print(rpart)
printcp(rpart)
# Decision Tree Plot...
prp(rpart)
dev.new()
fancyRpartPlot(rpart, main="Decision Tree Graph")