6
import numpy as np
import matplotlib.pyplot as plt
def weight(x, xi, tau):
return np.exp(-np.sum((x - xi) ** 2) / (2 * tau ** 2))
def predict(x, X, y, tau):
W = np.diag([weight(x, xi, tau) for xi in X])
theta = np.linalg.pinv(X.T @ W @ X) @ X.T @ W @ y
return x @ theta
# Generate training data
X = np.linspace(0, 2 * np.pi, 100)
y = np.sin(X) + 0.1 * np.random.randn(100)
X_ = np.c_[np.ones(X.shape), X] # Add bias term
# Generate test data
x_test = np.linspace(0, 2 * np.pi, 200)
x_test_ = np.c_[np.ones(x_test.shape), x_test]
# Predict
tau = 0.5
y_pred = [predict(xi, X_, y, tau) for xi in x_test_]
# Plot
plt.scatter(X, y, alpha=0.6, label="Data")
plt.plot(x_test, y_pred, color="red", label="LWR Prediction")
plt.legend()
plt.title("Locally Weighted Regression")
plt.show()
Comments
Post a Comment