lavender99:

num = pred.size(0)


What is num? I guess it is the size of mini-batch, the number of training examples, or the number of classes. If it is the size of mini-batch or the number of training examples, you can calculate per-example dice coefficients by using sum(dim=1) instead of sum().