2016-07-09 6 views
2

Der folgende Code wird verwendet, um die Wahrscheinlichkeitsausgabe der binären Klassifizierung mit zufälliger Gesamtstruktur zu erzeugen.So berechnen Sie Protokollverlust beim maschinellen Lernen

library(randomForest) 

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

Dann wird das Ergebnis über Vorhersage ist wie folgt:

enter image description here

Die wahre Label über Testdaten bekannt sind (genannt test_label). Jetzt möchte ich logarithmic loss für die Wahrscheinlichkeitsausgabe der binären Klassifikation berechnen. Die Funktion über LogLoss ist wie folgt.

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

Wie logarithmischen Verlust mit Wahrscheinlichkeitsausgabe der binären Klassifizierung zu berechnen. Vielen Dank.

Antwort

5
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)