0% found this document useful (0 votes)
11 views2 pages

TejasIngole - AIML - Lab13.ipynb - Colab

Uploaded by

tmingolem23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

TejasIngole - AIML - Lab13.ipynb - Colab

Uploaded by

tmingolem23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

10/30/24, 6:19 PM TejasIngole_AIML_Lab13.

ipynb - Colab

Tejas Ingole

232010012

AIML Lab 13

import numpy as np
import matplotlib.pyplot as plt

# Generate synthetic data for demonstration


np.random.seed(0)
X = np.linspace(-3, 3, 100)
y = np.sin(X) + np.random.normal(0, 0.1, X.shape)

# Define a function to compute weights


def get_weights(X, x_query, tau):
return np.exp(-np.square(X - x_query) / (2 * tau ** 2))

# Locally Weighted Regression function


def locally_weighted_regression(X, y, x_query, tau):
m = X.shape[0]
weights = get_weights(X, x_query, tau)
W = np.diag(weights) # Weight matrix
X_b = np.c_[np.ones((m, 1)), X] # Add intercept term
theta = np.linalg.pinv(X_b.T @ W @ X_b) @ X_b.T @ W @ y # Compute parameters
return np.array([1, x_query]).dot(theta)

# Fit the model for different points in X and plot results


def plot_lwr(X, y, tau):
y_pred = np.array([locally_weighted_regression(X, y, x_query, tau) for x_query in X])
plt.scatter(X, y, color='blue', label='Data points')
plt.plot(X, y_pred, color='red', label=f'LWR (tau={tau})')
plt.xlabel("X")
plt.ylabel("y")
plt.legend()
plt.show()

# Experiment with different tau values


plot_lwr(X, y, tau=0.1) # small tau - high bias
plot_lwr(X, y, tau=1.0) # large tau - low bias

https://colab.research.google.com/drive/1rtdHczKlL8MYRSyBB0HZl4rdEVBiq5nu#scrollTo=jqHn… 1/2
10/30/24, 6:19 PM TejasIngole_AIML_Lab13.ipynb - Colab

https://colab.research.google.com/drive/1rtdHczKlL8MYRSyBB0HZl4rdEVBiq5nu#scrollTo=jqHn… 2/2

You might also like