绘制拟合联合密度分布
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KernelDensity
np.random.seed(42)
mean = [0, 0]
cov = [[1, 0.5], [0.5, 1]]
data = np.random.multivariate_normal(mean, cov, size=200)
a = data[:, 0]
y = data[:, 1]
x_grid = np.linspace(a.min(), a.max(), 100)
y_grid = np.linspace(y.min(), y.max(), 100)
X, Y = np.meshgrid(x_grid, y_grid)
positions = np.vstack([X.ravel(), Y.ravel()]).T
kde = KernelDensity(kernel='gaussian', bandwidth=0.2).fit(data)
log_dens = kde.score_samples(positions)
dens = np.reshape(np.exp(log_dens), X.shape)
plt.figure(figsize=(8, 6))
plt.contourf(X, Y, dens, cmap='viridis')
plt.colorbar(label='Density')
plt.scatter(a, y, color='red', label='Data Points')
plt.xlabel('a')
plt.ylabel('y')
plt.title('Joint Density of a and y')
plt.legend()
plt.show()