<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zackary Nay on Medium]]></title>
        <description><![CDATA[Stories by Zackary Nay on Medium]]></description>
        <link>https://medium.com/@znay854?source=rss-66db740b91ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m5xrH1MQFrQ9Q4xTY86C9A.jpeg</url>
            <title>Stories by Zackary Nay on Medium</title>
            <link>https://medium.com/@znay854?source=rss-66db740b91ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:26:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@znay854/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Math Behind Kernel Density Estimation]]></title>
            <link>https://medium.com/data-science/the-math-behind-kernel-density-estimation-5deca75cba38?source=rss-66db740b91ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/5deca75cba38</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kernel-density-estimation]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <dc:creator><![CDATA[Zackary Nay]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 04:52:16 GMT</pubDate>
            <atom:updated>2024-09-17T04:52:16.761Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring the foundations, concepts, and math of kernel density estimation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*F_wPsQ6BJsuFG7v_" /></figure><p>The Kernel Density Estimator is a fundamental non-parametric method that is a versatile tool for uncovering the hidden distributions of your data. This article delves into the mathematical foundations of the estimator, provides guidance on choosing the optimal bandwidth, and briefly touches on the choice of kernel functions and other related topics.</p><h3><strong>Part 1: Introduction</strong></h3><p>Suppose I give you the following sample of data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*oKocZuIE-iHlffxY9FnqNQ.png" /></figure><p>One of the first and easiest steps in analyzing sample data is to generate a histogram, for our data we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*XeK5Xw1rbgyIJ4jEq988gg.png" /></figure><p>Not very useful, and we are no closer to understanding what the underlying distribution is. There is also the additional problem that, in practice, data rarely exhibit the sharp rectangular structure produced by a histogram. The kernel density estimator provides a remedy, and it is a non-parametric way to estimate the probability density function of a random variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*zI9LLpeEISPYYTfT1luurQ.png" /></figure><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.neighbors import KernelDensity<br><br># Generate sample data<br>np.random.seed(14)<br>uniform_data = np.random.uniform(low=1, high=7, size=20)<br>normal_data = np.random.normal(loc=3, scale=0.7, size=20)<br><br># Combine both distributions<br>combined_data = np.concatenate([uniform_data, normal_data])<br><br># Compute histogram<br>hist, bin_edges = np.histogram(combined_data, bins=9, density=True)<br><br># Compute KDE<br>kde = KernelDensity(kernel=&#39;gaussian&#39;).fit(combined_data[:, None])<br>x = np.linspace(min(combined_data), max(combined_data), 1000)[:, None]<br>log_density = kde.score_samples(x)<br>density = np.exp(log_density)<br><br># Plot histogram<br>plt.hist(combined_data, bins=9, density=True, color=&#39;blue&#39;, edgecolor=&#39;black&#39;, label=&#39;Histogram&#39;)<br><br># Plot KDE<br>plt.plot(x, density, color=&#39;red&#39;, label=&#39;KDE&#39;)<br><br># Add labels and legend<br>plt.ylabel(&#39;Density&#39;)<br>plt.title(&#39;Histogram and KDE&#39;)<br>plt.legend()<br><br># Show plot<br>plt.show()</pre><h3><strong>Part 2: Derivation</strong></h3><p>The following derivation takes inspiration from Bruce E. Hansen’s “Lecture Notes on Nonparametric” (2009). If you are interested in learning more you can refer to his original lecture notes <a href="https://users.ssc.wisc.edu/~bhansen/718/NonParametrics1.pdf">here</a>.</p><p>Suppose we wanted to estimate a probability density function, f(t), from a sample of data. A good starting place would be to estimate the cumulative distribution function, F(t), using the <a href="https://en.wikipedia.org/wiki/Empirical_distribution_function#:~:text=The%20empirical%20distribution%20function%20is,to%20the%20Glivenko%E2%80%93Cantelli%20theorem.">empirical distribution function</a> (EDF). Let X1, …, Xn be independent, identically distributed real random variables with the common cumulative distribution function F(t). The EDF is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/0*yhjpN75rpiOgwWYI" /></figure><p>Then, by the strong law of large numbers, as n approaches infinity, the EDF converges almost surely to F(t). Now, the EDF is a step function that could look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*9hGEf6J4lmxY5eO-XjjwZA.png" /></figure><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import norm<br><br># Generate sample data<br>np.random.seed(14)<br>data = np.random.normal(loc=0, scale=1, size=40)<br><br># Sort the data<br>data_sorted = np.sort(data)<br><br># Compute ECDF values<br>ecdf_y = np.arange(1, len(data_sorted)+1) / len(data_sorted)<br><br># Generate x values for the normal CDF<br>x = np.linspace(-4, 4, 1000)<br>cdf_y = norm.cdf(x)<br><br># Create the plot<br>plt.figure(figsize=(6, 4))<br>plt.step(data_sorted, ecdf_y, where=&#39;post&#39;, color=&#39;blue&#39;, label=&#39;ECDF&#39;)<br>plt.plot(x, cdf_y, color=&#39;gray&#39;, label=&#39;Normal CDF&#39;)<br>plt.plot(data_sorted, np.zeros_like(data_sorted), &#39;|&#39;, color=&#39;black&#39;, label=&#39;Data points&#39;)<br><br># Label axes<br>plt.xlabel(&#39;X&#39;)<br>plt.ylabel(&#39;Cumulative Probability&#39;)<br><br># Add grid<br>plt.grid(True)<br><br># Set limits<br>plt.xlim([-4, 4])<br>plt.ylim([0, 1])<br><br># Add legend<br>plt.legend()<br><br># Show plot<br>plt.show()</pre><p>Therefore, if we were to try and find an estimator for f(t) by taking the derivative of the EDF, we would get a scaled sum of <a href="https://en.wikipedia.org/wiki/Dirac_delta_function">Dirac delta functions</a>, which is not very helpful. Instead let us consider using the t<a href="https://home.cc.umanitoba.ca/~farhadi/Math2120/Numerical%20Differentiation.pdf">wo-point central difference formula</a> of the estimator as an approximation of the derivative. Which, for a small h&gt;0, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*TIkB0uWLNE3lma6RoJQ-AQ.png" /></figure><p>Now define the function k(u) as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*9ZZppiYGQDIhtYbKrNot0g.png" /></figure><p>Then we have that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*wlbC5odz5vXjYZrdVCFlmQ.png" /></figure><p>Which is a special case of the kernel density estimator, where here k is the uniform kernel function. More generally, a kernel function is a non-negative function from the reals to the reals which satisfies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*irSK8t7abMhiH0OBsPl49g.png" /></figure><p>We will assume that all kernels discussed in this article are symmetric, hence we have that k(-u) = k(u).</p><p>The moment of a kernel, which gives insights into the shape and behavior of the kernel function, is defined as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*QkInx-WZh98kNIFaBZIy1g.png" /></figure><p>Lastly, the order of a kernel is defined as the first non-zero moment.</p><p>We can only minimize the error of the kernel density estimator by either changing the h value (bandwidth), or the kernel function. The bandwidth parameter has a much larger impact on the resulting estimate than the kernel function but is also much more difficult to choose. To demonstrate the influence of the h value, take the following two kernel density estimates. A Gaussian kernel was used to estimate a sample generated from a standard normal distribution, the only difference between the estimators is the chosen h value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*dmW9flkr_nhEiDPJ_eEauw.png" /></figure><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.stats import gaussian_kde<br><br># Generate sample data<br>np.random.seed(14)<br>data = np.random.normal(loc=0, scale=1, size=100)<br><br># Define the bandwidths<br>bandwidths = [0.1, 0.3]<br><br># Plot the histogram and KDE for each bandwidth<br>plt.figure(figsize=(12, 8))<br>plt.hist(data, bins=30, density=True, color=&#39;gray&#39;, alpha=0.3, label=&#39;Histogram&#39;)<br><br>x = np.linspace(-5, 5, 1000)<br>for bw in bandwidths:<br>    kde = gaussian_kde(data , bw_method=bw)<br>    plt.plot(x, kde(x), label=f&#39;Bandwidth = {bw}&#39;)<br><br># Add labels and title<br>plt.title(&#39;Impact of Bandwidth Selection on KDE&#39;)<br>plt.xlabel(&#39;Value&#39;)<br>plt.ylabel(&#39;Density&#39;)<br>plt.legend()<br>plt.show()</pre><p>Quite a dramatic difference.</p><p>Now let us look at the impact of changing the kernel function while keeping the bandwidth constant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*0bPsJQDRiqHJCfiiDZLbpw.png" /></figure><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.neighbors import KernelDensity<br><br># Generate sample data<br>np.random.seed(14)<br>data = np.random.normal(loc=0, scale=1, size=100)[:, np.newaxis]  # reshape for sklearn<br><br># Intialize a constant bandwidth<br>bandwidth = 0.6<br><br># Define different kernel functions<br>kernels = [&quot;gaussian&quot;, &quot;epanechnikov&quot;, &quot;exponential&quot;, &quot;linear&quot;]<br><br># Plot the histogram (transparent) and KDE for each kernel<br>plt.figure(figsize=(12, 8))<br><br># Plot the histogram<br>plt.hist(data, bins=30, density=True, color=&quot;gray&quot;, alpha=0.3, label=&quot;Histogram&quot;)<br><br># Plot KDE for each kernel function<br>x = np.linspace(-5, 5, 1000)[:, np.newaxis]<br>for kernel in kernels:<br>    kde = KernelDensity(bandwidth=bandwidth, kernel=kernel)<br>    kde.fit(data)<br>    log_density = kde.score_samples(x)<br>    plt.plot(x[:, 0], np.exp(log_density), label=f&quot;Kernel = {kernel}&quot;)<br><br>plt.title(&quot;Impact of Different Kernel Functions on KDE&quot;)<br>plt.xlabel(&quot;Value&quot;)<br>plt.ylabel(&quot;Density&quot;)<br>plt.legend()<br>plt.show()</pre><p>While visually there is a large difference in the tails, the overall shape of the estimators are similar across the different kernel functions. Therefore, I will focus primarily focus on finding the optimal bandwidth for the estimator. Now, let’s explore some of the properties of the kernel density estimator, including its bias and variance.</p><h3><strong>Part 3: Properties of the Kernel Density Estimator</strong></h3><p>The first fact that we will need to utilize is that the integral of the estimator across the real line is 1. To prove this fact, we will need to make use of the change of u-substitution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/1*Rirldq6Ahb6M_1f8flG97g.png" /></figure><p>Employing that u-substitution we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*rMu05I-vR3wgS273jvRYag.png" /></figure><p>Now we can find the mean of the estimated density:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*gcl-RmBmUX-0ckSf3W0D7g.png" /></figure><p>Therefore, the mean of the estimated density is simply the sample mean.</p><p>Now let us find the second moment of the estimator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*UvBdirk5TFVc0B1-tqGFvg.png" /></figure><p>We can then find the variance of the estimated density:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*2L8yg-XHu5b1TVmb2xK_AA.png" /></figure><p>To find the optimal bandwidth and kernel, we will be minimizing the mean squared error of the estimator. To achieve this, we will first need to find the bias and variance of the estimator.</p><p>The expected value of a random variable, X, with a probability density function of f, can be calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*y68e0tssFy_kIiA8dHsLGg.png" /></figure><p>Thus,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*AEoe4uIXoOka_RAdhNXVTA.png" /></figure><p>Where z is a dummy variable of integration. We can then use a change of variables to get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*BHaceX__iv6_FcOim3IgFA.png" /></figure><p>Therefore, we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*H7d2rZ3pjpxt54JW6KNbyg.png" /></figure><p>Most of the time, however, the integral above is not analytically solvable. Therefore, we will have to approximate f(x+ hu) by using its Taylor expansion. As a reminder, the Taylor expansion of f(x) around a is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*PStWa0WTmxk458qfVAxCVQ.png" /></figure><p>Thus, assume f(x) is differentiable to the v+1 term. For f(x+hu) the expansion is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*H-lTZbtZ4vCZ_4MpWvDulw.png" /></figure><p>Then for a v-order kernel, we can take the expression out to the v’th term:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*Euembivc9-i0JLpvo2vdxQ.png" /></figure><p>Where the last term is the remainder, which vanishes faster than h as h approaches 0. Now, assuming that k is a v’th order kernel function, we have that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*yMwOMCHtTWkTdI0WNLOegQ.png" /></figure><p>Therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*rVVw593gCvCaybd1m-fiPg.png" /></figure><p>Thus we have that the bias of the estimator is then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*5iKkoxvs-4irAmLnRATPuw.png" /></figure><p>The upper bound for the variance can be obtained via the following calculation <a href="https://faculty.washington.edu/yenchic/17Sp_403/Lec7-density.pdf">[Chen 2].</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*8eOw9_Z_ojCo8WVduod8xg.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*UooBfFpGIt3luHjT7JktlA.png" /></figure><p>This term is also known as the roughness and can be denoted as R(k).</p><p>Finally, we can get an expression for the mean squared error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*-d_EN0GcjJSoyZ4hZ0gQbQ.png" /></figure><p>Where AMSE is short for asymptotic mean squared error. We can then minimize the asymptotic mean integrated square error defined as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*eEMFxHEX-LGRxDaFfjb0VA.png" /></figure><p>to find what bandwidth will lead to the lowest error (Silverman, 1986):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*L207o-vnU_o99xK-yFvLWw.png" /></figure><p>Then, by setting the equation to 0 and simplifying we find that the optimal bandwidth for a kernel of order v is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*43GH8UcKXfvZKyud4Emr8A.png" /></figure><p>The more familiar expression is for second order kernels, where the bandwidth that minimizes the AMISE is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*O_BdeRAIgcJ7sJ4BvPNz8w.png" /></figure><p>However, this solution may be a letdown as we require knowing the distribution that we are estimating to find the optimal bandwidth. In practice, we would not have this distribution if we were using the kernel density estimator in the first place.</p><h3><strong>Part 4: Bandwidth Selection</strong></h3><p>Despite not being able to find the bandwidth that minimizes the mean integrated square error, there are several methods available to choose a bandwidth without knowing the underlying distribution.<strong> It is important to note, however, that a larger h value will cause your estimator to have less variance but greater bias, while a smaller bandwidth will produce a rougher estimate with less bias (Eidous et al., 2010).</strong></p><p>Some methods to find a bandwidth include using:</p><p>1: The Solve-the-Equation Rule</p><p>2: Least Squares Cross-Validation</p><p>3: Biased Cross-Validation</p><p>4: The Direct Plug in Method</p><p>5: The Contrast Method</p><p>It is important to note that depending on the sample size and skewness of your data, the ‘best’ method to choose your bandwidth changes. Most packages in Python allow you to use Silverman&#39;s proposed method, where you directly plug in some distribution (typically normal) for f and then compute the bandwidth based upon the kernel function that you have chosen. This procedure, known as <strong>Silverman’s Rule of Thumb, </strong>provides a relatively simple estimate for the bandwidth. However, it often tends to overestimate, resulting in a smoother estimate with lower variance but higher bias. Silverman’s Rule of Thumb also specifically does not perform well for bimodal distributions, and there are more accurate techniques available for those cases.</p><p>If you assume that your data is normally distributed with a mean of 0, use the sample standard deviation, and apply the Epanechnikov kernel (discussed below), you can select the bandwidth using the Rule of Thumb via the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*0mWqlRcoWmtpodrkamvlKQ.png" /></figure><p>Eidous et al. found the Contrast Method to have the best performance compared to the other methods I listed. However, this method has drawbacks, as it increases the number of parameters to be chosen.</p><p>The cross validation method is another good choice in bandwidth selection method, as it often leads to a small bias but a large variance (Heidenreich et al, 2013). It is most useful for when you are looking for a bandwidth selector that tends to undershoot the optimal bandwidth. To keep this article not overly long I will only be going over the Ordinary Least Squares Cross Validation method. The method tends to work well for rather wiggly densities and a moderate sample size of around 50 to 100. If you have a very small or large sample size this <a href="https://core.ac.uk/download/pdf/159147961.pdf">paper</a> is a good resource to find another way to choose your bandwidth. As pointed out by Heidenreich, “<strong>it definitely makes a difference which bandwidth selector is chosen; not only in numerical terms but also for the quality of density estimation</strong>”.</p><p>As a quick refresher, when we are creating a model we reserve some of our sample as a validation set to see how our model performs on the sample that it has not been trained on. K Fold Cross Validation minimizes the impact of possibly selecting a test set that misrepresents the dataset by splitting the dataset into K parts and then training the model K times and allowing each part to be the validation set once.</p><p>Leave One Out Cross Validation is K Fold Cross Validation taken to the extreme, where for a sample size of n, we train the model n times and leave out one sample each time. <a href="https://machinelearningmastery.com/loocv-for-evaluating-machine-learning-algorithms/">Here</a> is an article that goes more in-depth into the method in the context of training machine learning algorithms.</p><p>Let us turn back to the AMISE expression. Instead of investigating the asymptotic mean integrated square error, we will minimize the mean integrated square error (MISE). First, we can expand the square:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*dYmVIPVJN1wYAqZ33Tq25g.png" /></figure><p>As we have no control over the expected value of the last term, we can seek to minimize the first two terms and drop the third. Then, because X is an unbiased estimator for E[X], we can find the first term directly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*17bedUR-XtOYEdTpmMavFA.png" /></figure><p>Then the convolution of k with k is defined as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*eJWYN8Ma8WTM6K1rmPq3RA.png" /></figure><p>Hence,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*i18VZNEK1V8Uu0onTP5dZw.png" /></figure><p>Thus, for the first term, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*G24Nu9mrIDvjMX65xKrTjw.png" /></figure><p>Next, we can approximate the second term by Monte Carlo methods. First, as discussed earlier, the density function is equivalent to the derivative of the cumulative distribution function, which we can approximate via the empirical distribution function. Then, the integral can be approximated by the average value of the estimator over the <a href="https://jwmi.github.io/BMS/chapter5-monte-carlo.pdf">sample</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*5aZkGHD6pFJsn6JVJfgXAA.png" /></figure><p>Then the least squares cross validation selector (LSCV) is defined as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*JwYhB-Zh1JLm2vpCy_hQfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*PygHhmLYkG-_GDxK_c4h4w.png" /></figure><p>We then get the final selector defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*AHH1VcxSpJ6EZA-Uv2YQtQ.png" /></figure><p>The optimal bandwidth is the h value that minimizes LSCV, defined as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*s7f2CN6LECRsM5B78uT66A.png" /></figure><p>The LSCV(h) function can have multiple local minimums, hence the optimal bandwidth that you find can be sensitive to the interval chosen. It is useful to graph the function and then visually investigate where the global minimum lies.</p><h3><strong>Part 5: Optimal Kernel Selection</strong></h3><p>If we are working with a second order kernel (which is typical), the choice in kernel selection is much more straightforward than bandwidth. <strong>Under the criteria of minimizing the AMISE, the Epanechnikov</strong> <strong>kernel is an optimal kernel.</strong> The full proof can be found in this paper by <a href="https://projecteuclid.org/journals/annals-of-statistics/volume-12/issue-2/Smooth-Optimum-Kernel-Estimators-of-Densities-Regression-Curves-and-Modes/10.1214/aos/1176346523.full">Muler</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*_7C5QW_ctz1rtHfWdsCaPg.png" /></figure><p>There are other kernels which are as efficient as the Epanechnikov kernel, which are also touched on in Muler’s paper. However, I wouldn’t worry too much about your choice of kernel function, the choice in bandwidth is much more important.</p><h3><strong>Part 6: Further Topics and Conclusion</strong></h3><h4>Adaptive Bandwidths</h4><p>One of the proposed ways to improve the Kernel Density Estimator is through an adaptive bandwidth. An adaptive bandwidth adjusts the bandwidth for each data point, increasing it when the density of the sample data is lower and decreasing it when the density is higher. While promising in theory, an adaptive bandwidth has been shown to perform quite poorly in the univariate case (<a href="https://projecteuclid.org/journals/annals-of-statistics/volume-20/issue-3/Variable-Kernel-Density-Estimation/10.1214/aos/1176348768.full">Terrel, Scott 1992</a>). While it may be better for larger dimensional spaces, for the one-dimensional case I believe it is best to stick with a constant bandwidth.</p><h4>Multivariate Kernel Density Estimation</h4><p>The kernel density estimator can also be extended to higher dimensions, where the kernel is a radial basis function or is a product of multiple kernel functions. The approach does suffer from the curse of dimensionality, where as the dimension grows larger the number of data points needed to produce a useful estimator grows exponentially. It is also computationally expensive and is not a great method for analyzing high-dimensional data.</p><p>Nonparametric multivariate density estimation is still a very active field, with <a href="https://arxiv.org/abs/1705.07057">Masked Autoregressive Flow </a>appearing to be quite a new and promising approach.</p><h4>Real World Applications</h4><p>Kernel density estimation has numerous applications across disciplines. First, it has been shown to improve machine learning algorithms such as in the case of the flexible naive Bayes classifier.</p><p>It has also been used to estimate <a href="https://www.sciencedirect.com/science/article/pii/S2095756415305808">traffic accident density</a>. The linked paper uses the KDE to help make a model that indicates the risk of traffic accidents in different cities across Japan.</p><p>Another fun use is in <a href="https://pubs.geoscienceworld.org/ssa/bssa/article-abstract/86/2/353/120015/Kernel-estimation-methods-for-seismic-hazard-area">seismolog</a>y, where the KDE has been used for modelling the risk of earthquakes in different locations.</p><h4>Conclusion</h4><p>The kernel density estimator is an excellent addition to the data analysts’ toolbox. While a histogram is certainly a fine way of analyzing data without using any underlying assumptions, the kernel density estimator provides a solid alternative for univariate data. For higher dimensional data, or for when computational time is a concern, I would recommend looking elsewhere. Nonetheless, the KDE is an intuitive, powerful and versatile tool in data analysis.</p><p><em>Unless otherwise noted, all images are by the author.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5deca75cba38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-math-behind-kernel-density-estimation-5deca75cba38">The Math Behind Kernel Density Estimation</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strange Attractors in Python]]></title>
            <link>https://medium.com/intuition/strange-attractors-in-python-2d08921892d1?source=rss-66db740b91ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d08921892d1</guid>
            <category><![CDATA[science]]></category>
            <category><![CDATA[chaos-theory]]></category>
            <category><![CDATA[strange-attractors]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Zackary Nay]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 19:54:09 GMT</pubDate>
            <atom:updated>2024-03-08T03:09:05.895Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simulating Chaos using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*IpGWXyABAH-SCIAu.png" /></figure><p><strong>Some</strong> of the most beautiful visualizations in mathematics come from strange attractors. From a simple set of dynamic equations, we can produce beautiful three-dimensional shapes and structures. The visualizations are surprisingly easy to create using Python and little knowledge of the math behind the equations is required to start making your own!</p><p>There are a few librarys we need first:</p><pre>import matplotlib.pyplot as plt <br>from matplotlib.animation import FuncAnimation</pre><p>The two main parts that we need to code arethe x-y-z coordinates of the plot given time and the animation of the visual. We will first work with the Lorenz attractor which has the following equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/0*iUQN34xTF00v28VU.png" /><figcaption>Lorenz Equations</figcaption></figure><p>Don’t click away now! While these equations may seem intimidating, you do not need to know what they mean to get nice animations. However, we do need to define these equations in Python.</p><pre>def Lorenz(xyz=[0, 1, 1.05], s=10, r=28, b=2.667, time=0.01):<br>    &quot;&quot;&quot;<br>    Parameters<br>    ----------<br>    xyz : array-like, shape (3,)<br>       Intial point<br>    s, r, b : float<br>       Parameters defining the Lorenz attractor.<br>    time: float<br>        The &#39;time&#39; step between each point<br>    Returns<br>    -------<br>    3 lists containing the x-coordinates, y-coordinates and z-coordinates<br>    respectively.<br>    &quot;&quot;&quot;<br>    #Intializing the list of points<br>    x, y, z = [xyz[0]], [xyz[1]], [xyz[2]]<br>    for i in range(1, 10000):<br>        #setting the current x,y,z cooridnate.<br>        current_x, current_y, current_z = x[-1], y[-1], z[-1]<br><br>        #Updating the list of points with the next value<br>        x.append(current_x + time * (s * (current_y - current_x)))<br>        y.append(current_y + time * (r * current_x - current_y - current_x * current_z))<br>        z.append(current_z + time * (current_x * current_y - b * current_z))<br>    return x, y, z </pre><p>Next we have to define two functions that will be used in the animation:</p><pre>def init():<br>    &#39;&#39;&#39;<br>    Sets thee canvas for blitting<br>    &#39;&#39;&#39;<br>    return ln<br><br>def update(i):<br>    &#39;&#39;&#39;<br>    Updates the animation<br>    &#39;&#39;&#39;<br>    ln.set_data([ x_values[:i], y_values[:i]])<br>    ln.set_3d_properties( z_values[:i] )<br>    return ln</pre><p>Finally we need the main code for the generation of the animation.</p><pre>fig = plt.figure(facecolor=&quot;black&quot;)<br>ax = fig.add_subplot(projection=&#39;3d&#39;)<br><br>x_values, y_values, z_values = Lorenz()<br>ln, = ax.plot(x_values, y_values, z_values)<br><br>ani = FuncAnimation(fig, <br>                    update,<br>                    frames=len(x_values), <br>                    init_func=init,<br>                    interval=.01,<br>                    )<br>plt.show()</pre><p>Which gives us the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Yj7oPXxRWLBkteyG5iHmqw.gif" /><figcaption>GIF of Lorenz Animation</figcaption></figure><p>If you are interested in creating your own animations with different attractors, <a href="https://www.3d-meier.de/tut19/Seite0.html">this</a> website has a list of the equations and basic visualizations of different attractors. Simply replace the lorenz function and equations with an attractor of your liking.</p><p><a href="https://github.com/Zackary111/Attractor">Here</a> you can find the repository to the code.</p><p><em>Zackary Nay is a full-time software developer working within the construction industry, where he implements artificial intelligence and other software to expedite repetitive tasks. In his free time, he likes to read and go backpacking.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d08921892d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intuition/strange-attractors-in-python-2d08921892d1">Strange Attractors in Python</a> was originally published in <a href="https://medium.com/intuition">Intuition</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Math Behind Gradient Descent]]></title>
            <link>https://znay854.medium.com/the-math-behind-gradient-descent-part-1-2-0e57c8430cb0?source=rss-66db740b91ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e57c8430cb0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Zackary Nay]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 19:23:05 GMT</pubDate>
            <atom:updated>2024-07-09T15:44:41.837Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*DFBbV7sSfHzmP0VT.png" /></figure><p>The following is a brief derivation of the batch gradient descent algorithm.</p><p>In <a href="https://medium.com/@z.nay854/a-friendly-approach-to-ai-part-1-1-ce2f61222aad">Part 1–1</a> I discussed the Perceptron algorithm, which took the predicted output of 1 or -1 to update the weights of the net input. There is a better way however. In this article I will go through the derivation of the gradient descent optimization algorithm.</p><p>An activation function, is a function that determines the output of a node based upon the inputs and weights. In our case lets define the activation function as the following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/0*lknVxZ2l5MiuTI_u" /></figure><p>Or, equivalently:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*CMIpCLHafomkMvv7" /></figure><p>This activation function is simply just the identity function, but it will be important that we get used to the activation functions as it will be a reucuring function in the series. Note that w and x are in this case vectors and we are taking the dot product, the output of which is the same as the predicted value of the equation discused in Part 1–1.</p><p>A cost functition is a function that measures the performance of a machine learning model. Lets now define the cost function that we would like to minimize:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/0*T_lItxOGY44ohaRb" /></figure><p>J(w) is the sum of squared errors between the true class label and the predicted value, with a inconsequential one-half in order to make then derivation a little cleaner. Ideally we would like to change w such that it approaches the global minimum of J(w). Hence, lets find the gradient with respect to the j-th weight:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*_wqINjtYzOKO79bU" /></figure><p>Then applying chain rule we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*ZHFcQbsGrJv6lV-Z" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*8qBbqbYzzglb6y86" /></figure><p>Finally, with some simplification we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/0*1y-pDQXlHtna9jIc" /></figure><p>Which is the exact same as the Perceptron algorithm! Thus, we can change the j-th weight by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*erqeuQbWHSt4G65e" /></figure><p>In conclusion, the derivation is not too difficult, and by minimizing the cost function we can see where the Perceptron algorithm comes from. The name batch gradient descent comes from us applying this gradient descent on all of the training set data.</p><p>If you would like to see the proof of convergence of the Perceptron algorithm or why the algorithm for non-seperable data, post a comment!</p><p><em>Zackary Nay is a full-time software developer working within the construction industry, where he implements artificial intelligence and other software to expedite repetitive tasks. In his free time, he likes to read and go backpacking.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e57c8430cb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>