<p>I'm sorry, I think I may have over-thought this whole thing a bit.  Consider the more general derivation from before, for any kernel K and the Euclidean distance (I'm ignoring the constants on the front of f(x) for convenience.  You can rederive with the constants if you like):</p>

<p>∇f(x) = ∑ K'(∥ x - x_i ∥) d/dx(∥ x - x_i ∥).<br>
= ∑ K'(∥ x - x_i ∥) d/dx((∥ x - x_i ∥^2)^1/2)<br>
= ∑ K'(∥ x - x_i ∥) (1/2 (∥ x - x_i ∥^2)^(-1/2)) (x - x_i)<br>
= ∑ K'(∥ x - x_i ∥) (1 / (2 ∥ x - x_i ∥^2)) (x - x_i)</p>

<p>Now plug in the Gaussian kernel:</p>

<p>K(∥ x - x_i ∥) = exp(-∥ x - x_i ∥^2 / b^2)</p>

<p>which gives by the chain rule</p>

<p>K'(∥ x - x_i ∥) = exp(-∥ x - x_i ∥^2 / b^2) * -b^-2 * 2 (∥ x - x_i ∥^2)</p>

<p>Note that last term, 2 (∥ x - x_i ∥^2).  When we plug that into ∇f(x) above, it cancels with the second term and we get the familiar</p>

<p>∇f(x) = K'(∥ x - x_i ∥) (x - x_i)</p>

<p>So there isn't actually a need for knowing whether or not the kernel uses a squared distance.  We can use this calculation always:</p>

<p>∇f(x) = ∑ K'(∥ x - x_i ∥) (1 / (2 ∥ x - x_i ∥^2)) (x - x_i)</p>

<p>and if the kernel <em>does</em> use the squared distance, then there will exist the term 2 (∥ x - x_i ∥^2) in its gradient.  The <code>Gradient()</code> function should be inlined with the rest of the expression, so a smart compiler should be able to cancel out the 2 (∥ x - x_i ∥^2) and the (1 / (2 ∥ x - x_i ∥^2)).  And even if not, this is a few floating point calculations and not an unnecessary distance calculation (because you need to calculate ∥ x - x_i ∥ no matter what), so I don't think it will be incredibly computationally costly.  I'd be interested in comparing the runtime of the more general implementation with your Gaussian-specific implementation.  Ideally, the speed should be the same.</p>

<p>Does that make sense?  I'm sorry for the confusion.</p>

<p style="font-size:small;-webkit-text-size-adjust:none;color:#666;">&mdash;<br>Reply to this email directly or <a href="https://github.com/mlpack/mlpack/pull/388#issuecomment-75608745">view it on GitHub</a>.<img alt="" height="1" src="https://github.com/notifications/beacon/AJ4bFIdrZWwoUhgONk9kJMhfjYqdQxEwks5nu3FagaJpZM4DTzb1.gif" width="1" /></p>
<div itemscope itemtype="http://schema.org/EmailMessage">
  <div itemprop="action" itemscope itemtype="http://schema.org/ViewAction">
    <link itemprop="url" href="https://github.com/mlpack/mlpack/pull/388#issuecomment-75608745"></link>
    <meta itemprop="name" content="View Pull Request"></meta>
  </div>
  <meta itemprop="description" content="View this Pull Request on GitHub"></meta>
</div>