googlenetloss.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. import paddle
  13. import paddle.nn as nn
  14. import paddle.nn.functional as F
  15. class GoogLeNetLoss(nn.Layer):
  16. """
  17. Cross entropy loss used after googlenet
  18. """
  19. def __init__(self, epsilon=None):
  20. super().__init__()
  21. assert (epsilon is None or epsilon <= 0 or
  22. epsilon >= 1), "googlenet is not support label_smooth"
  23. def forward(self, inputs, label):
  24. input0, input1, input2 = inputs
  25. if isinstance(input0, dict):
  26. input0 = input0["logits"]
  27. if isinstance(input1, dict):
  28. input1 = input1["logits"]
  29. if isinstance(input2, dict):
  30. input2 = input2["logits"]
  31. loss0 = F.cross_entropy(input0, label=label, soft_label=False)
  32. loss1 = F.cross_entropy(input1, label=label, soft_label=False)
  33. loss2 = F.cross_entropy(input2, label=label, soft_label=False)
  34. loss = loss0 + 0.3 * loss1 + 0.3 * loss2
  35. loss = loss.mean()
  36. return {"GooleNetLoss": loss}