Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

fastest way to compute pair wise distances python

#my_cython.pyx
import numpy as np
cimport numpy as np
import cython

cdef extern from "math.h":
    double abs(double t)

@cython.wraparound(False)
@cython.boundscheck(False)
def pairwise_distance(np.ndarray[np.double_t, ndim=1] r):
    cdef int i, j, c, size
    cdef np.ndarray[np.double_t, ndim=1] ans
    size = sum(range(1, r.shape[0]+1))
    ans = np.empty(size, dtype=r.dtype)
    c = -1
    for i in range(r.shape[0]):
        for j in range(i, r.shape[0]):
            c += 1
            ans[c] = abs(r[i] - r[j])
    return ans

# main.py
import numpy as np
import random

import pyximport; pyximport.install()
from my_cython import pairwise_distance

r = np.array([random.randrange(1, 1000) for _ in range(0, 1000)], dtype=float)

pairwise_distance(r)
 
Comment

fastest way to compute pair wise distances python

import numpy as np
import random
import sklearn.metrics.pairwise
import scipy.spatial.distance

r = np.array([random.randrange(1, 1000) for _ in range(0, 1000)])
c = r[:, None]

def option1(r):
    dists = np.abs(r - r[:, None])

def option2(r):
    dists = scipy.spatial.distance.pdist(r, 'cityblock')

def option3(r):
    dists = sklearn.metrics.pairwise.manhattan_distances(r)

In [36]: timeit option1(r)
100 loops, best of 3: 5.31 ms per loop

In [37]: timeit option2(c)
1000 loops, best of 3: 1.84 ms per loop

In [38]: timeit option3(c)
100 loops, best of 3: 11.5 ms per loop
Comment

PREVIOUS NEXT
Code Example
Python :: bad request 400 heroku app 
Python :: python selenium check if browser is open 
Python :: python walrus operator 
Python :: how to extract keys from dictreader python 
Python :: how to set class attributes with kwargs python 
Python :: Using replace() method to remove newlines from a string 
Python :: google scikit learn decision tree 
Python :: python switch item 
Python :: variable bound to a set python 
Python :: lambda example python 
Python :: Run a Flask API from CMD 
Python :: clear terminal in python 
Python :: python remove multiple element from list by index 
Python :: rest plus 
Python :: binary search tree python 
Python :: python remove first element of list 
Python :: come fare aprire una pagina web python 
Python :: what is tkinter in python 
Python :: np evenly spaced array 
Python :: Check instance has an attribute in python 
Python :: how to add some thing in python list 
Python :: .defaultdict 
Python :: flask run development mode 
Python :: Selenium get response body python 
Python :: how to round a number up in python 
Python :: pandas pull value from column 
Python :: df iloc 
Python :: name columns pandas 
Python :: format numbers in column to percentage in python 
Python :: python observer pattern 
ADD CONTENT
Topic
Content
Source link
Name
3+1 =