tf.keras.losses.cosine_similarity
Stay organized with collections
Save and categorize content based on your preferences.
Computes the cosine similarity between labels and predictions.
View aliases
Main aliases
tf.losses.cosine_similarity
Compat aliases for migration
See
Migration guide for
more details.
`tf.compat.v1.keras.losses.cosine`, `tf.compat.v1.keras.losses.cosine_proximity`, `tf.compat.v1.keras.losses.cosine_similarity`, `tf.compat.v1.keras.metrics.cosine`, `tf.compat.v1.keras.metrics.cosine_proximity`
tf.keras.losses.cosine_similarity(
y_true, y_pred, axis=-1
)
Note that it is a number between -1 and 1. When it is a negative number
between -1 and 0, 0 indicates orthogonality and values closer to -1
indicate greater similarity. The values closer to 1 indicate greater
dissimilarity. This makes it usable as a loss function in a setting
where you try to maximize the proximity between predictions and
targets. If either y_true
or y_pred
is a zero vector, cosine
similarity will be 0 regardless of the proximity between predictions
and targets.
loss = -sum(l2_norm(y_true) * l2_norm(y_pred))
Standalone usage:
y_true = [[0., 1.], [1., 1.], [1., 1.]]
y_pred = [[1., 0.], [1., 1.], [-1., -1.]]
loss = tf.keras.losses.cosine_similarity(y_true, y_pred, axis=1)
loss.numpy()
array([-0., -0.999, 0.999], dtype=float32)
Args |
y_true
|
Tensor of true targets.
|
y_pred
|
Tensor of predicted targets.
|
axis
|
Axis along which to determine similarity.
|
Returns |
Cosine similarity tensor.
|
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates. Some content is licensed under the numpy license.
Last updated 2023-10-06 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2023-10-06 UTC."],[],[]]