Last active
February 25, 2024 23:05
-
-
Save ThomasParistech/a381d9bb105416bbba343b048f8560ab to your computer and use it in GitHub Desktop.
basic_kde
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from scipy.stats import norm | |
def silverman_bandwidth(x_data: np.ndarray) -> float: | |
return (4/(3*x_data.shape[0]))**0.2 * np.std(x_data) | |
def basic_kde(x_data: np.ndarray, x_prediction: np.ndarray) -> np.ndarray: | |
"""Perform Gaussian Kernel Density Estimation. | |
Args: | |
x_data: Sample points drawn from the distribution to estimate. | |
Numpy array of shape (N,) | |
x_prediction: Points at which to evaluate the density estimate. | |
Numpy array of shape (N,) | |
Returns: | |
Densities evaluated at `x_prediction` by averaging gaussian kernels | |
around `x_data`. Numpy array of shape (N,) | |
""" | |
h = silverman_bandwidth(x_data) | |
pdf_values = norm.pdf(x_prediction.reshape(1, -1), | |
loc=x_data.reshape(-1, 1), | |
scale=h) | |
densities = np.mean(pdf_values, axis=0) | |
return densities |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment