Advertisement
mirosh111000

Perceptron(pr3)

Sep 3rd, 2024
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.60 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, beta=1.0):
  12.     return 1 / (1 + np.exp(-beta * x))  # Сигмоїдна функція з параметром beta
  13.  
  14. class Perceptron:
  15.    
  16.     def __init__(self, learning_rate=0.003, n_iters=15041, eps=0.1, return_stop=False, beta=1.0):
  17.         self.lr = learning_rate
  18.         self.n_iters = n_iters
  19.         self.weights = None
  20.         self.bias = None
  21.         self.eps = eps
  22.         self.return_stop = return_stop
  23.         self.beta = beta
  24.         self.activation_function = lambda x: activation_function(x, self.beta)
  25.         self.misclassified_counts = []
  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.         for iter_ in range(self.n_iters):
  34.             n_misclassified = 0
  35.            
  36.             for index, x_i in enumerate(X):
  37.                 linear_output = np.dot(x_i, self.weights) + self.bias
  38.                 y_predicted = self.activation_function(linear_output)
  39.                
  40.                 error = Y[index] - y_predicted
  41.                
  42.                 self.weights += self.lr * error * y_predicted * (1 - y_predicted) * x_i * self.beta
  43.                 self.bias += self.lr * error * y_predicted * (1 - y_predicted) * self.beta
  44.                
  45.                 # Перевірка на відповідність умовам зупинки
  46.                 if np.abs(error) > self.eps:
  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.         if self.return_stop != False:
  58.             return iter_
  59.            
  60.                
  61.     def predict(self, x):
  62.         linear_output = np.dot(x, self.weights) + self.bias
  63.         y_predicted = self.activation_function(linear_output)
  64.         return y_predicted
  65.  
  66.  
  67.  
  68. N = 100
  69. M = 10  
  70.  
  71. data = np.random.randint(0, 2, size=(N, M))
  72. target = np.where(np.mean(data, axis=1) < 0.5, 0, 1)
  73. bias = np.ones((N, 1))
  74. data_with_bias = np.hstack((data, bias))
  75.  
  76. df = pd.DataFrame(data_with_bias, columns=[f'x{i}' for i in range(1, M+1)] + ['bias'])
  77. df['target'] = (np.mean(data, axis=1))
  78.  
  79. print(df)
  80.  
  81.  
  82. x_train, x_test, y_train, y_test = train_test_split(df.iloc[:, :-1], df[['target']], test_size=0.2, random_state=42)
  83.  
  84.  
  85. model = Perceptron(learning_rate=0.01, n_iters=1000, eps=0.1, beta=2)
  86. model.fit(X=x_train.to_numpy(), Y=y_train.to_numpy())
  87.  
  88. def get_results(model, x, y):
  89.     y_pred = model.predict(x.to_numpy())
  90.     preds_df = y.copy()
  91.     preds_df['preds'] = y_pred
  92.     preds_df['error'] = np.abs(preds_df['preds'] - preds_df['target'])
  93.     return preds_df
  94.  
  95.  
  96. y_pred = model.predict(x_test.to_numpy())
  97. y_pred_train = model.predict(x_train.to_numpy())
  98.  
  99. preds_train_df = get_results(model, x_train, y_train)
  100. preds_df = get_results(model, x_test, y_test)
  101. print(f"Err in train = {len(preds_train_df.loc[preds_train_df['error'] > 0.1])}")
  102. print(f"Err in test = {len(preds_df.loc[preds_df['error'] > 0.1])}")
  103. print(preds_train_df)
  104. print(preds_df)
  105. print(preds_train_df.describe())
  106. print(preds_df.describe())
  107.  
  108. plt.figure(figsize=(10, 5))
  109. plt.title(f'Залежнiсть кiлькостi помилок вiд номера епохи навчання(lr={model.lr})')
  110. plt.plot(np.arange(1, len(model.misclassified_counts)+1), model.misclassified_counts, '-')
  111. plt.xlabel('Номер епохи')
  112. plt.ylabel('Кількість помилок')
  113. plt.grid()
  114. plt.show()
  115.  
  116.  
  117. learning_rates = np.linspace(0.001, 6, 500)
  118. epochs_needed = []
  119.  
  120. for lr in learning_rates:
  121.     print(lr)
  122.     model = Perceptron(learning_rate=lr, n_iters=500, eps=0.1, beta=1, return_stop=1)
  123.     epochs = model.fit(X=x_train.to_numpy(), Y=y_train.to_numpy())
  124.     epochs_needed.append(epochs)
  125.  
  126. plt.figure(figsize=(10, 6))
  127. plt.plot(learning_rates, epochs_needed)
  128. plt.xlabel("Крок навчання (learning rate)")
  129. plt.ylabel("Кількість епох")
  130. plt.title("Залежність кількості епох від кроку навчання")
  131. plt.grid(True)
  132. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement