clientper.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import copy
  2. import torch
  3. import torch.nn as nn
  4. import numpy as np
  5. from flcore.clients.clientbase import Client
  6. class clientPer(Client):
  7. def __init__(self, args, id, train_samples, test_samples, **kwargs):
  8. super().__init__(args, id, train_samples, test_samples, **kwargs)
  9. self.criterion = nn.CrossEntropyLoss()
  10. self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.learning_rate, momentum=0.9)
  11. def train(self):
  12. trainloader = self.load_train_data()
  13. # self.model.to(self.device)
  14. self.model.train()
  15. max_local_steps = self.local_steps
  16. for step in range(max_local_steps):
  17. for i, (x, y) in enumerate(trainloader):
  18. if type(x) == type([]):
  19. x[0] = x[0].to(self.device)
  20. else:
  21. x = x.to(self.device)
  22. y = y.to(self.device)
  23. self.optimizer.zero_grad()
  24. output = self.model(x)
  25. loss = self.criterion(output, y)
  26. loss.backward()
  27. self.optimizer.step()
  28. # self.model.cpu()
  29. def set_parameters(self, model):
  30. for new_param, old_param in zip(model.parameters(), self.model.base.parameters()):
  31. old_param.data = new_param.data.clone()