2013-12-07 41 views
3

應我在R中,使用什麼命令具有用於rpart()predict()和命令以生成一個預測模型之後執行混淆矩陣?的R - 什麼命令使用從rpart包輸入的結果以產生混淆矩陣()和預測()?

# Grow tree 
library(rpart) 
fit <- rpart(activity ~ ., method="class", data=train.data) 

printcp(fit) # display the results 
plotcp(fit) # visualize cross-validation results 
summary(fit) # detailed summary of splits 

# Prune the tree (in my case is exactly the same as the initial model) 
pfit <- prune(fit, cp=0.10) # from cptable 
pfit <- prune(fit,cp=fit$cptable[which.min(fit$cptable[,"xerror"]),"CP"]) 

# Predict using the test dataset 
pred1 <- predict(fit, test.data, type="class") 

# Show re-substitution error 
table(train.data$activity, predict(fit, type="class")) 

# Accuracy rate 
sum(test.data$activity==pred1)/length(pred1) 

我想以明確的方式來概括真陽性,假陰性,假陽性和真陰性。具有相同矩陣敏感性,特異性,正向預測值和負向預測值也是很好的。

Relationships among terms 來源:http://en.wikipedia.org/wiki/Sensitivity_and_specificity

+0

也許你可以在新的變數來自兩個模型的預測,並表(DF $ rpart包,DF $預測),其中DF是您在分析數據幀。 – Duck

回答

1

使用predict()方法中,用適合和原始數據幀,像這樣:

pred = predict(train.fit, newdata, type = "vector") 
newdata$pred = as.vector(pred) 
newdata$prediction = activities[newdata$pred] 

tab = table (newdata$prediction, newdata$activity) 
print(tab) 

在上面的例子中,軟件rpart模型預測的活性(一因子變量)。 pred是數字,其值與該因子的級別相對應。 activities = sort(unique(data$activity))對應於默認的因子映射。

+0

我通常喜歡用 confmat <添加上 - 表(newdata $類,predicted_classes) 精度=(confmat [1] + confmat [5] + confmat [9])/ SUM(confmat) confmat 的sprintf (「準確度是%f」,準確度) – Max