Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import matplotlib.pyplot as plt
- from sklearn.metrics import mean_squared_error
- # Генерация случайной выборки с шумом
- np.random.seed(0)
- X = np.sort(5 * np.random.rand(80, 1), axis=0)
- y_true = np.sin(X).ravel()
- y = y_true + 0.1 * np.random.randn(80)
- # Реализация метода Надарая-Ватсона
- def nadaraya_watson(X_train, y_train, x, h):
- kernel = np.exp(-0.5 * ((X_train - x) / h) ** 2)
- return np.sum(kernel * y_train) / np.sum(kernel)
- # Реализация метода Lawless
- def lawless(X_train, y_train, x, h):
- kernel = np.exp(-0.5 * ((X_train - x) / h) ** 2)
- return np.sum(kernel * y_train) / np.sum(kernel**2)
- # Генерация точек для оценки регрессии
- x_plot = np.linspace(0, 5, 1000)
- # Вычисление оценок для метода Надарая-Ватсона и Lawless
- h = 0.1
- y_nadaraya_watson = [nadaraya_watson(X, y, x, h) for x in x_plot]
- y_lawless = [lawless(X, y, x, h) for x in x_plot]
- # Визуализация результатов
- plt.figure(figsize=(10, 6))
- plt.scatter(X, y, c='r', label='Выборка с шумом')
- plt.plot(x_plot, y_true, label='Истинная функция', linewidth=2)
- plt.plot(x_plot, y_nadaraya_watson, label='Метод Надарая-Ватсона', linewidth=2)
- plt.plot(x_plot, y_lawless, label='Метод Lawless', linewidth=2)
- plt.xlabel('X')
- plt.ylabel('y')
- plt.legend()
- plt.title('Регрессия методом Надарая-Ватсона и Lawless')
- plt.show()
Add Comment
Please, Sign In to add comment