PyTorch常用函數:torch.topk; torch.index_select; torch.lt


torch.topk

torch.topk(input, k, dim=None, largest=True, sorted=True, out=None) -> (Tensor, LongTensor)
 pytorch中文官網文檔:http://www.mamicode.com/info-detail-2217311.html

沿給定dim維度返回輸入張量input中 k 個最大值。
如果不指定dim,則默認為input的最后一維。
如果為largest為 False ,則返回最小的 k 個值。

返回一個元組 (values,indices),其中indices是原始輸入張量input中測元素下標。
如果設定布爾值sorted 為_True_,將會確保返回的 k 個值被排序。

參數:

input (Tensor) – 輸入張量
k (int) – “top-k”中的k
dim (int, optional) – 排序的維
largest (bool, optional) – 布爾值,控制返回最大或最小值
sorted (bool, optional) – 布爾值,控制返回值是否排序
out (tuple, optional) – 可選輸出張量 (Tensor, LongTensor) output buffer
------------------------------------實例------------------------------------
假設神經網絡的輸出如下,為二分類。batch_size=4

import torch

output = torch.tensor([[-5.4783, 0.2298],
[-4.2573, -0.4794],
[-0.1070, -5.1511],
[-0.1785, -4.3339]])
得到其top1值操作如下:

maxk = max((1,)) # 取top1准確率,若取top1和top5准確率改為max((1,5))
_, pred = output.topk(maxk, 1, True, True)
topk參數中,maxk取得是top1准確率,dim=1是按行取值, largest=1是取最大值

結果如下,

_
tensor([[ 0.2298],
[-0.4794],
[-0.1070],
[-0.1785]])
pred
tensor([[1],
[1],
[0],
[0]])
 

_是top1的值,pred是最大值的索引(size=4*1),一般會進行轉置處理同真實值對比

index_select

anchor_w = self.FloatTensor(self.scaled_anchors).index_select(1, self.LongTensor([0]))

參數說明:index_select(x, 1, indices)

1代表維度1,即列,indices是篩選的索引序號。

例子:

import torch


x = torch.linspace(1, 12, steps=12).view(3,4)

print(x)
indices = torch.LongTensor([0, 2])
y = torch.index_select(x, 0, indices)
print(y)

z = torch.index_select(x, 1, indices)
print(z)

z = torch.index_select(y, 1, indices)
print(z)
 

結果:

tensor([[  1.,   2.,   3.,   4.],
        [  5.,   6.,   7.,   8.],
        [  9.,  10.,  11.,  12.]])
tensor([[  1.,   2.,   3.,   4.],
        [  9.,  10.,  11.,  12.]])
tensor([[  1.,   3.],
        [  5.,   7.],
        [  9.,  11.]])
tensor([[  1.,   3.],
        [  9.,  11.]])

torch.lt

torch.lt(inputotherout=None) → Tensor

Computes \text{input} < \text{other}input<other element-wise.

The second argument can be a number or a tensor whose shape is broadcastable with the first argument.

Parameters
  • input (Tensor) – the tensor to compare

  • other (Tensor or python:float) – the tensor or value to compare

  • out (Tensoroptional) – the output tensor that must be a BoolTensor

Returns

torch.BoolTensor containing a True at each location where comparison is true

Return type

Tensor

Example:

>>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) tensor([[False, False], [True, False]])

主要參考:
https://blog.csdn.net/u014264373/article/details/86525621
https://blog.csdn.net/jacke121/article/details/83044660
https://pytorch.org/docs/stable/torch.html#torch.lt


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM