Advertisement
fevzi02

Untitled

Dec 12th, 2023
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from sklearn.metrics import mean_squared_error
  4.  
  5. # Генерация случайной выборки с шумом
  6. np.random.seed(0)
  7. X = np.sort(5 * np.random.rand(80, 1), axis=0)
  8. y_true = np.sin(X).ravel()
  9. y = y_true + 0.1 * np.random.randn(80)
  10.  
  11. # Реализация метода Надарая-Ватсона
  12. def nadaraya_watson(X_train, y_train, x, h):
  13. kernel = np.exp(-0.5 * ((X_train - x) / h) ** 2)
  14. return np.sum(kernel * y_train) / np.sum(kernel)
  15.  
  16. # Реализация метода Lawless
  17. def lawless(X_train, y_train, x, h):
  18. kernel = np.exp(-0.5 * ((X_train - x) / h) ** 2)
  19. return np.sum(kernel * y_train) / np.sum(kernel**2)
  20.  
  21. # Генерация точек для оценки регрессии
  22. x_plot = np.linspace(0, 5, 1000)
  23.  
  24. # Вычисление оценок для метода Надарая-Ватсона и Lawless
  25. h = 0.1
  26. y_nadaraya_watson = [nadaraya_watson(X, y, x, h) for x in x_plot]
  27. y_lawless = [lawless(X, y, x, h) for x in x_plot]
  28.  
  29. # Визуализация результатов
  30. plt.figure(figsize=(10, 6))
  31. plt.scatter(X, y, c='r', label='Выборка с шумом')
  32. plt.plot(x_plot, y_true, label='Истинная функция', linewidth=2)
  33. plt.plot(x_plot, y_nadaraya_watson, label='Метод Надарая-Ватсона', linewidth=2)
  34. plt.plot(x_plot, y_lawless, label='Метод Lawless', linewidth=2)
  35. plt.xlabel('X')
  36. plt.ylabel('y')
  37. plt.legend()
  38. plt.title('Регрессия методом Надарая-Ватсона и Lawless')
  39. plt.show()
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement