CodeByAM
CodeByAM

Reputation: 13

plotting issue in simple gaussian kernel regression in python

I wrote a python code for kernel regression with gaussian function, but when plotting I'm having a problem that I don't understand why. the plot is not smooth.

this is my code:

import numpy as np
#gaussian regression with bandwidth 0.01
def gaussian_kernel(x, x_i, h):
    return (1 / (np.sqrt(2 * np.pi) * h)) * np.exp(-0.5 * ((x - x_i) / h) ** 2)

def gaussian_kernel_regression(X_train, y_train, X_test, h):
    y_pred = np.zeros(X_test.shape)
    for i, x_test in enumerate(X_test):
        weights = gaussian_kernel(x_test, X_train, h)
        y_pred[i] = np.sum(weights * y_train) / np.sum(weights)
    return y_pred

# Run Gaussian Kernel Regression
h = 0.001  # Bandwidth
y_pred = gaussian_kernel_regression(X_train, y_train, X_test, h)

# Plot the results
plt.scatter(X_train, y_train, color='red', label='Training Data')
plt.plot(X_test, y_pred, color='blue', label='Gaussian Kernel Regression')
plt.title('Gaussian Kernel Regression')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.show()

and this is my out put: enter image description here

Upvotes: 0

Views: 28

Answers (0)

Related Questions