I used 15 for dim1 since you are dealing with 15 classes (genres) as far as I’ve understood it.
Sure, let’s see what this line of code is actually doing.
torch.zeros(labels.size(0), 15) initializes a new tensor with all zeros in the shape of [batch_size, 15]. This should be the same shape as your model output. For dim1 I’m using the number of classes, so let’s call this dimension “class dimension”.
.scatter_ is an inplace method, which uses an index tensor (labels in this case) to fill the indices given by labels with a certain value in a specified dimension.
I’m using dim=1, since I would like to use the passed indices in labels ([1, 4, 1, 0, 5, 2]) to index dim1 (the “class dimension”).
Then I’m setting src=1. to fill all specified indices with the values of 1.
Does this explanation make sense to you? Let me know, if you need some further examples or explanations.
Yes, the loop look alright. You should use item() instead of .data, but besides that it looks good!