FedNets.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Python version: 3.6
  4. from torch import nn
  5. import torch.nn.functional as F
  6. class MLP(nn.Module):
  7. def __init__(self, dim_in, dim_hidden, dim_out):
  8. super(MLP, self).__init__()
  9. self.layer_input = nn.Linear(dim_in, dim_hidden)
  10. self.relu = nn.ReLU()
  11. self.dropout = nn.Dropout()
  12. self.layer_hidden = nn.Linear(dim_hidden, dim_out)
  13. self.softmax = nn.Softmax(dim=1)
  14. def forward(self, x):
  15. x = x.view(-1, x.shape[1]*x.shape[-2]*x.shape[-1])
  16. x = self.layer_input(x)
  17. x = self.dropout(x)
  18. x = self.relu(x)
  19. x = self.layer_hidden(x)
  20. return self.softmax(x)
  21. class CNNMnist(nn.Module):
  22. def __init__(self, args):
  23. super(CNNMnist, self).__init__()
  24. self.conv1 = nn.Conv2d(args.num_channels, 10, kernel_size=5)
  25. self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
  26. self.conv2_drop = nn.Dropout2d()
  27. self.fc1 = nn.Linear(320, 50)
  28. self.fc2 = nn.Linear(50, args.num_classes)
  29. def forward(self, x):
  30. x = F.relu(F.max_pool2d(self.conv1(x), 2))
  31. x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
  32. x = x.view(-1, x.shape[1]*x.shape[2]*x.shape[3])
  33. x = F.relu(self.fc1(x))
  34. x = F.dropout(x, training=self.training)
  35. x = self.fc2(x)
  36. return F.log_softmax(x, dim=1)
  37. class CNNFashion_Mnist(nn.Module):
  38. def __init__(self, args):
  39. super(CNNFashion_Mnist, self).__init__()
  40. self.layer1 = nn.Sequential(
  41. nn.Conv2d(1, 16, kernel_size=5, padding=2),
  42. nn.BatchNorm2d(16),
  43. nn.ReLU(),
  44. nn.MaxPool2d(2))
  45. self.layer2 = nn.Sequential(
  46. nn.Conv2d(16, 32, kernel_size=5, padding=2),
  47. nn.BatchNorm2d(32),
  48. nn.ReLU(),
  49. nn.MaxPool2d(2))
  50. self.fc = nn.Linear(7*7*32, 10)
  51. def forward(self, x):
  52. out = self.layer1(x)
  53. out = self.layer2(out)
  54. out = out.view(out.size(0), -1)
  55. out = self.fc(out)
  56. return out
  57. class CNNCifar(nn.Module):
  58. def __init__(self, args):
  59. super(CNNCifar, self).__init__()
  60. self.conv1 = nn.Conv2d(3, 6, 5)
  61. self.pool = nn.MaxPool2d(2, 2)
  62. self.conv2 = nn.Conv2d(6, 16, 5)
  63. self.fc1 = nn.Linear(16 * 5 * 5, 120)
  64. self.fc2 = nn.Linear(120, 84)
  65. self.fc3 = nn.Linear(84, args.num_classes)
  66. def forward(self, x):
  67. x = self.pool(F.relu(self.conv1(x)))
  68. x = self.pool(F.relu(self.conv2(x)))
  69. x = x.view(-1, 16 * 5 * 5)
  70. x = F.relu(self.fc1(x))
  71. x = F.relu(self.fc2(x))
  72. x = self.fc3(x)
  73. return F.log_softmax(x, dim=1)