最新消息: 新版网站上线了!!!

浅谈Pytorch中的torch.gather函数的含义

pytorchÖеÄgatherº¯Êý

pytorch±Ètensorflow¸ü¼Ó±à³ÌÓѺã¬ËùÒÔ×¼±¸ÓÃpytorchÊÔ×Å×ö×î½üÒª×öµÄһЩʵÑé¡£

Á¢¸öflag¿ªÊ¼Ñ§Ï°pytorch£¬Ð¿ªÒ»¸ö·ÖÀàÕûÀíѧϰpytorchÖеÄһЩ²Èµ½µÄÄà¿Ó¡£

½ñÌì¸Õ¿ªÊ¼½Ó´¥£¬¶ÁÁËÒ»ÏÂdocumentation£¬Ð´Ò»¸öÒ»¿ªÊ¼Ã¿Ì«¸ã¶®µÄº¯Êýgather

b = torch.Tensor([[1,2,3],[4,5,6]])
print b
index_1 = torch.LongTensor([[0,1],[2,0]])
index_2 = torch.LongTensor([[0,1,1],[0,0,0]])
print torch.gather(b, dim=1, index=index_1)
print torch.gather(b, dim=0, index=index_2)

¹Û²ìËüµÄÊä³ö½á¹û£º

 1 2 3
 4 5 6
[torch.FloatTensor of size 2x3]


 1 2
 6 4
[torch.FloatTensor of size 2x2]


 1 5 6
 1 2 3
[torch.FloatTensor of size 2x3]

ÕâÀïÊǹٷ½ÎĵµµÄ½âÊÍ

torch.gather(input, dim, index, out=None) ¡ú Tensor

 Gathers values along an axis specified by dim.

 For a 3-D tensor the output is specified by:

 out[i][j][k] = input[index[i][j][k]][j][k] # dim=0
 out[i][j][k] = input[i][index[i][j][k]][k] # dim=1
 out[i][j][k] = input[i][j][index[i][j][k]] # dim=2

 Parameters: 

  input (Tensor) ¨C The source tensor
  dim (int) ¨C The axis along which to index
  index (LongTensor) ¨C The indices of elements to gather
  out (Tensor, optional) ¨C Destination tensor

 Example:

 >>> t = torch.Tensor([[1,2],[3,4]])
 >>> torch.gather(t, 1, torch.LongTensor([[0,0],[1,0]]))
  1 1
  4 3
 [torch.FloatTensor of size 2x2]

¿ÉÒÔ¿´³ö£¬gatherµÄ×÷ÓÃÊÇÕâÑùµÄ£¬indexʵ¼ÊÉÏÊÇË÷Òý£¬¾ßÌåÊÇÐл¹ÊÇÁеÄË÷ÒýÒª¿´Ç°Ãædim µÄÖ¸¶¨£¬±ÈÈç¶ÔÓÚÎÒÃǵÄÀõ×Ó£¬¡¾1,2,3;4,5,6,¡¿£¬Ö¸¶¨dim=1£¬Ò²¾ÍÊǺáÏò£¬ÄÇôË÷Òý¾ÍÊÇÁкš£indexµÄ´óС¾ÍÊÇÊä³öµÄ´óС£¬ËùÒÔ±ÈÈçindexÊÇ¡¾1,0;0,0¡¿£¬ÄÇô¿´indexµÚÒ»ÐУ¬1ÁÐÖ¸µÄÊÇ2£¬ 0ÁÐÖ¸µÄÊÇ1£¬Í¬Àí£¬µÚ¶þÐÐΪ4£¬4 ¡£ÕâÑù¾ÍÊäÈëΪ¡¾2,1;4,4¡¿£¬²Î¿¼ÕâÑùµÄ½âÊÍ¿´ÉÏÃæµÄÊä³ö½á¹û£¬¼´¿ÉÀí½âgatherµÄº¬Òå¡£

gatherÔÚone-hotΪÊä³öµÄ¶à·ÖÀàÎÊÌâÖУ¬¿ÉÒÔ°Ñ×î´óÖµ×ø±ê×÷Ϊindex´«½øÈ¥£¬È»ºóÌáÈ¡µ½Ã¿Ò»ÐеÄÕýÈ·Ô¤²â½á¹û£¬ÕâÒ²ÊÇgather¿ÉÄܵÄÒ»¸ö×÷Óá£

ÒÔÉÏÕâƪdz̸PytorchÖеÄtorch.gatherº¯ÊýµÄº¬Òå¾ÍÊÇС±à·ÖÏí¸ø´ó¼ÒµÄÈ«²¿ÄÚÈÝÁË£¬Ï£ÍûÄܸø´ó¼ÒÒ»¸ö²Î¿¼£¬Ò²Ï£Íû´ó¼Ò¶à¶àÖ§³Ö½Å±¾Ö®¼Ò¡£

转载请注明:谷谷点程序 » 浅谈Pytorch中的torch.gather函数的含义