Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implent tf.nn.in_top_k in pytorch

I want to implent tf.nn.in_top_k in pytorch. Here is the link of tf.nn.in_top_k,

tf.math.in_top_k(
    targets, predictions, k, name=None
)

It computed precision at k as a bool Tensor and will return a Tensor of type bool.

tf.nn.in_top_k

I wonder whether there are similar api in pytorch?

like image 412
rosefun Avatar asked Feb 02 '26 10:02

rosefun


1 Answers

AFAIK there is no equivalent in_top_k function built into pytorch. It's relatively straightforward to write one. For example

def in_top_k(targets, preds, k):
    topk = preds.topk(k)[1]
    return (targets.unsqueeze(1) == topk).any(dim=1)
like image 181
jodag Avatar answered Feb 03 '26 23:02

jodag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!