simple_cnn.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. ################################################################################
  2. # Copyright (c) 2021 ContinualAI. #
  3. # Copyrights licensed under the MIT License. #
  4. # See the accompanying LICENSE file for terms. #
  5. # #
  6. # Date: 1-05-2020 #
  7. # Author(s): Vincenzo Lomonaco, Antonio Carta #
  8. # E-mail: contact@continualai.org #
  9. # Website: avalanche.continualai.org #
  10. ################################################################################
  11. import torch.nn as nn
  12. from avalanche.models.dynamic_modules import MultiTaskModule, \
  13. MultiHeadClassifier
  14. class SimpleCNN(nn.Module):
  15. def __init__(self, num_classes=10):
  16. super(SimpleCNN, self).__init__()
  17. self.features = nn.Sequential(
  18. nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1),
  19. nn.ReLU(inplace=True),
  20. nn.Conv2d(32, 32, kernel_size=3, padding=0),
  21. nn.ReLU(inplace=True),
  22. nn.MaxPool2d(kernel_size=2, stride=2),
  23. nn.Dropout(p=0.25),
  24. nn.Conv2d(32, 64, kernel_size=3, padding=1),
  25. nn.ReLU(inplace=True),
  26. nn.Conv2d(64, 64, kernel_size=3, padding=0),
  27. nn.ReLU(inplace=True),
  28. nn.MaxPool2d(kernel_size=2, stride=2),
  29. nn.Dropout(p=0.25),
  30. nn.Conv2d(64, 64, kernel_size=1, padding=0),
  31. nn.ReLU(inplace=True),
  32. nn.AdaptiveMaxPool2d(1),
  33. nn.Dropout(p=0.25)
  34. )
  35. self.classifier = nn.Sequential(
  36. nn.Linear(64, num_classes)
  37. )
  38. def forward(self, x):
  39. x = self.features(x)
  40. x = x.view(x.size(0), -1)
  41. x = self.classifier(x)
  42. return x
  43. class MTSimpleCNN(SimpleCNN, MultiTaskModule):
  44. def __init__(self):
  45. """
  46. Multi-task CNN with multi-head classifier.
  47. """
  48. super().__init__()
  49. self.classifier = MultiHeadClassifier(64)
  50. def forward(self, x, task_labels):
  51. x = self.features(x)
  52. x = x.squeeze()
  53. x = self.classifier(x, task_labels)
  54. return x
  55. __all__ = [
  56. 'SimpleCNN',
  57. 'MTSimpleCNN'
  58. ]