I have the following code writtein in lua.
I'd like to get indices for N maximum scores from scores
and their corresponding scores.
It looks like I will have to iteratively remove the current maximum value from scores
and retrieve the maximum again, but can't find an appropriate way to do it.
nqs=dataset['question']:size(1);
scores=torch.Tensor(nqs,noutput);
qids=torch.LongTensor(nqs);
for i=1,nqs,batch_size do
xlua.progress(i, nqs)
r=math.min(i+batch_size-1,nqs);
scores[{{i,r},{}}],qids[{{i,r}}]=forward(i,r);
-- print(scores)
end
tmp,pred=torch.max(scores,2);
I hope I did not misunderstand, since the code you show (especially the foor loop) does not really seem relevant to want you want to do. Anyway, here is how I'd do it.
sr=scores:view(-1,scores:size(1)*scores:size(2))
val,id=sr:sort()
--val is a row vector with the values stored in increasing order
--id will be the corresponding index in sr
--now you can slice val and id from the end to find the N values you want, then you can recover the original index in the scores matrix simply with
col=(index-1)%scores:size(2)+1
row=math.ceil(index/scores:size(2))
hope this helps.