簡體   English   中英

如何根據R中的決策樹模型測試數據?

[英]How do I test data against a decision tree model in R?

我使用R中的rpart包從訓練數據構建了一個決策樹。現在我有更多數據,我想在樹上檢查它以檢查模型。 邏輯/迭代,我想做以下事情:

for each datapoint in new data
     run point thru decision tree, branching as appropriate
     examine how tree classifies the data point
     determine if the datapoint is a true positive or false positive

我如何在R中做到這一點?

為了能夠使用它,我假設您將訓練集分成子集訓練集和測試集。

要創建訓練模型,您可以使用:

model <- rpart(y~., traindata, minbucket=5)   # I suspect you did it so far.

要將其應用於測試集:

pred <- predict(model, testdata) 

然后,您將獲得預測結果的向量。

在您的訓練測試數據集中,您也有“真實”的答案。 讓我們說一下訓練集中的最后一列。

簡單地將它們等同將產生結果:

pred == testdata[ , last]  # where 'last' equals the index of 'y'

當元素相等時,你會得到一個真,當你得到一個假,這意味着你的預測是錯誤的。

pred + testdata[, last] > 1 # gives TRUE positive, as it means both vectors are 1
pred == testdata[, last]    # gives those that are correct

看看你有多少正確率可能會很有趣:

mean(pred == testdata[ , last])    # here TRUE will count as a 1, and FALSE as 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM