Alexnet.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import torch
  2. import torch.nn as nn
  3. class Alexnet(nn.Module):
  4. def __init__(self, input_channels, output_num, input_size):
  5. super().__init__()
  6. self.features = nn.Sequential(
  7. nn.Conv2d(in_channels=input_channels, out_channels=64, kernel_size=3, stride=2, padding=1),
  8. nn.BatchNorm2d(64), # 批量归一化层
  9. nn.MaxPool2d(kernel_size=2),
  10. nn.ReLU(inplace=True),
  11. nn.Conv2d(in_channels=64, out_channels=192, kernel_size=3, padding=1),
  12. nn.BatchNorm2d(192), # 批量归一化层
  13. nn.MaxPool2d(kernel_size=2),
  14. nn.ReLU(inplace=True),
  15. nn.Conv2d(in_channels=192, out_channels=384, kernel_size=3, padding=1),
  16. nn.BatchNorm2d(384), # 批量归一化层
  17. nn.ReLU(inplace=True),
  18. nn.Conv2d(in_channels=384, out_channels=256, kernel_size=3, padding=1),
  19. nn.BatchNorm2d(256), # 批量归一化层
  20. nn.ReLU(inplace=True),
  21. nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, padding=1),
  22. nn.BatchNorm2d(256), # 批量归一化层
  23. nn.MaxPool2d(kernel_size=2),
  24. nn.ReLU(inplace=True),
  25. )
  26. self.input_size = input_size
  27. self._init_classifier(output_num)
  28. def _init_classifier(self, output_num):
  29. with torch.no_grad():
  30. # Forward a dummy input through the feature extractor part of the network
  31. dummy_input = torch.zeros(1, 3, self.input_size, self.input_size)
  32. features_size = self.features(dummy_input).numel()
  33. self.classifier = nn.Sequential(
  34. nn.Dropout(0.5),
  35. nn.Linear(features_size, 1000),
  36. nn.ReLU(inplace=True),
  37. nn.Dropout(0.5),
  38. nn.Linear(1000, 256),
  39. nn.ReLU(inplace=True),
  40. nn.Linear(256, output_num)
  41. )
  42. def forward(self, x):
  43. x = self.features(x)
  44. x = x.reshape(x.size(0), -1)
  45. x = self.classifier(x)
  46. return x
  47. if __name__ == '__main__':
  48. import argparse
  49. parser = argparse.ArgumentParser(description='AlexNet Implementation')
  50. parser.add_argument('--input_channels', default=3, type=int)
  51. parser.add_argument('--output_num', default=10, type=int)
  52. parser.add_argument('--input_size', default=32, type=int)
  53. args = parser.parse_args()
  54. model = Alexnet(args.input_channels, args.output_num, args.input_size)
  55. tensor = torch.rand(1, args.input_channels, args.input_size, args.input_size)
  56. pred = model(tensor)
  57. print(model)
  58. print("Predictions shape:", pred.shape)