Path: blob/master/python/cython/pairwise2.pyx
2574 views
# cython: boundscheck = False1# cython: wraparound = False23# we can turn off the checks globally by defining them at the top4cimport cython5import numpy as np6from libc.math cimport sqrt78cdef inline double euclidean_distance(double[:, :] X, int i1, int i2):9cdef int j10cdef double tmp, d = 01112for j in range(X.shape[1]):13tmp = X[i1, j] - X[i2, j]14d += tmp * tmp1516return sqrt(d)171819def pairwise2(double[:, :] X, metric = 'euclidean'):20if metric == 'euclidean':21dist_func = euclidean_distance22else:23raise ValueError("unrecognized metric")2425cdef double dist26cdef int i, j, n_samples27n_samples = X.shape[0]28cdef double[:, :] D = np.zeros((n_samples, n_samples), dtype = np.float64)2930for i in range(n_samples):31for j in range(i + 1, n_samples):32# do not create extra numpy array by directly slicing on X33dist = dist_func(X, i, j)34D[i, j] = dist35D[j, i] = dist3637return D38394041