clientavg.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import torch
  2. import torch.nn as nn
  3. import numpy as np
  4. import copy
  5. import sys
  6. from flcore.clients.clientbase import Client
  7. class clientAVG(Client):
  8. def __init__(self, args, id, train_samples, test_samples, **kwargs):
  9. super().__init__(args, id, train_samples, test_samples, **kwargs)
  10. self.criterion = nn.CrossEntropyLoss()
  11. self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.learning_rate, momentum=0.9)
  12. def train(self):
  13. trainloader = self.load_train_data()
  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()