0

I need to calculate the cosine similarity between X and every element in the array Y. I'm unsure how to achieve this using numpy, ie, how to perform an operation on every element of a multi-dimensional array. Can you point me in the right direction?

x = np.array([234,112,89], dtype='uint8') # this is a pixel colour from an image
y = cv2.imread('./myimg.png') # y is a multi-dimensional array
res = np.zeroes_like(y, dtype='int32')

x32 = x.astype('int32') # allow for negative values? Do you think this is the correct data type as cosine similarity is given as a float value between -1 and 1
y32 = y.astype('int32')

# Now to calculate the cosine similarity of x to every pixel/element in array y
# Is there a numpy way to perform the below operation?
for c in range(0,y.shape[1],1):
    for r in range(0,y.shape[0],1):
        res[r,c] = spatial.distance.cosine(y32[r,c].flatten(), x32.flatten())
sazr
  • 23,396
  • 63
  • 179
  • 330

0 Answers0