LeNet.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import torch
  2. import torch.nn as nn
  3. class LeNet(nn.Module):
  4. def __init__(self, input_channels, output_num, input_size):
  5. super(LeNet, self).__init__()
  6. self.features = nn.Sequential(
  7. nn.Conv2d(input_channels, 16, 5),
  8. nn.MaxPool2d(2, 2),
  9. nn.Conv2d(16, 32, 5),
  10. nn.MaxPool2d(2, 2)
  11. )
  12. self.input_size = input_size
  13. self.input_channels = input_channels
  14. self._init_classifier(output_num)
  15. def _init_classifier(self, output_num):
  16. with torch.no_grad():
  17. # Forward a dummy input through the feature extractor part of the network
  18. dummy_input = torch.zeros(1, self.input_channels, self.input_size, self.input_size)
  19. features_size = self.features(dummy_input).numel()
  20. self.classifier = nn.Sequential(
  21. nn.Linear(features_size, 120),
  22. nn.Linear(120, 84),
  23. nn.Linear(84, output_num)
  24. )
  25. def forward(self, x):
  26. x = self.features(x)
  27. x = x.reshape(x.size(0), -1)
  28. x = self.classifier(x)
  29. return x
  30. if __name__ == '__main__':
  31. import argparse
  32. parser = argparse.ArgumentParser(description='LeNet Implementation')
  33. parser.add_argument('--input_channels', default=3, type=int)
  34. parser.add_argument('--output_num', default=10, type=int)
  35. parser.add_argument('--input_size', default=32, type=int)
  36. args = parser.parse_args()
  37. model = LeNet(args.input_channels, args.output_num, args.input_size)
  38. tensor = torch.rand(1, args.input_channels, args.input_size, args.input_size)
  39. pred = model(tensor)
  40. print(model)
  41. print("Predictions shape:", pred.shape)