Skip to content

Instantly share code, notes, and snippets.

@davidmezzetti
Last active January 24, 2020 00:24
Show Gist options
  • Save davidmezzetti/ac71f3268c161c71e3f6e07df32aa4e6 to your computer and use it in GitHub Desktop.
Save davidmezzetti/ac71f3268c161c71e3f6e07df32aa4e6 to your computer and use it in GitHub Desktop.
# Generate random data
x = np.random.rand(5, 5)
y = np.random.rand(1, 5)
print("x:", "\n", x)
print("y:", "\n", y)
# Calculate cosine similarity in NumPy
results = np_cosine_similarity(x, y)
# Get the index with highest cosine similarity (argsort sorts asc)
indices = np.argsort(np.squeeze(-results), axis=0)[:1]
# Print cosine similarity, best result and score
print("np:", "\n", results)
print(x[indices], results[indices])
# Calculate cosine similarity in TensorFlow
results = tf_cosine_similarity(x, y)
# Get the index of the highest cosine similarity (top_k sorts desc)
indices = tf.math.top_k(tf.squeeze(results), k=1).indices
# Print cosine similarity, best result and score
print("tf:", "\n", results.numpy())
print(x[indices.numpy()], tf.gather(results, indices).numpy())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment