Advertisement
mirosh111000

Perceptron

Aug 18th, 2024
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.13 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import seaborn as sns
  4. import pandas as pd
  5. from sklearn.model_selection import train_test_split
  6. from sklearn.metrics import accuracy_score
  7. from random import random
  8.  
  9.  
  10. def plot_decision_boundary(perceptron, X, y, title):
  11.     plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='blue', label='0')
  12.     plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='orange', label='1')
  13.    
  14.     x1_values = np.array([X[:, 0].min(), X[:, 0].max()])
  15.     x2_values = -(perceptron.weights[0] * x1_values + perceptron.bias) / perceptron.weights[1]
  16.     plt.plot(x1_values, x2_values, label='Decision Boundary', color='green')
  17.    
  18.     plt.title(title)
  19.     plt.xlabel('X1')
  20.     plt.ylabel('X2')
  21.     plt.legend()
  22.     plt.grid(True)
  23.     plt.show()
  24.  
  25. def activation_function(x):
  26.     # sigmoid, tanh, relu, leakyrelu
  27.     return 1/(1+np.exp(-x))
  28.  
  29. class Perceptron:
  30.    
  31.     # learning_rate - alpha
  32.     def __init__(self, learning_rate = 0.003, n_iters = 15041):
  33.         self.lr = learning_rate
  34.         self.n_iters = n_iters
  35.         self.activation_function = activation_function
  36.         self.weights = None
  37.         self.bias = None
  38.        
  39.     def fit(self, X, Y):
  40.         n_samples, n_features = X.shape
  41.        
  42.         # self.weights = np.zeros(n_features)
  43.         self.weights = np.array([])
  44.         for i in range(n_features):
  45.            self.weights = np.append(self.weights, random())
  46.        
  47.         # self.bias = 0
  48.         self.bias = random()
  49.        
  50.         y_ = np.where(Y > 0, 1, 0)
  51.        
  52.         for iter_ in range(self.n_iters):
  53.             for index, x_i in enumerate(X):
  54.                 linear_output = np.dot(x_i, self.weights) + self.bias
  55.                 y_predicted = self.activation_function(linear_output)
  56.                
  57.                 # Perceptron update rule
  58.                 perceptron_update = self.lr * (y_[index]-y_predicted)
  59.                 self.weights += perceptron_update * x_i
  60.                 self.bias += perceptron_update
  61.                
  62.     def predict(self, x):
  63.         linear_output = np.dot(x, self.weights) + self.bias
  64.         y_predicted = self.activation_function(linear_output)
  65.        
  66.         return np.where(y_predicted > 0.5, 1, 0)
  67.  
  68. data = pd.read_csv('iris.csv')
  69. data = data[data['species'] != 'setosa']
  70. data['target'] = np.where((data['species'] == 'virginica'), 0, 1)
  71. data = data.drop(columns=['species', 'sepal_width', 'sepal_length'])
  72. sns.pairplot(data, hue='target', palette='dark')
  73. plt.show()
  74.  
  75.  
  76.  
  77. x_train, x_test, y_train, y_test = train_test_split(data.iloc[:, :-1], data['target'], test_size=0.2, random_state=42)
  78.  
  79. model = Perceptron(learning_rate=0.1, n_iters=1000)
  80. model.fit(X=x_train.to_numpy(), Y=y_train.to_numpy())
  81.  
  82. y_pred = model.predict(x_test)
  83. y_pred_train = model.predict(x_train)
  84.  
  85. accuracy = accuracy_score(y_true=y_train, y_pred=y_pred_train)
  86. plot_decision_boundary(model, x_train.to_numpy(), y_train, f'Perceptron Train accuracy: {accuracy * 100:.2f}%')
  87.  
  88. accuracy = accuracy_score(y_true=y_test, y_pred=y_pred)
  89. plot_decision_boundary(model, x_test.to_numpy(), y_test, f'Perceptron Test accuracy: {accuracy * 100:.2f}%')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement