knn with custom distance function in R
<p>I want to apply k nearest neighbour with a custom distance function. I have not found a way to pass this function using packages like FNN or class. Is there a way to pass a function or distance matrix to an existing knn algorithm in some R package or do I have to write it from scratch?</p>

<h2>Background</h2>

<p>To elaborate on my problem: my data includes columns for</p>

<ul>
<li>start latitude</li>
<li>start longitude</li>
<li>start country</li>
<li>end latitude</li>
<li>end longitude</li>
<li>end country</li>
<li>start+end country</li>
<li>means of transportation</li>
<li>distance</li>
<li>price</li>
</ul>

<p>and I want to estimate the price based on the other factors. The distance function needs to include the haversine distance to measure the similarity of start and end points' latitude and longitude, so I cannot use a built-in distance like euclidean or minkowski.</p>

<h2>Open for Python suggestions</h2>

<p>If somebody believes that for some reason this would be much easier to do in Python (provided the same programming skills in both languages) using some fancy package, I am also very open to additional information about this.</p>

<p>After searching a bit, I found a package called KODAMA that <strong>does cross validation</strong> 10 fold for instance and seems to have a knn prediction function <code>knn.predict</code> working with a distance matrix calculated separately by the <code>knn.dist</code> function.</p>

<p>It appears that the output of the <code>knn.dist</code> function is nothing but a standard distance matrix with symmetric values and diagonal set to zero, of class Matrix.
So we can create one separately, those lines of code are equivalent:</p>

<pre><code>kdist &lt;- KODAMA::knn.dist(x)
kdist &lt;- dist(x, upper=T, diag=T) %&gt;% as.matrix # it also works
knn.predict(train, test, y ,kdist, k=3, agg.meth="majority")
</code></pre>

<p>You might try it with your custom distance matrix. 
hope it helps. </p>

python machine-learning distance knn