Find top five similar image using cosine similarity

Viewed 265

I have a feature list of images with length n.

feature_list -> [array[img1], array[img2]....n] 

I can find top 5 using sklearn.neighbors.NearestNeighbors. by following

neighbors = NearestNeighbors(n_neighbors=5, algorithm='brute',metric='euclidean').fit(feature_list)
test_img_feature = extract_features('test.jpg', model_after_tuning)
distances, indices = neighbors.kneighbors([test_img_feature])

This is working fine. But I want to use cosine similarity instead of euclidean. so far I did the following ..

def calculate_similarity(vector1, vector2):
    sim_cos = 1-spatial.distance.cosine(vector1, vector2)
    return sim_cos

fea_vec_img1 = extract_features('./test.jpg', model_after_tuning)
fea_vec_img2 = extract_features('./test1.jpg', model_after_tuning)

calculate_similarity(fea_vec_img1 , fea_vec_img2)

Its working fine but I want to search top 5 from the whole feature_list which containing the whole data.

when I pass the following its getting error

calculate_similarity(feature_list, fea_vec_img2)

Is there any fit function of cosine similarity for whole feature_list like NearestNeighbors?

0 Answers
Related