Guest User

Untitled

a guest
Jan 17th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. import numpy as np
  2.  
  3. def pattern_associator_delta(inputs, targets, weights=None, rate=0.25, max_steps=100):
  4. step = 0
  5. if weights is None:
  6. weights = [0] * len(inputs[0])
  7. weights = np.array(weights, dtype='float64', ndmin=2)
  8. inputs = [np.array(i, ndmin=2) for i in inputs]
  9. targets = [np.array(i, ndmin=2) for i in targets]
  10. while step < max_steps:
  11. errors = np.zeros(len(inputs), dtype='float64')
  12. # Train over all patterns
  13. for input_pattern, target_pattern in zip(inputs, targets):
  14. output_pattern = np.dot(input_pattern, weights.T)
  15. error = target_pattern - output_pattern
  16. delta = np.dot(error.T, input_pattern) * rate
  17. weights = weights + delta
  18. # Compute errors at current state
  19. for i, io in enumerate(zip(inputs, targets)):
  20. output_pattern = np.dot(io[0], weights.T)
  21. error = io[1] - output_pattern
  22. errors[i] = np.sqrt(np.mean(error**2))
  23. tss = sum(errors**2)
  24. print('tss: {}'.format(tss))
  25. if np.isclose(tss, 0):
  26. break
  27. step += 1
  28.  
  29. # Validate
  30. for input_pattern, target_pattern in zip(inputs, targets):
  31. assert np.allclose(np.dot(input_pattern, weights.T), target_pattern, atol=1e-3)
  32.  
  33. return weights
  34.  
  35.  
  36. pattern_associator_delta(inputs=[[1, 1, 1, 1], [1, 1, -1, -1]],
  37. targets=[[1], [1]])
  38.  
  39. pattern_associator_delta(inputs=[[1, -1, 1, -1],
  40. [1, 1, 1, 1],
  41. [1, 1, 1, -1],
  42. [1, -1, -1, 1]],
  43. targets =[[1], [1], [-1], [-1]])
Add Comment
Please, Sign In to add comment