2017-08-04 20 views
0

我有使用隨機森林算法的訓練模型。現在我想在僅包含一條記錄的數據集上使用此模型預測結果。按照列車數據幀更改測試數據幀的級別

當我試圖執行預測命令時,拋出以下錯誤。

prediction.randomForest中的錯誤(model,test1,type =「response」): 新數據中預測變量的類型與培訓數據的類型不匹配。

注意到這是因爲訓練和測試數據框中因素變量的級別不同。

所以我發現stakoverflow一個解決方案使用腳本

common <- intersect(names(train), names(test1)) 
for (p in common) { if (class(train[[p]]) == "factor") { levels(test1[[p]]) <- levels(train[[p]]) } } 

請參考以下鏈接查詢修改的水平。

r random forest error - type of predictors in new data do not match

但不幸的是它改變了大多數變量的數據值。

例如:

在TEST1數據幀有一個變量名「類別」具有值「> = 100」,它改變爲「11-50」

回答

0

我們只需要爲factor改變類

nm1 <- names(which(sapply(train, is.factor))) 
for (p in nm1) { 
    levels(test1[[p]]) <- levels(train[[p]]) 
} 

如果是基於randomForest,我們甚至不用去尋找train數據。獲得從model對象xlevels並指定基於該

lvlslst <- model[["forest"]][["xlevels"]] 
lvlsCols <- names(lvlslst)[sapply(lvlslst, is.character)] 
for(j in lvlsCols) { 
    levels(test1[[j]]) <- lvlslst[[j]] 

} 
+0

感謝您的答覆「測試1」欄目的levels。我嘗試了您提供的兩種解決方案,但它也會在測試數據框中更改值。 – user3734568

+0

@ user3734568我只是在你的代碼中分配'levels',並且沒有改變任何東西。你必須檢查你的數據集 – akrun

+0

感謝您的回覆。我認爲在我的test1數據中只有一行,對於第一級「> = 100」,但我的列車數據有400條記錄,類別有3個級別「11-50」,「51-100」和「> = 100」 。當我使用腳本級別(test1 [[p]])< - levels(train [[p]])時,對於測試1,它似乎考慮了列車樣本的第一個級別,並用列車數據框架中的第1級替換值。 – user3734568