gpt4 book ai didi

r - 如何计算机器学习中的对数损失

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:07:14 24 4
gpt4 key购买 nike

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

library(randomForest) 

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

则预测结果如下:

enter image description here

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

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

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

最佳答案

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)

关于r - 如何计算机器学习中的对数损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38282377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com