FedNets.py 2.0 KB

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