簡體   English   中英

在 R 中使用 xgboost 進行多類分類

[英]Multiclass Classification with xgboost in R

我正在嘗試使用 xgboost 包在 R 中進行多類(特別是 4 個類)分類。 我一直在對 2 個類別進行二元分類,但無法使其對 4 個類別起作用。我遇到的問題是預測函數的輸出只是概率,而不是實際的類別預測,即 0-3。

prediction <- predict(xgboost.model, as.matrix(df.test[,1:(ncol(df.test)-1)]))

最后一列是我的目標變量。

預期的

[1] 0 1 0 2 3 0 0 1 

實際的

[1] 0.1940184 0.2905097 0.3002516 0.2152203 0.3094974 0.2442986 0.1251981 0.3210058

對於那些想知道分辨率要求我遍歷 df.test 數據幀的每一行的人,因為它似乎沒有批量工作。 代碼是:

prediction <- data.frame()
    for(l in 1:nrow(df.test)){
      prediction1 <- predict(xgboost.model, as.matrix(df.test[l,1:(ncol(df.test)-1)])) %>% t() %>% as.data.frame()
      colnames(prediction1) <- as.character(classes2)
      prediction1$prediction <- names(prediction1)[apply(prediction1, 1, which.max)]
      prediction <- rbind(prediction, prediction1)
    }
    pred.perc <- prediction %>% dplyr::select(-c(prediction))
    prediction <- prediction %>% dplyr::select(prediction)

如果您使用apply函數會容易得多,因為它可以為您節省大量空間,並且您基本上可以在一行中編寫所有內容。 apply函數系列非常節省計算並為您節省大量時間。 這些函數允許以多種方式交叉數據並避免顯式使用循環結構,請在此處閱讀應用函數

但是要回答您的問題,您可以這樣做:

# Use the predicted label with the highest probability
prediction$label = apply(prediction,1,function(x) colnames(prediction)[which.max(x)])

這將找到每個樣本的最大概率並將最大概率的類分配給列label

暫無
暫無

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

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