Learning how to define a custom metric in sklearn so it can be used with KDTree which in turn for correlation function
In [23]:
from sklearn.neighbors import *
import numpy as np
import math as m
In [10]:
In [ ]:
In [2]:
dist = DistanceMetric.get_metric('euclidean')
X = [[0, 1, 2],[3, 4, 5]]
dist.pairwise(X)
Out[2]:
In [3]:
dist.dist_to_rdist(3)
Out[3]:
In [26]:
def myDistance(x,y):
return np.sqrt(x**2+y**2)
In [27]:
distc=DistanceMetric.get_metric("pyfunc",func=myDistance)
In [28]:
distc.pairwise(X)
In [ ]:
In [41]:
class LCDMDistance(DistanceMetric):
"""LCDM Distance metric
D(x, y) = \sqrt{ x^2+y^2-2xycos(theta) }
"""
def __init__(self):
return None
def dist(x,y):
return np.sqrt(x**2+y**2-2*x*y)
def pairwise(x):
return dist(x,x)
def rdist_to_dist(self, rdist):
return np.sqrt(rdist)
def dist_to_rdist(self, dist):
return dist ** 2
In [48]:
distlcdm=LCDMDistance.pairwise(X)
In [47]:
distlcdm.pairwise(X)
In [62]:
def dist(x,y):
return np.sqrt(np.sum(x**2+y**2-2*x*y))
In [63]:
x=[1,2,3]
In [51]:
KDTree.valid_metrics
Out[51]:
In [54]:
KDTree.data
Out[54]:
In [56]:
np.random.seed(0)
X = np.random.random((30, 3))
r = np.linspace(0, 1, 5)
tree = KDTree(X,metric="pyfunc",func=dist)
tree.two_point_correlation(X, r)
In [58]:
BallTree.valid_metrics
Out[58]:
In [64]:
np.random.seed(0)
X = np.random.random((30, 3))
r = np.linspace(0, 1, 5)
tree = BallTree(X,metric="pyfunc",func=dist)
tree.two_point_correlation(X, r)
Out[64]:
In [ ]: