mirosh111000

Perceptron(pr2)

Aug 19th, 2024
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.38 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.datasets import make_blobs
  6. from sklearn.decomposition import PCA
  7. from sklearn.model_selection import train_test_split
  8. from sklearn.metrics import silhouette_score, accuracy_score
  9. from random import random
  10.  
  11. def activation_function(x):
  12.     #f(x)=1/(1+e^(-x))
  13.     # sigmoid, tanh, relu, leakyrelu
  14.     return 1/(1+np.exp(-x))
  15.  
  16. class Perceptron:
  17.    
  18.     def __init__(self, learning_rate=0.003, n_iters=15041, return_stop=False):
  19.         self.lr = learning_rate
  20.         self.n_iters = n_iters
  21.         self.activation_function = activation_function
  22.         self.weights = None
  23.         self.bias = None
  24.         self.misclassified_counts = []
  25.         self.return_stop = return_stop
  26.        
  27.     def fit(self, X, Y):
  28.         n_samples, n_features = X.shape
  29.        
  30.         self.weights = np.array([random() for _ in range(n_features)])
  31.         self.bias = random()
  32.        
  33.         y_ = np.where(Y > 0, 1, 0)
  34.        
  35.         for iter_ in range(self.n_iters):
  36.             n_misclassified = 0  
  37.            
  38.             for index, x_i in enumerate(X):
  39.                 linear_output = np.dot(x_i, self.weights) + self.bias
  40.                 y_predicted = self.activation_function(linear_output)
  41.                
  42.                 perceptron_update = self.lr * (y_[index] - y_predicted)
  43.                 self.weights += perceptron_update * x_i
  44.                 self.bias += perceptron_update
  45.                
  46.                 if (y_predicted > 0.5) != y_[index]:
  47.                     n_misclassified += 1
  48.            
  49.             self.misclassified_counts.append(n_misclassified)
  50.            
  51.             if n_misclassified == 0:
  52.                 print(f"Навчання зупинено на епохі {iter_}")
  53.                 if self.return_stop != False:
  54.                     return iter_
  55.                 break
  56.                
  57.     def predict(self, x):
  58.         linear_output = np.dot(x, self.weights) + self.bias
  59.         y_predicted = self.activation_function(linear_output)
  60.         return np.where(y_predicted > 0.5, 1, 0)
  61.  
  62.  
  63.  
  64.  
  65. N = 1000  # Кількість наборів
  66. M = 40   # Довжина кожного набору
  67.  
  68. data = np.random.randint(0, 2, size=(N, M))
  69. target = np.where(np.mean(data, axis=1) < 0.5, 0, 1)
  70. bias = np.ones((N, 1))
  71. data_with_bias = np.hstack((data, bias))
  72.  
  73. df = pd.DataFrame(data_with_bias, columns=[f'x{i}' for i in range(1, M+1)] + ['bias'])
  74. df['target'] = target
  75.  
  76. pca = PCA(n_components=2)
  77. X_pca = pca.fit_transform(data_with_bias)
  78. df_pca = pd.DataFrame(X_pca, columns=[f'PCA{i+1}' for i in range(2)])
  79. df_pca['target'] = target
  80. sns.pairplot(df_pca, hue='target', palette='dark')
  81. plt.show()
  82.  
  83. print(df.target.value_counts())
  84.  
  85. df
  86.  
  87.  
  88. x_train, x_test, y_train, y_test = train_test_split(df.iloc[:, :-1], df['target'], test_size=0.2, random_state=42)
  89.  
  90. model = Perceptron(learning_rate=0.1, n_iters=15000)
  91. model.fit(X=x_train.to_numpy(), Y=y_train.to_numpy())
  92.  
  93. y_pred = model.predict(x_test)
  94. y_pred_train = model.predict(x_train)
  95. preds = model.predict(df.iloc[:, :-1])
  96. df['preds'] = preds
  97. df
  98.  
  99. train_accuracy = accuracy_score(y_true=y_train, y_pred=y_pred_train)
  100. accuracy = accuracy_score(y_true=y_test, y_pred=y_pred)
  101. print(f'Точність на навчальній вибірці: {accuracy*100}%\nТочність на тренувальній вибірці: {train_accuracy*100}%')
  102.  
  103. plt.figure(figsize=(10, 5))
  104. plt.title('Залежнiсть кiлькостi помилок вiд номера епохи навчання')
  105. plt.plot(np.arange(1, len(model.misclassified_counts)+1), model.misclassified_counts, '-')
  106. plt.xlabel('Номер епохи')
  107. plt.ylabel('Кількість помилок')
  108. plt.grid()
  109. plt.show()
  110.  
  111.  
  112.  
  113. learning_rates = np.linspace(0.001, 1, 100)
  114. epochs_needed = []
  115.  
  116. for lr in learning_rates:
  117.     print(lr)
  118.     model = Perceptron(learning_rate=lr, n_iters=15000, return_stop=1)
  119.     epochs = model.fit(X=x_train.to_numpy(), Y=y_train.to_numpy())
  120.     epochs_needed.append(epochs)
  121.  
  122. plt.figure(figsize=(10, 6))
  123. plt.plot(learning_rates, epochs_needed)
  124. plt.xlabel("Крок навчання (learning rate)")
  125. plt.ylabel("Кількість епох для повної класифікації")
  126. plt.title("Залежність кількості епох від кроку навчання")
  127. plt.grid(True)
  128. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment