Take two matrices, arr1, arr2 of size mxn and pxn respectively. I'm trying to find the cosine distance of their respected rows as a mxp matrix. Essentially I want to take the the pairwise dot product of the rows, then divide by the outer product of the norms of each rows.
import numpy as np
def cosine_distance(arr1, arr2):
numerator = np.dot(arr1, arr2.T)
denominator = np.outer(
np.sqrt(np.square(arr1).sum(1)),
np.sqrt(np.square(arr2).sum(1)))
return np.nan_to_num(np.divide(numerator, denominator))
I Think this should be returning an mxn matrix with entries in [-1.0, 1.0] but for some reason I'm getting values out of that interval. I'm thinking that my one of these numpy functions is doing something other than what I think it does.