Shafayat__

Untitled

Dec 6th, 2023
746
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.14 KB | None | 0 0
  1. import numpy as np
  2. from sklearn.datasets import make_blobs
  3.  
  4. def make_blocks(n_samples=20, centers=2, n_features=3):
  5.     x, y = make_blobs(n_samples=n_samples, centers=centers, n_features=n_features, random_state=42)
  6.     y = y[:, np.newaxis]  # Adding a new axis to make it compatible with the network architecture
  7.     return x, y
  8.  
  9. def sigmoid(x):
  10.     return 1 / (1 + np.exp(-x))
  11.  
  12. def sigmoid_derivative(x):
  13.     return x * (1 - x)
  14.  
  15. input_neurons = 3
  16. hidden_neurons = 3
  17. output_neurons = 1
  18.  
  19. np.random.seed(42)
  20.  
  21. weights_input_hidden = np.random.rand(input_neurons, hidden_neurons)
  22. bias_hidden = np.zeros((1, hidden_neurons))
  23.  
  24. weights_hidden_output = np.random.rand(hidden_neurons, output_neurons)
  25. bias_output = np.zeros((1, output_neurons))
  26.  
  27. learning_rate = 0.01
  28. epochs = 100
  29.  
  30. x, y = make_blocks(n_samples=20, centers=2, n_features=3)
  31.  
  32. for epoch in range(epochs):
  33.     hidden_layer_input = np.dot(x, weights_input_hidden) + bias_hidden
  34.     hidden_layer_output = sigmoid(hidden_layer_input)
  35.  
  36.     output_layer_input = np.dot(hidden_layer_output, weights_hidden_output) + bias_output
  37.     predicted_output = sigmoid(output_layer_input)
  38.  
  39.     error = y - predicted_output
  40.  
  41.     output_error = error * sigmoid_derivative(predicted_output)
  42.     hidden_layer_error = output_error.dot(weights_hidden_output.T) * sigmoid_derivative(hidden_layer_output)
  43.  
  44.     weights_hidden_output += hidden_layer_output.T.dot(output_error) * learning_rate
  45.     bias_output += np.sum(output_error, axis=0, keepdims=True) * learning_rate
  46.  
  47.     weights_input_hidden += x.T.dot(hidden_layer_error) * learning_rate
  48.     bias_hidden += np.sum(hidden_layer_error, axis=0, keepdims=True) * learning_rate
  49.  
  50. hidden_layer_input = np.dot(x, weights_input_hidden) + bias_hidden
  51. hidden_layer_output = sigmoid(hidden_layer_input)
  52.  
  53. output_layer_input = np.dot(hidden_layer_output, weights_hidden_output) + bias_output
  54. predicted_output = sigmoid(output_layer_input)
  55.  
  56. predicted_output = np.round(predicted_output)
  57.  
  58. accuracy = np.mean(predicted_output == y)
  59.  
  60. print("Predicted Output:")
  61. print(predicted_output)
  62. print("\nTrue Output:")
  63. print(y)
  64. print("\nAccuracy: {:.2%}".format(accuracy))
  65.  
Advertisement
Add Comment
Please, Sign In to add comment