如何计算机器学习中的日志丢失

use*_*694 3 algorithm r classification machine-learning

以下代码用于生成随机森林的二进制分类的概率输出.

library(randomForest) 

rf <- randomForest(train, train_label,importance=TRUE,proximity=TRUE)
prediction<-predict(rf, test, type="prob")
Run Code Online (Sandbox Code Playgroud)

然后关于预测的结果如下:

在此输入图像描述

关于测试数据的真实标签是已知的(名为test_label).现在我想计算二进制分类概率输出的对数损失.关于LogLoss的功能如下.

LogLoss=function(actual, predicted)
{
  result=-1/length(actual)*(sum((actual*log(predicted)+(1-actual)*log(1-predicted))))
  return(result)
}
Run Code Online (Sandbox Code Playgroud)

如何用二进制分类的概率输出计算对数损失.谢谢.

cat*_*ure 6

library(randomForest) 

rf <- randomForest(Species~., data = iris, importance=TRUE, proximity=TRUE)
prediction <- predict(rf, iris, type="prob")
#bound the results, otherwise you might get infinity results
prediction <- apply(prediction, c(1,2), function(x) min(max(x, 1E-15), 1-1E-15)) 

#model.matrix generates a true probabilities matrix, where an element is either 1 or 0
#we subtract the prediction, and, if the result is bigger than 0 that's the correct class
logLoss = function(pred, actual){
  -1*mean(log(pred[model.matrix(~ actual + 0) - pred > 0]))
}

logLoss(prediction, iris$Species)
Run Code Online (Sandbox Code Playgroud)