Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ethen8181
GitHub Repository: ethen8181/machine-learning
Path: blob/master/python/cython/pairwise2.pyx
2574 views
1
# cython: boundscheck = False
2
# cython: wraparound = False
3
4
# we can turn off the checks globally by defining them at the top
5
cimport cython
6
import numpy as np
7
from libc.math cimport sqrt
8
9
cdef inline double euclidean_distance(double[:, :] X, int i1, int i2):
10
cdef int j
11
cdef double tmp, d = 0
12
13
for j in range(X.shape[1]):
14
tmp = X[i1, j] - X[i2, j]
15
d += tmp * tmp
16
17
return sqrt(d)
18
19
20
def pairwise2(double[:, :] X, metric = 'euclidean'):
21
if metric == 'euclidean':
22
dist_func = euclidean_distance
23
else:
24
raise ValueError("unrecognized metric")
25
26
cdef double dist
27
cdef int i, j, n_samples
28
n_samples = X.shape[0]
29
cdef double[:, :] D = np.zeros((n_samples, n_samples), dtype = np.float64)
30
31
for i in range(n_samples):
32
for j in range(i + 1, n_samples):
33
# do not create extra numpy array by directly slicing on X
34
dist = dist_func(X, i, j)
35
D[i, j] = dist
36
D[j, i] = dist
37
38
return D
39
40
41