Reputation: 21
Since I have learned metric 0/1 loss for multi-label classification, and I need to create that metric
so I would like to def check
that could count and return how many inside tensor between two tensors are actually matched
For Example
# Only second inside tensor are exactly equal
a = torch.tensor([[1,0,1,1], [1,0,1,1],[1,0,1,1]])
b = torch.tensor([[0,0,1,1], [1,0,1,1],[1,0,1,0]])
check(a,b) -> 1
AND
# Only second and third are exactly equal
c = torch.tensor([[1,0,1,1], [1,0,1,1],[1,0,1,1]])
d = torch.tensor([[0,0,1,1], [1,0,1,1],[1,0,1,1]])
check(c,d) -> 2
My question is that how could we define function check to retrieve 2 tensors and return the following expected output, Thank you in advanced
Upvotes: 0
Views: 278
Reputation: 21
I'm answering my question, Thanks to the combination of @Zwang
and @LudvigH advice,
There are many ways you can do this, subtracting one tensor from the other then summing values and finding the non zero tensors, to simply using python's built in == function. What have you tried? - Zwang
I tried one of his methods, and that's answering my question :D, and fixed bug by @Ludvigs
def check(a,b):
assert a.size() == b.size()
diff_tensor = a - b # [1,0,0,0],[0,0,0,0],[0,0,0,0]
diff_tensor = torch.abs(diff_tensor) # In case summation of them are neglect to zero, Credit goes to @LudvigH
diff_scalar = torch.sum(diff_tensor, dim= 1) # [1 , 0 , 0]
return torch.numel(diff_scalar[diff_scalar==0])
Upvotes: 1