本文簡要介紹python語言中 torch.nn.BCEWithLogitsLoss 的用法。
用法:
class torch.nn.BCEWithLogitsLoss(weight=None, size_average=None, reduce=None, reduction='mean', pos_weight=None)weight(Tensor,可選的) -手動重新調整每個批次元素損失的權重。如果給定,則必須是大小為
nbatch的張量。size_average(bool,可選的) -已棄用(請參閱
reduction)。默認情況下,損失是批次中每個損失元素的平均值。請注意,對於某些損失,每個樣本有多個元素。如果字段size_average設置為False,則會對每個小批量的損失求和。當reduce為False時忽略。默認值:Truereduce(bool,可選的) -已棄用(請參閱
reduction)。默認情況下,根據size_average對每個小批量的觀察結果進行平均或求和。當reduce是False時,返回每個批次元素的損失並忽略size_average。默認值:Truereduction(string,可選的) -指定要應用於輸出的縮減:
'none'|'mean'|'sum'。'none':不應用減少,'mean':輸出的總和將除以輸出中的元素數,'sum':輸出將被求和。注意:size_average和reduce正在被棄用,同時,指定這兩個參數中的任何一個都將覆蓋reduction。默認值:'mean'pos_weight(Tensor,可選的) -大量的正麵例子。必須是長度等於類數的向量。
這種損失將
Sigmoid層和BCELoss組合在一個類中。這個版本比使用簡單的Sigmoid後跟BCELoss在數值上更穩定,因為通過將操作組合到一層,我們利用 log-sum-exp 技巧來實現數值穩定性。未減少的(即
reduction設置為'none')損失可以說明為:其中 是批量大小。如果
reduction不是'none'(默認'mean'),那麽這用於測量例如auto-encoder 中的重建誤差。請注意,目標
t[i]應該是 0 到 1 之間的數字。可以通過向正例添加權重來權衡召回率和精度。在多標簽分類的情況下,損失可以說明為:
其中是類號(用於多標簽二分類,用於single-label二分類),是批次中的樣本數,是權重 類的肯定答案。
提高召回率, 提高精度。
例如,如果數據集包含單個類的 100 個正樣本和 300 個負樣本,則該類的
pos_weight應該等於 。損失將表現為數據集包含 正例。例子:
>>> target = torch.ones([10, 64], dtype=torch.float32) # 64 classes, batch size = 10 >>> output = torch.full([10, 64], 1.5) # A prediction (logit) >>> pos_weight = torch.ones([64]) # All weights are equal to 1 >>> criterion = torch.nn.BCEWithLogitsLoss(pos_weight=pos_weight) >>> criterion(output, target) # -log(sigmoid(1.5)) tensor(0.2014)- 形狀:
輸入: ,其中 表示任意數量的維度。
目標:,與輸入的形狀相同。
輸出:標量。如果
reduction是'none',那麽 ,與輸入的形狀相同。
例子:
>>> loss = nn.BCEWithLogitsLoss() >>> input = torch.randn(3, requires_grad=True) >>> target = torch.empty(3).random_(2) >>> output = loss(input, target) >>> output.backward()
參數:
相關用法
- Python PyTorch BCELoss用法及代碼示例
- Python PyTorch Bernoulli用法及代碼示例
- Python PyTorch Binomial用法及代碼示例
- Python PyTorch BucketBatcher用法及代碼示例
- Python PyTorch BatchSampler用法及代碼示例
- Python PyTorch BatchNorm1d用法及代碼示例
- Python PyTorch Bilinear用法及代碼示例
- Python PyTorch BatchNorm3d用法及代碼示例
- Python PyTorch Batcher用法及代碼示例
- Python PyTorch Beta用法及代碼示例
- Python PyTorch BatchNorm2d用法及代碼示例
- Python PyTorch frexp用法及代碼示例
- Python PyTorch jvp用法及代碼示例
- Python PyTorch cholesky用法及代碼示例
- Python PyTorch vdot用法及代碼示例
- Python PyTorch ELU用法及代碼示例
- Python PyTorch ScaledDotProduct.__init__用法及代碼示例
- Python PyTorch gumbel_softmax用法及代碼示例
- Python PyTorch get_tokenizer用法及代碼示例
- Python PyTorch saved_tensors_hooks用法及代碼示例
- Python PyTorch positive用法及代碼示例
- Python PyTorch renorm用法及代碼示例
- Python PyTorch AvgPool2d用法及代碼示例
- Python PyTorch MaxUnpool3d用法及代碼示例
- Python PyTorch Tensor.unflatten用法及代碼示例
注:本文由純淨天空篩選整理自pytorch.org大神的英文原創作品 torch.nn.BCEWithLogitsLoss。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
