6

import numpy as np, matplotlib.pyplot as plt

def lwr(x, X, y, tau):

    W = np.diag(np.exp(-np.sum((X - x)**2, axis=1) / (2 * tau**2)))

    return x @ np.linalg.pinv(X.T @ W @ X) @ X.T @ W @ y

np.random.seed(42)

X = np.linspace(0, 2*np.pi, 100)

y = np.sin(X) + 0.1*np.random.randn(100)

Xb = np.c_[np.ones(X.shape), X]

xt = np.linspace(0, 2*np.pi, 200)

xtb = np.c_[np.ones(xt.shape), xt]

tau = 0.5

yp = np.array([lwr(xi, Xb, y, tau) for xi in xtb])

plt.figure(figsize=(10,6))

plt.scatter(X, y, c='red', alpha=0.7, label='Training Data')

plt.plot(xt, yp, c='blue', lw=2, label=f'LWR Fit (tau={tau})')

plt.xlabel('X'), plt.ylabel('y'), plt.title('Locally Weighted Regression')

plt.legend(), plt.grid(alpha=0.3)

plt.show()

Comments

Popular posts from this blog

9

7

10