I want to calculate the output sum_logloss (see below) across all levels of a factor (C1) using a data table formula. But the result is not what I expect. Here is a small example showing what I get and why I expect a different sum_logloss as outcome.
LogLoss <- function(actual, predicted, eps=0.00001) {
predicted <- pmin(pmax(predicted, eps), 1-eps)
-1/length(actual)*(sum(actual*log(predicted)+(1-actual)*log(1-predicted)))
}
# THIS RETURNS TOTAL LOGLOSS
TotalLogLossVector <- function(actual_vector, predicted_vector) {
sum(mapply(LogLoss, actual_vector, predicted_vector))
}
df = data.frame(C1=c(1,1,2,2,1), C2=c(4,5,4,5,5), click=c(1,0,0,1,1))
df <- data.table(df)
df
C1 C2 click
1: 1 4 1
2: 1 5 0
3: 2 4 0
4: 2 5 1
5: 1 5 1
df[,list(mean_CTR=mean(click),count=.N, sum_logloss=TotalLogLossVector(click,rep(mean_CTR,.N)) ),by=C1]
C1 mean_CTR count sum_logloss
1: 1 0.6666667 3 3.663061
2: 2 0.5000000 2 1.928626
LogLoss(1,0.6666667)
[1] 0.4054651
LogLoss(0,0.6666667)
[1] 1.098612
TotalLogLossVector(c(1,0,1), c(0.6666667,0.6666667,0.6666667))
[1] 1.909543
so sum_logloss for C1=1 should be 2 * LogLoss(1,0.6666667) + 1 * LogLoss(0,0.6666667) = 1.909543, and not 3.663061.