hxd1011 hxd1011 - 2 months ago 9
R Question

Vectorize nested for loops in R (for multi class logistic loss calculation)

I am calculating the cost for a data set. Is there any way to simplify this nested for loop? Should I use apply or matrix multiplication?

More Background: this is muti-class logistic loss will be used in machine learning. and y_m is a indicator matrix that derived from label y (classification for 10 labels). I am simplify the problem to have a minimal reproducible code by randomly generate h2 and y.

h2=matrix(runif(5000*10),ncol=10)
y=round(runif(5000)*9)+1

y_m <- matrix(0,ncol=10,nrow=length(y))
y_m[cbind(1:length(y),y)] <- 1

J=0
for(i in 1:5000){
for(k in 1:10){
J=J-y_m[i,k]*log(h2[i,k])-(1-y_m[i,k])*log(1-h2[i,k]);
}
}
J

Answer

Try this:

J <- sum(-y_m*log(h2)-(1-y_m)*log(1-h2))
Comments