# Plot the 1D density curve for the gaussian kernel
# Create a sample distribution
N = 100
X = np.concatenate((np.random.normal(0, 1, int(0.6 * N)),
np.random.normal(10, 1, int(0.4 * N)))
)[:, np.newaxis]
X_plot = np.linspace(-5, 15, 1000)[:, np.newaxis]
# Calculate the true density
true_density = 0.6 * norm(0, 1).pdf(X_plot[:, 0]) + \
0.4 * norm(10, 1).pdf(X_plot[:, 0])
# Creating a figure
fig, ax = plt.subplots()
# Plotting the true density
ax.fill(
X_plot[:, 0], true_density,
fc='black', alpha=0.2,
label='Sample distribution'
)
# Calculating the density using the gaussian kernel with bandwidth 0.5
kde = KernelDensity(kernel='gaussian', bandwidth=0.5).fit(X)
# Calculating the log of the probability density function
log_dens = kde.score_samples(X_plot)
# Plotting the density curve
ax.plot(
X_plot[:, 0],
np.exp(log_dens),
color="cornflowerblue",
linestyle="-",
label="Gaussian kernel density"
)
# Set the title, x and y labels of the plot
ax.set_title("Gaussian Kernel Density")
ax.set_xlim(-4, 15)
ax.set_ylim(0, 0.3)
ax.grid(True)
ax.legend(loc='upper right')
# Display the plot
plt.show()