trainer.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # Improve performance of neural network
  2. import numpy as np
  3. from lab import neural, io_mnist
  4. from copy import copy
  5. def train(inputNetwork, learnRate, epochs, batchSize = 10):
  6. """
  7. Create an improved network
  8. inputNetwork : the network to be trained
  9. epochs : the number of iterations
  10. return : a trained copy with improved performance
  11. """
  12. net = copy(inputNetwork)
  13. np_images, np_expected = io_mnist.load_training_samples()
  14. nbSamples = np_images.shape[1]
  15. # Prepare variables
  16. a0 = np.empty((net.inputLength, batchSize))
  17. w1 = net.layer1 # reference
  18. b1 = np.stack([net.bias1] * batchSize).transpose() # stack
  19. z1 = np.empty((net.hiddenLength, batchSize))
  20. a1 = np.empty((net.hiddenLength, batchSize))
  21. w2 = net.layer2 # reference
  22. b2 = np.stack([net.bias2] * batchSize).transpose() # stack
  23. z2 = np.empty((net.outputLength, batchSize))
  24. a2 = np.empty((net.outputLength, batchSize))
  25. y = np.empty((net.outputLength, batchSize))
  26. g = net.activationFunction
  27. g_ = net.activationDerivative
  28. d2 = np.empty(a2.shape)
  29. d1 = np.empty(a1.shape)
  30. permut = np.arange(nbSamples)
  31. for epoch in range(epochs):
  32. # Create mini batches
  33. np.random.shuffle(permut)
  34. # Iterate over batches
  35. for batchIndex in range(0, nbSamples, batchSize):
  36. # Capture batch
  37. batchEndIndex = batchIndex + batchSize
  38. batchSelection = permut[batchIndex : batchEndIndex]
  39. a0 = np_images[:, batchSelection]
  40. y = np_expected[:, batchSelection]
  41. # Forward computation
  42. z1 = w1 @ a0 + b1
  43. a1 = g(z1)
  44. z2 = w2 @ a1 + b2
  45. a2 = g(z2)
  46. # Backward propagation
  47. d2 = a2 - y
  48. d1 = w2.transpose() @ d2 * g_(z1)
  49. # Weight correction
  50. net.layer2 -= learnRate * d2 @ a1.transpose() / batchSize
  51. net.layer1 -= learnRate * d1 @ a0.transpose() / batchSize
  52. net.bias2 -= learnRate * d2 @ np.ones(batchSize) / batchSize
  53. net.bias1 -= learnRate * d1 @ np.ones(batchSize) / batchSize
  54. return net