【问题标题】:How to compute log loss in machine learning如何计算机器学习中的日志损失
【发布时间】:2016-11-11 22:48:51
【问题描述】:

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

library(randomForest) 

rf <- randomForest(train, train_label,importance=TRUE,proximity=TRUE)
prediction<-predict(rf, test, type="prob")

那么预测结果如下:

关于测试数据的真实标签是已知的(命名为 test_label)。现在我想计算logarithmic loss 用于二进制分类的概率输出。关于LogLoss的函数如下。

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

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

【问题讨论】:

    标签: r algorithm machine-learning classification


    【解决方案1】:
    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)
    

    【讨论】:

      【解决方案2】:

      我认为 logLoss 公式有点错误。

      model <- glm(vs ~ mpg, data = mtcars, family = "binomial")
      
      ### Actual formula (Wrong)
      logLoss1 <- function(pred, actual){
        -1*mean(log(pred[model.matrix(~ actual + 0) - pred > 0]))
      }
      logLoss1(actual = model$y, pred = model$fitted.values)
      # [1] 0.4466049
      
      ### From ModelMetrics package
      ModelMetrics::logLoss(actual = model$y, pred = model$fitted.values)
      # [1] 0.3989584
      
      ### From MLmetrics package
      MLmetrics::LogLoss(y_pred = model$fitted.values, y_true = model$y)
      # [1] 0.3989584
      
      ### From reticulate package
      sklearn.metrics <- import("sklearn.metrics")
      sklearn.metrics$log_loss(y_true = model$y, y_pred = model$fitted.values)
      # [1] 0.3989584
      
      ### Native formula (Good) 
      logLoss2 <- function(pred, actual){
        -mean(actual * log(pred) + (1 - actual) * log(1 - pred))
      }
      logLoss2(actual = model$y, pred = model$fitted.values)
      # [1] 0.3989584
      

      我使用的是 R 版本 4.1.0 (2021-05-18)。

      【讨论】:

        猜你喜欢
        • 2021-04-15
        • 1970-01-01
        • 1970-01-01
        • 2020-06-09
        • 1970-01-01
        • 1970-01-01
        • 2016-05-16
        • 2017-12-16
        • 1970-01-01
        相关资源
        最近更新 更多