To compute the probability density function (PDF) for a multivariate Gaussian distribution with a diagonal covariance matrix, we'll follow these steps:
-
Extract the variances (diagonal values) from the covariance matrix sigma_i using np.diagonal(sigma_i). This results in a 1-D array of variances for each feature.
-
Calculate the variance-adjusted (normalized) differences between each point and the mean mu_i for every feature: (points - mu_i) / sigma_i_variances, where sigma_i_variances is the square root of the variances obtained in step 1.
-
Compute the exponential part for each feature across all points.
-
Calculate the product of these expressions for all features to get the overall density value for each point.
-
Finally, multiply each of these results by the constant term derived from the variances.
Here's a step-by-step implementation of the normalPDF function:
import numpy as np
class Gaussian:
def normalPDF(self, points, mu_i, sigma_i):
"""
Args:
points: N x D numpy array
mu_i: (D,) numpy array, the center for the ith gaussian.
sigma_i: DxD numpy array, the covariance matrix of the ith gaussian.
Return:
pdf: (N,) numpy array, the probability density value of N data for the ith gaussian
Hint:
np.diagonal() should be handy.
"""
# Extract the variances (sigma^2) which are on the diagonal of sigma_i
variances = np.diagonal(sigma_i)
# Handle the case where variances might be zero (potential for numerical stability issues)
SIGMA_CONST = 1e-8
if np.any(variances == 0):
variances = variances + SIGMA_CONST
# Calculate the constant part
coeff = 1 / np.sqrt(2 * np.pi * variances)
# Calculate the squared differences
squared_diff = (points - mu_i) ** 2
# Calculate the exponent part
exponent = -0.5 * (squared_diff / variances)
# Calculate `exp` for each feature and each point
exp_values = np.exp(exponent)
# Compute product across all features for each point
point_probs = np.prod(coeff * exp_values, axis=1)
return point_probs
Explanation:
- Step 1:
variances = np.diagonal(sigma_i) efficiently extracts the variances of each feature.
- Step 2:
SIGMA_CONST is used to adjust any zero variances for numerical stability.
- Steps 3 to 5: We calculate the exponent using element-wise operations, compute the exponential functions, and then take the product over all dimensions (features) for each point to get the final PDF values.
This implementation assumes that the input data, points, and parameters mu_i and sigma_i are correctly shaped and adhere to the expected dimensions.