fork download
  1. import numpy as np
  2.  
  3. # Parameters
  4. learning_rate = 0.1
  5. max_iterations = 1000
  6.  
  7. # Activation function with dynamic thresholding
  8. def activation_function(weighted_sum, threshold=0.5):
  9. return 1 if weighted_sum > threshold else 0
  10.  
  11. # Inputs for XOR truth table
  12. inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
  13. targets = [0, 1, 1, 0] # XOR Truth Table
  14.  
  15. # Initialize weights (hidden and output layers)
  16. weights_input_to_hidden = np.random.rand(3) # Weights for N1, N2, bias → N3
  17. weights_hidden_to_output = np.random.rand(2) # Weights for N3, bias → N4
  18.  
  19. # Training loop
  20. epoch = 0
  21. network_trained = False
  22.  
  23. while epoch < max_iterations:
  24. epoch += 1
  25. all_correct = True
  26.  
  27. for input_vector, target in zip(inputs, targets):
  28. N1, N2 = input_vector
  29. bias = 1 # Bias input
  30.  
  31. # Forward pass
  32. N3_input = np.dot(np.append(input_vector, bias), weights_input_to_hidden)
  33. N3 = activation_function(N3_input) # Output of hidden neuron
  34.  
  35. N4_input = (N3 * weights_hidden_to_output[0] + # From hidden neuron
  36. bias * weights_hidden_to_output[1]) # Bias contribution
  37. N4 = activation_function(N4_input) # Final output
  38.  
  39. # Error calculation
  40. error = target - N4
  41.  
  42. # Weight updates if error exists
  43. if error != 0:
  44. all_correct = False
  45.  
  46. # Update weights for N3 → N4
  47. weights_hidden_to_output[0] += learning_rate * error * N3
  48. weights_hidden_to_output[1] += learning_rate * error * bias
  49.  
  50. # Update weights for N1, N2, bias → N3
  51. weights_input_to_hidden += learning_rate * error * np.append(input_vector, bias)
  52.  
  53. if all_correct:
  54. network_trained = True
  55. break
  56.  
  57. # Results
  58. if network_trained:
  59. print(f"The network learned the XOR truth table correctly after {epoch} iterations.")
  60. else:
  61. print(f"The network failed to learn the XOR truth table after {epoch} iterations.")
  62.  
  63. # Testing the trained network
  64. print("\nTesting the trained network:")
  65. for input_vector, target in zip(inputs, targets):
  66. N1, N2 = input_vector
  67. bias = 1
  68.  
  69. # Forward pass
  70. N3_input = np.dot(np.append(input_vector, bias), weights_input_to_hidden)
  71. N3 = activation_function(N3_input)
  72.  
  73. N4_input = (N3 * weights_hidden_to_output[0] +
  74. bias * weights_hidden_to_output[1])
  75. N4 = activation_function(N4_input)
  76.  
  77. print(f"Input: {input_vector}, Target: {target}, Output: {N4}")
  78.  
Success #stdin #stdout 0.32s 28848KB
stdin
Standard input is empty
stdout
The network failed to learn the XOR truth table after 1000 iterations.

Testing the trained network:
Input: [0 0], Target: 0, Output: 1
Input: [0 1], Target: 1, Output: 1
Input: [1 0], Target: 1, Output: 0
Input: [1 1], Target: 0, Output: 0