pytorch masked fill方法簡單理解

2021-10-12 09:20:42 字數 2084 閱讀 8252

>>> help(torch.tensor.masked_fill)

help on method_descriptor:

masked_fill(...)

masked_fill(mask, value) -> tensor

out-of-place version of :meth:`torch.tensor.masked_fill_`

>>> help(torch.tensor.masked_fill_)

help on method_descriptor:

masked_fill_(...)

masked_fill_(mask, value)

fills elements of :attr:`self` tensor with :attr:`value` where :attr:`mask` is

true. the shape of :attr:`mask` must be

:ref:`broadcastable

` with the shape of the underlying

tensor.

args:

mask (booltensor): the boolean mask

value (float): the value to fill in with

masked_fill方法有兩個引數,maske和value,mask是乙個pytorch張量(tensor),元素是布林值,value是要填充的值,填充規則是mask中取值為true位置對應於self的相應位置用value填充。

>>> t = torch.randn(3,2)

>>> t

tensor([[-0.9180, -0.4654],

[ 0.9866, -1.3063],

[ 1.8359, 1.1607]])

>>> m = torch.randint(0,2,(3,2))

>>> m

tensor([[0, 1],

[1, 1],

[1, 0]])

>>> m == 0

tensor([[ true, false],

[false, false],

[false, true]])

>>> t.masked_fill(m == 0, -1e9)

tensor([[-1.0000e+09, -4.6544e-01],

[ 9.8660e-01, -1.3063e+00],

[ 1.8359e+00, -1.0000e+09]])

注意:引數m必須與t的size相同或者兩者是可廣播(broadcasting-semantics)的 如下

>>> m = torch.randint(0, 2, (3, 1))

>>> m

tensor([[0],

[1],

[1]])

# m和t是可廣播的

>>> t.masked_fill(m == 0, -1e9)

tensor([[-1.0000e+09, -1.0000e+09],

[ 9.8660e-01, -1.3063e+00],

[ 1.8359e+00, 1.1607e+00]])

>>> m = torch.randint(0, 2, (3, 3))

>>> m

tensor([[0, 0, 0],

[1, 1, 0],

[1, 1, 1]])

# m和t是不可廣播的

>>> t.masked_fill(m == 0, -1e9)

traceback (most recent call last):

file "", line 1, in runtimeerror: the size of tensor a (3) must match the size of tensor b (2) at non-singleton dimension 1

關於廣播(broadcasting-semantics),可參考pytorch 廣播語義(broadcasting semantics)

pytorch masked fill方法簡單理解

help torch.tensor.masked fill help on method descriptor masked fill masked fill mask,value tensor out of place version of meth torch.tensor.masked fil...

Spring Cloud Eureka簡單理解

eureka服務治理基礎架構包括三個核心要素。1 服務註冊中心 eureka分為客戶端和服務端,eureka服務端提供服務註冊與發現的功能。2 服務提供者 提供服務的應用,spring boot應用或者遵循eureka通訊機制的應用。將應用自己註冊到eureka註冊中心,以供其它應用的發現。3 服務...

Java Method的invoke簡單理解

首先method類代表乙個方法,所以invoke 呼叫 就是呼叫method類代表的方法。它可以讓你實現動態呼叫,例如你可以動態的傳人引數。下面是乙個簡單的例子。public class methodtest class clazz test.class trycatch nosuchmethode...