hxd1011 hxd1011 - 1 year ago 73
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.


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

for(i in 1:5000){
for(k in 1:10){

Answer Source

Try this:

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