Friday, 30 April 2021

Computing cosine similarity between two tensor vectors in lambda layer?

Here's the basic code,

def euclidean_distance(vects):
    x, y = vects
    sum_square = K.sum(K.square(x - y), axis=1, keepdims=True)
    return K.sqrt(K.maximum(sum_square, K.epsilon()))


def eucl_dist_output_shape(shapes):
    shape1, shape2 = shapes
    return (shape1[0], 1)


# measure the similarity of the two vector outputs
output = Lambda(euclidean_distance, name="output_layer", output_shape=eucl_dist_output_shape)([output_a, output_b])

# specify the inputs and output of the model
model = Model([input_a, input_b], output)

I want to use cosine similarity (0 to 1 scale) instead of euclidean distance for measure the similiart between two vectors, I tried to use cosine_similarity from scikit-learn but it didn't work.

So, we need to use keras.backend to build it? Can someone tell me how do I do it?



from Computing cosine similarity between two tensor vectors in lambda layer?

No comments:

Post a Comment