ARCHIVE sources/0254/r01/s.zip
MEMBER README.md SHA256 b75a0f352e98a3f01a261cff11c7cf9494d1b78f3860783bfe0beece6c354143
1: # 🔂 *EnsLoss*: Stochastic Calibrated Loss Ensembles for Preventing Overfitting in Classification 
2: 
3: [![Python](https://badges.aleen42.com/src/python.svg)](https://www.python.org/)
4: [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/statmlben/ensLoss/pulls)
5: 
6: ## Introduction
7: 
8: Empirical risk minimization (ERM) with a computationally feasible surrogate loss is a widely accepted approach for binary classification. Specifically, given a training dataset $(\mathbf{x}\_i, y_i)_{i=1}^n$, the $\phi$-classification framework is formulated as:
9: 
10: <a href="https://github.com/statmlben/ensloss"><img src="./fig/loss.png" align="right" height="200" /></a>
11: 
12: $$
13: \min\_{f \in \mathcal{F}} \frac{1}{n} \sum_{i=1}^n \phi ( y_i f(\mathbf{x}\_i) ),
14: $$
15: 
16: where $\phi$ is a computing loss function to facilitate the empirical computation. Notably, most successful classification methods fall within this ERM framework, utilizing various loss functions and functional spaces. 
17: 
18: For example, typical losses including the hinge loss $\phi(z) = (1 - z)_+$ for SVMs, the exponential loss $\phi(z) = \exp(-z)$ for AdaBoost, and the logistic loss $\phi(z) = \log(1 + \exp(-z))$ for logistic regression, see the various loss function in the right figure.
19: 
20: Notably, the surrogate loss is not arbitrary, typically requiring *convexity* and *calibration* (CC) properties to ensure consistency in maximizing accuracy, which is summarized in the following theorem.
21: 
22: > **Theorem 1** (Classification-calibration; Bartlett et al., 2006). A convex loss function $\phi$ is classification-calibrated if and only if it is differentiable at 0 and $\phi'(0) < 0$.
23: 
24: **Motivative Question.** However, in practical applications, determining which loss function performs better is a very challenging problem, as it is typically unknown and can vary across datasets.
25: 
26: We examine two of the most popular losses: BCE and Hinge loss. We provide experimental results on 45 CIFAR2 datasets (see codes in [main_img.py](./main_image.py)), which also confirms that the superiority of the loss function is not consistent across different models / datasets.
27: 
28: | Model | ResNet34 | ResNet50 | VGG16 | VGG19 |
29: |-------|----------|----------|-------|-------|
30: | BCE > Hinge | 3 | 26 | 9 | 13 |
31: | Hinge > BCE | 42 | 19 | 36 | 22 |
32: 
33: 
34: ## Our Method: EnsLoss
35: 
36: In this project, we propose a novel loss ensemble method, namely **EnsLoss**, which extends the ensemble learning concept to combine losses within the ERM framework. Unlike existing ensemble methods, our method distinctively preserves the "*legitimacy*" of the combined losses, i.e., ensuring the CC properties.
37: 
38: - GitHub repo: [https://github.com/statmlben/ensloss](https://github.com/statmlben/ensloss)
39: - ICML 2025: [pdf](https://openreview.net/pdf?id=wP8meX6uJC)
40: 
41: This repo describes a set of experiments that demonstrate the performance of the proposed **EnsLoss** method compared with existing methods based on a *fixed loss function*, and also assess its *compatibility* with other regularization methods.
42: 
43: > **Quick overview.** Comparison of epoch-vs-test\_accuracy curves for various models on CIFAR2 (cat-dog) dataset using **EnsLoss** (ours) and other fixed losses (logistic (BCE), hinge, and exponential losses).
44: >
45: > ![overview](./fig/overview.png)
46: 
47: The proposed **EnsLoss** is optimal (over other loss functions; even over epoch-wise) on almost all 45 CIFAR2 datasets (with all other experimental setups kept identical), see the detailed results in [Benchmarks for Image Data](#benchmarks-for-image-data).
48: 
49: ## Motivation
50: 
51: ### {ensemble + CC} losses in SGD
52: The primary motivation behind consists of two components: **ensemble** and the **calibration** (CC conditions) of the loss functions.
53: 
54: ![demo](./fig/demo.png)
55: 
56: ### CC losses | CC loss-derivatives
57: 
58: The key observation of SGD is that the *impact of the loss function $\phi$ on SGD is solely reflected in its loss-derivative $\partial \phi$*. We only need to generate the valid loss derivatives; refer to the following figure illustrating the transformation of the CC conditions of losses into loss-derivatives.
59: 
60: ![CC](./fig/ensLoss_CC.png)
61: 
62: Hence, it allows us to bypass the generation of loss and directly generate the loss-derivatives in SGD, thereby inspires *doubly stochastic gradients* (i.e., random batch samples and random calibrated loss-derivatives) of our Algorithm.
63: 
64: ## Overview of the Experiments
65: 
66: Different **loss functions** can be integrated with **various neural networks** and **regularization methods** to tackle the classification problem across **diverse datasets**. In order to compare the advantages of our proposed method, we have provided reproducible benchmark code and results in this repository.
67: 
68: This repository supports:
69: 
70: - **Data Modes**
71:   - [x] Image data ([main_img.py](./main_image.py))
72:   - [x] Tabular data ([main_tab.py](./main_tab.py))
73:   - [ ] Text data ([main_text.py](./main_text.py))
74: 
75: - **Loss** ([losses.py](./losses.py))
76:   - [x] `ensLoss` (our method)
77:   - [x] `BCELoss`: binary cross entropy
78:   - [x] `Hinge`: hinge loss
79:   - [x] `EXP`: exponential loss
80:   - [x] `BinFocal`: binary focal loss
81: 
82: - **Model** ([img_models](./img_models/) + [tab_models](./tab_models/) + [text_models](./text_models/))
83:   - [x] VGG: `VGG16`, `VGG19`
84:   - [x] ResNet: `ResNet18`, `ResNet34`, `ResNet50`, `ResNet101`, `ResNet152`
85:   - [x] MobileNet: `MobileNet`, `MobileNetV2`
86:   - [x] DenseNet: `DenseNet121`, `DenseNet161`, `DenseNet169`, `DenseNet201`
87:   - [x] TabMLP\{D\} with different depths `D=1,3,5`
88:   - [x] LSTM: `LSTM`, `BiLSTM`
89: 
90: - **Regularization methods**
91:   - [x] `dropout` in [ResNet](./img_models/resnet.py)
92:   - [x] `weight_decay`
93:   - [x] `data augumentation` in [CIFAR](./loader.py)
94: 
95: Our running results are publicly available in both our W&B projects and this GitHub repository.
96: - **W&B projects**
97:   - [x] [ensLoss-tab](https://wandb.ai/bdai/ensLoss-tab?nw=nwuserbdai)
98:   - [x] [ensLoss-img](https://wandb.ai/bdai/ensLoss-img?nw=nwuserbdai)
99:   - [x] [ensLoss-txt](https://wandb.ai/bdai/ensLoss-txt?nw=nwuserbdai)
100: - **Markdown reports**
101:   - [x] [out_tab](./out/out_tab.md)
102:   - [x] [out_cifar](./out/out_cifar.md)
103:   - [x] [out_pcam](./out/out_pcam.md)
104:   - [x] [out_text](./out/out_text.md)
105:   - [x] [out_reg](./out/out_reg.md)
106: 
107: ## Benchmarks for Image Data
108: 
109: This benchmark contains two image datasets: [CIFAR10](https://www.cs.toronto.edu/~kriz/cifar.html) and [PCam](https://github.com/basveeling/pcam).
110: 
111: - **CIFAR.** The CIFAR10 dataset was originally designed for multiclass image classification. In our study, we construct (10 x 9) / 2 = 45 binary CIFAR datasets, denoted as CIFAR2, by selecting all possible pairs of two classes from the CIFAR10 dataset, which enables the evaluation of our method.
112: - **PCam.** The PCam dataset is an image binary classification dataset consisting of 327,680 96x96 color images derived from histopathologic scans of lymph node sections, with each image annotated with a binary label indicating the presence or absence of metastatic tissue.
113: 
114: ### Replicating Benchmark
115: The summary statistics of datasets exhibiting statistical significance when comparing the proposed **ensLoss** against all other fixed loss methods in **45 CIFAR2** binary classification datasets are presented.
116: 
117: | **Models**       | **EnsLoss** | **(vs BCE)**                  | **(vs Exp)**                  | **(vs Hinge)**                |
118: |------------------|-------------|-------------------------------|-------------------------------|-------------------------------|
119: | **ResNet34**     |             | (41 better, 4 no diff, 0 worse) | (45 better, 0 no diff, 0 worse) | (36 better, 9 no diff, 0 worse) |
120: | **ResNet50**     |             | (42 better, 3 no diff, 0 worse) | (45 better, 0 no diff, 0 worse) | (43 better, 2 no diff, 0 worse) |
121: | **ResNet101**    |             | (39 better, 6 no diff, 0 worse) | (45 better, 0 no diff, 0 worse) | (40 better, 5 no diff, 0 worse) |
122: | **VGG16**        |             | (36 better, 9 no diff, 0 worse) | (45 better, 0 no diff, 0 worse) | (29 better, 16 no diff, 0 worse) |
123: | **VGG19**        |             | (36 better, 9 no diff, 0 worse) | (45 better, 0 no diff, 0 worse) | (27 better, 18 no diff, 0 worse) |
124: | **MobileNet**    |             | (45 better, 0 no diff, 0 worse) | (45 better, 0 no diff, 0 worse) | (44 better, 1 no diff, 0 worse) |
125: | **MobileNetV2**  |             | (45 better, 0 no diff, 0 worse) | (45 better, 0 no diff, 0 worse) | (45 better, 0 no diff, 0 worse) |
126: 
127: <!-- ![img_benchmark](./fig/img_benchmark.png) -->
128: 
129: To replicate the benchmark results presented in our paper, please use the following command:
130: ```bash
131: bash ./sh_files/runs_cifar_mobilenet.sh
132: bash ./sh_files/runs_cifar_resnet.sh
133: bash ./sh_files/runs_cifar_vgg.sh
134: bash ./sh_files/runs_pcam.sh
135: ```
136: Our runing results are publicly avaliable in our W\&B project [ensLoss-img](https://wandb.ai/bdai/ensLoss-img?nw=nwuserbdai) and the markdown report [out_cifar](./out/out_cifar.md) and [out_pcam](./out/out_pcam.md).
137: 
138: ### Customize the Run
139: To execute the methods on a dataset, use the following command:
140: ```bash
141: ## run for CIFAR
142: python main_image.py -F="CIFAR35"
143: ## run for PCam
144: python main_image.py -F="PCam"
145: ```
146: > Note that `CIFAR{u}{v}` represents the pairwise CIFAR dataset containing labels {u} and {v}.
147: 
148: The runing configuration is included in `main_img.py`, with the default settings as follows:
149: ```python
150: config = {
151:         'loss_list': ['ensLoss', 'Focal', 'BCE', 'Hinge', 'EXP'],
152:         'dataset' : 'CIFAR',
153:         'model': {'net': 'ResNet50'},
154:         'save_model': False,
155:         'batch_size': 128,
156:         'ensLoss_per_epochs': -1,
157:         'trainer': {'epochs': 200, 'val_per_epochs': 5},
158:         'optimizer': {'lr': 1e-3, 'type': 'SGD', 'weight_decay': 5e-4, 'lr_scheduler': 'CosineAnnealingLR', 'args': {'T_max': 200}},
159:         'device': torch.device("cuda:0" if torch.cuda.is_available() else "cpu")}
160: ```
161: To customize your experiment, please adjust the parameters in `argument` and `config`.
162: 
163: > Note that the results regarding the compatibility of existing overfitting prevention methods in our paper can also be replicated with customized runs, see [main_reg.py](./main_reg.py).
164: 
165: 
166: ## Benchmarks for Tabular Data
167: 
168: This benchmark contain 14 tabular datasets in [openml](https://www.openml.org/). These datasets were selected based on the following filtering criteria: `verified`, `>1000 instances`, `>1000 features`, `binary class`, `dense`, and with at least one official run. The resulting datasets can be found [here](https://www.openml.org/search?type=data&sort=runs&status=active&qualities.NumberOfInstances=between_1000_10000&qualities.NumberOfFeatures=between_1000_10000&qualities.NumberOfClasses=%3D_2&format=ARFF):
169: 
170: | **Dataset**       | **Data ID** | **(n,d) (× 10³)** |
171: |-------------------|-------------|-------------------|
172: | Bioresponse       | 4134        | (3.75, 1.78)      |
173: | guillermo         | 41159       | (20.0, 4.30)      |
174: | riccardo          | 41161       | (20.0, 4.30)      |
175: | hiva-agnostic     | 1039        | (4.23, 1.62)      |
176: | christine         | 41142       | (5.42, 1.64)      |
177: | OVA-Breast        | 1128        | (1.54, 10.9)      |
178: | OVA-Uterus        | 1138        | (1.54, 10.9)      |
179: | OVA-Ovary         | 1166        | (1.54, 10.9)      |
180: | OVA-Kidney        | 1134        | (1.54, 10.9)      |
181: | OVA-Lung          | 1130        | (1.54, 10.9)      |
182: | OVA-Omentum       | 1139        | (1.54, 10.9)      |
183: | OVA-Colon         | 1161        | (1.54, 10.9)      |
184: | OVA-Endometrium   | 1142        | (1.54, 10.9)      |
185: | OVA-Prostate      | 1146        | (1.54, 10.9)      |
186: 
187: ### Replicating Benchmark
188: The summary statistics of datasets exhibiting statistical significance when comparing the proposed **ensLoss** against all other fixed loss methods in **14 OpenML** binary classification datasets are presented.
189: 
190: | **Models** | **EnsLoss** | **(vs BCE)**         | **(vs Exp)**         | **(vs Hinge)**       |
191: |------------|-------------|----------------------|----------------------|----------------------|
192: | **MLP(1)** |             | (9 better, 4 no diff, 1 worse) | (7 better, 5 no diff, 2 worse) | (5 better, 4 no diff, 5 worse) |
193: | **MLP(3)** |             | (7 better, 7 no diff, 0 worse) | (8 better, 5 no diff, 1 worse) | (9 better, 3 no diff, 2 worse) |
194: | **MLP(5)** |             | (11 better, 3 no diff, 0 worse) | (11 better, 2 no diff, 1 worse) | (13 better, 0 no diff, 1 worse) |
195: 
196: <!-- ![tab_benchmark](./fig/tab_benchmark.png) -->
197: 
198: To replicate the benchmark results presented in our paper, please use the following command:
199: ```bash
200: bash ./sh_files/runs_tab.sh
201: ```
202: Our runing results are publicly avaliable in our W\&B project [ensLoss-tab](https://wandb.ai/bdai/ensLoss-tab?nw=nwuserbdai) and the markdown report [out_tab](./out/out_tab.md).
203: 
204: ### Customize the Run
205: To execute the methods on a dataset, use the following command:
206: ```bash
207: python main_tab.py -ID=4134
208: ```
209: Note that the `ID` refers to the dataset ID in OpenML. The runing configuration is included in `main_tab.py`, with the default settings as follows:
210: 
211: ```python
212: config = {
213:         'dataset' : 4134,
214:         'model': {'net': 'TabMLP3', 'args': {}},
215:         'batch_size': 128,
216:         'save_model': False,
217:         'ensLoss_per_epochs': -1,
218:         'trainer': {'epochs': 300, 'val_per_epochs': 10},
219:         'optimizer': {'lr': 1e-4, 'type': 'SGD', 'weight_decay': 5e-6,
220:                         'lr_scheduler': 'CosineAnnealingLR', 'args': {'T_max': 300}},
221:         'device': torch.device("cuda:0" if torch.cuda.is_available() else "cpu")}
222: ```
223: To customize your experiment, please adjust the parameters in `argument` and `config`.
224: 
225: 
226: ## Benchmarks for Text Data
227: This benchmark contains one text datasets: [GLUE-SST2](https://huggingface.co/datasets/nyu-mll/glue).
228: 
229: > Currently, the majority of NLP learning employs fine-tuning (often just a few epochs) from large pretrained models. Consequently, `ensLoss` that require extensive epoch training, are not particularly suitable. Therefore, we did not focus on NLP results in this paper; however, we conducted some preliminary experiments.
230: 
231: To execute the methods on a dataset, use the following command:
232: ```bash
233: python main_text.py -F="SST2"
234: ```
235: 
236: The runing configuration is included in `main_text.py`, with the default settings as follows:
237: ```python
238: config = {
239:         'dataset' : args.filename,
240:         'model': {'net': 'BiLSTM'},
241:         'save_model': False,
242:         'batch_size': 32,
243:         'ensLoss_per_epochs': -1,
244:         'trainer': {'epochs': 50, 'val_per_epochs': 5},
245:         'optimizer': {'lr': 2e-5, 'type': 'AdamW', 'weight_decay': 1e-5,
246:                         'lr_scheduler': 'CosineAnnealingLR', 'args': {'T_max': args.epoch}},
247:         'device': torch.device("cuda:0" if torch.cuda.is_available() else "cpu")}
248: ```
249: To customize your experiment, please adjust the parameters in `argument` and `config`.
250: 
251: ## References
252: - [OpenML](https://www.openml.org/)
253: - [Pytorch.data](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html)
254: - [Train CIFAR10 with PyTorch](https://github.com/kuangliu/pytorch-cifar)
255: - [huggingface.transformers](https://huggingface.co/transformers/v3.3.1/index.html)
256: - [GLUE benchmark](https://gluebenchmark.com/leaderboard)
257: - [PS3E24: PyTorch Tabular Resnet](https://www.kaggle.com/code/syerramilli/ps3e24-pytorch-tabular-resnet)
258: 
259: ## Thank you
260: 
261: If you find this repository helpful, please star our repo 🌟.
262: 
263: Thank you so much for the support from our stargazers.
264: 
265: [![Stargazers repo roster for @statmlben/ensLoss](https://reporoster.com/stars/statmlben/ensLoss)](https://github.com/statmlben/ensLoss/stargazers)
MEMBER losses.py SHA256 c3644b47f36083af61c77b1219408aea33ce0d5a0d787747e86a38e3071fb637
1: """ Loss functions for Binary Classification"""
2: 
3: # Authors: Ben Dai
4: # License: MIT License
5: 
6: import numpy as np
7: import pandas as pd
8: 
9: import torch
10: import torch.nn as nn
11: import torch.optim as optim
12: import torch.nn.functional as F
13: 
14: class ensLoss(nn.Module):
15:     def __init__(self, dist=torch.distributions.exponential.Exponential(1 / 1.)):
16:         super(ensLoss, self).__init__()
17:         self.dist = dist
18:         self.lam = 0.0
19:         ## How often should the loss function be updated in SGD, based on `self.period` the number of steps?
20:         self.period = 10
21: 
22:     def BC_inv(self, z):
23:         if self.lam == 0.:
24:             return torch.exp(z)
25:         else:
26:             diff = 1. + self.lam*z
27:             return (torch.where(diff > 0.0, diff, 0.0))**(1.0/self.lam)
28: 
29:     def forward(self, output, target):
30:         target = 2.*target - 1.
31:         batch_size_tmp = len(target)
32:         s_batch = torch.zeros(batch_size_tmp)
33:         s_batch = output.flatten()*target.flatten()
34: 
35:         ## generate random gradient
36:         g_num = batch_size_tmp
37:         g_batch = torch.zeros(g_num)
38:         
39:         # sample from dist
40:         # rd_grad = - self.dist.sample((g_num,)).flatten()
41:         
42:         # generate random loss from the inverse Box-Cox transformation
43:         rd_grad = torch.randn((g_num,))
44:         rd_grad = - self.BC_inv(rd_grad)
45:         rd_grad, _ = torch.sort(rd_grad)
46:         rd_grad = np.maximum(rd_grad, -1.0)
47:         _, ind_tmp = torch.sort(s_batch)
48:         g_batch[ind_tmp] = rd_grad
49:         g_batch = g_batch.to("cuda")
50: 
51:         ## superlinear tail of the loss-derivatives
52:         s_batch_no_grad = s_batch.detach()
53:         pos_ind = (s_batch_no_grad > 1.0)
54:         if len(s_batch_no_grad[pos_ind]) > 0:
55:             g_batch[pos_ind] *= (1 / s_batch_no_grad[pos_ind] )
56:         
57:         g_batch = g_batch.detach() - 1e-6
58: 
59:         ## final gradient
60:         loss = g_batch * s_batch
61:         loss = loss.mean()
62:         return loss
63: 
64: class BCELoss(nn.Module):
65:     def __init__(self, weight=None, reduction='mean'):
66:         super(BCELoss, self).__init__()
67:         self.BCE = nn.BCEWithLogitsLoss(weight=weight, reduction=reduction)
68: 
69:     def forward(self, output, target):
70:         loss = self.BCE(output, target)
71:         return loss
72: 
73: class BinFocal(nn.Module):
74:     def __init__(self, gamma=2.0, weight=None, reduction='mean'):
75:         super(BinFocal, self).__init__()
76:         self.gamma = gamma
77:         self.reduction = reduction
78: 
79:     def forward(self, output, target):
80:         loss = sigmoid_focal_loss(inputs=output, 
81:                                   targets=target, 
82:                                   gamma=self.gamma, 
83:                                   reduction=self.reduction)
84:         return loss    
85: 
86: def sigmoid_focal_loss(
87:     inputs: torch.Tensor,
88:     targets: torch.Tensor,
89:     alpha: float = -1,
90:     gamma: float = 2,
91:     reduction: str = "none",
92: ) -> torch.Tensor:
93:     """
94:     Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
95: 
96:     Args:
97:         inputs (Tensor): A float tensor of arbitrary shape.
98:                 The predictions for each example.
99:         targets (Tensor): A float tensor with the same shape as inputs. Stores the binary
100:                 classification label for each element in inputs
101:                 (0 for the negative class and 1 for the positive class).
102:         alpha (float): Weighting factor in range (0,1) to balance
103:                 positive vs negative examples or -1 for ignore. Default: ``0.25``.
104:         gamma (float): Exponent of the modulating factor (1 - p_t) to
105:                 balance easy vs hard examples. Default: ``2``.
106:         reduction (string): ``'none'`` | ``'mean'`` | ``'sum'``
107:                 ``'none'``: No reduction will be applied to the output.
108:                 ``'mean'``: The output will be averaged.
109:                 ``'sum'``: The output will be summed. Default: ``'none'``.
110:     Returns:
111:         Loss tensor with the reduction option applied.
112:     """
113:     # Original implementation from https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/focal_loss.py
114: 
115:     p = torch.sigmoid(inputs)
116:     ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
117:     p_t = p * targets + (1 - p) * (1 - targets)
118:     loss = ce_loss * ((1 - p_t) ** gamma)
119: 
120:     if alpha >= 0:
121:         alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
122:         loss = alpha_t * loss
123: 
124:     # Check reduction option and return loss accordingly
125:     if reduction == "none":
126:         pass
127:     elif reduction == "mean":
128:         loss = loss.mean()
129:     elif reduction == "sum":
130:         loss = loss.sum()
131:     else:
132:         raise ValueError(
133:             f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'"
134:         )
135:     return loss
136: 
137: class Hinge(nn.Module):
138:     def __init__(self, reduction='mean'):
139:         super(Hinge, self).__init__()
140:         self.reduction = reduction
141: 
142:     def forward(self, output, target):
143:         target = 2.*target - 1.
144:         score = output * target
145:         loss = torch.maximum(1. - score, torch.zeros_like(score))
146:         if self.reduction == 'mean':
147:             loss_out = loss.mean()
148:         elif self.reduction == 'sum':
149:             loss_out = loss.sum()
150:         else: 
151:             raise Exception("Sorry, reduction of loss must be mean or sum") 
152:         return loss_out
153: 
154: class EXP(nn.Module):
155:     def __init__(self, reduction='mean'):
156:         super(EXP, self).__init__()
157:         self.reduction = reduction
158: 
159:     def forward(self, output, target):
160:         target = 2.*target - 1.
161:         score = output * target
162:         loss = torch.exp(-score)
163:         if self.reduction == 'mean':
164:             loss_out = loss.mean()
165:         elif self.reduction == 'sum':
166:             loss_out = loss.sum()
167:         else: 
168:             raise Exception("Sorry, reduction of loss must be mean or sum") 
169:         return loss_out
170: 
171: class sqrt_Hinge(nn.Module):
172:     def __init__(self, reduction='mean'):
173:         super(sqrt_Hinge, self).__init__()
174:         self.reduction = reduction
175: 
176:     def forward(self, output, target):
177:         target = 2.*target - 1.
178:         score = output * target
179:         loss = (score <= 1.0) * (1.0 - score) - 2 * (score > 1.0) * (torch.sqrt(abs(score) - 1))
180:         # loss = (score <= 1.0) * (1.0 - score) - 0 * (score > 1.0)
181:         if self.reduction == 'mean':
182:             loss_out = loss.mean()
183:         elif self.reduction == 'sum':
184:             loss_out = loss.sum()
185:         else:
186:             raise Exception("Sorry, reduction of loss must be mean or sum") 
187:         return loss_out
188: 
189: class Inv_Log_Hinge(nn.Module):
190:     def __init__(self, reduction='mean'):
191:         super(Inv_Log_Hinge, self).__init__()
192:         self.reduction = reduction
193: 
194:     def forward(self, output, target):
195:         target = 2.*target - 1.
196:         score = output * target
197:         loss = (score <= 1.0) * (1.0 - score) + (score > 1.0) * (torch.e / torch.log(abs(score) + torch.e - 1) - torch.e)
198:         if self.reduction == 'mean':
199:             loss_out = loss.mean()
200:         elif self.reduction == 'sum':
201:             loss_out = loss.sum()
202:         else:
203:             raise Exception("Sorry, reduction of loss must be mean or sum") 
204:         return loss_out
205: 
206: class Log_Hinge(nn.Module):
207:     def __init__(self, reduction='mean'):
208:         super(Log_Hinge, self).__init__()
209:         self.reduction = reduction
210: 
211:     def forward(self, output, target):
212:         target = 2.*target - 1.
213:         score = output * target
214:         loss = (score <= 1.0) * (1.0 - score) - (score > 1.0) * torch.log(abs(score))
215:         if self.reduction == 'mean':
216:             loss_out = loss.mean()
217:         elif self.reduction == 'sum':
218:             loss_out = loss.sum()
219:         else:
220:             raise Exception("Sorry, reduction of loss must be mean or sum") 
221:         return loss_out
222: 
223: class Exp_Hinge(nn.Module):
224:     def __init__(self, reduction='mean'):
225:         super(Exp_Hinge, self).__init__()
226:         self.reduction = reduction
227: 
228:     def forward(self, output, target):
229:         target = 2.*target - 1.
230:         score = output * target
231:         loss = (score <= 1.0) * (1.0 - score) - (score > 1.0) * torch.exp(- (score - 1))
232:         if self.reduction == 'mean':
233:             loss_out = loss.mean()
234:         elif self.reduction == 'sum':
235:             loss_out = loss.sum()
236:         else:
237:             raise Exception("Sorry, reduction of loss must be mean or sum") 
238:         return loss_out
239: 
240: 
241: class Inv_Hinge(nn.Module):
242:     def __init__(self, reduction='mean'):
243:         super(Inv_Hinge, self).__init__()
244:         self.reduction = reduction
245: 
246:     def forward(self, output, target):
247:         target = 2.*target - 1.
248:         score = output * target
249:         loss = (score <= 1.0) * (1.0 - score) + (score > 1.0) * (1 / score - 1)
250:         if self.reduction == 'mean':
251:             loss_out = loss.mean()
252:         elif self.reduction == 'sum':
253:             loss_out = loss.sum()
254:         else:
255:             raise Exception("Sorry, reduction of loss must be mean or sum") 
256:         return loss_out
