16def tcc(y: torch.tensor, y_true: torch.LongTensor, n: int) -> torch.tensor:
18 Calculates loss using the required number of Taylor terms of cross entropy loss.
21 y(torch.tensor): The probabilities predicted by ML model.
22 y_true(torch.LongTensor): The truth values provided for training purposes (1D tensor).
23 n(int): Number of terms to to be taken
for the Taylor Series.
26 A torch tesor
with the value of the calculated Taylor cross entropy loss.
29 With n = 0, this returns the regular cross entropy loss.
32 loss = torch.zeros(len(y_true))
33 if torch.cuda.is_available():
34 loss = loss.to(
"cuda")
35 ProbTrue = y[np.arange(len(y_true)), y_true]
37 for i
in range(1, n + 1):
38 loss += torch.pow(1 - ProbTrue, i) / i
40 loss = -1 * torch.log(ProbTrue)
41 loss = torch.sum(loss)
47 Class for calculation of Taylor cross entropy loss.
50 n (int): Number of Taylor series terms to be used
for loss calculation.
56 Initialize the loss class.
59 n (int)(optional): Number of Taylor series terms to be used
for loss calculation.
66 def forward(self, y: torch.tensor, y_true: torch.LongTensor) -> torch.tensor:
68 Calculates the Taylor categorical cross entropy loss.
71 y(torch.tensor): Tensor containing the output of the model.
72 y_true(torch.tensor): 1D tensor containing the truth value for a given set of features.
75 The calculated loss
as a torch tensor.
77 return tcc(y, y_true, self.
n)
def __init__(self, int n=0)
torch.tensor forward(self, torch.tensor y, torch.LongTensor y_true)