Skip to content

cosine_similarity

CosineSimilarityLayer ¤

CosineSimilarityLayer(
    name=None,
    input_dtype=None,
    output_dtype=None,
    axis=-1,
    keepdims=False,
    **kwargs
)

Bases: BaseLayer

Computes the cosine similarity between two input tensors.

Initializes the CosineSimilarityLayer layer

Parameters:

Name Type Description Default
name Optional[str]

Name of the layer, defaults to None.

None
input_dtype Optional[str]

The dtype to cast the input to. Defaults to None.

None
output_dtype Optional[str]

The dtype to cast the output to. Defaults to None.

None
axis int

The axis along which to compute the cosine similarity. Defaults to -1.

-1
keepdims bool

Whether to keep the shape of the input tensor. Defaults to False.

False
Source code in src/kamae/tensorflow/layers/cosine_similarity.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def __init__(
    self,
    name: Optional[str] = None,
    input_dtype: Optional[str] = None,
    output_dtype: Optional[str] = None,
    axis: int = -1,
    keepdims: bool = False,
    **kwargs: Any,
) -> None:
    """
    Initializes the CosineSimilarityLayer layer

    :param name: Name of the layer, defaults to `None`.
    :param input_dtype: The dtype to cast the input to. Defaults to `None`.
    :param output_dtype: The dtype to cast the output to. Defaults to `None`.
    :param axis: The axis along which to compute the cosine similarity. Defaults to
    `-1`.
    :param keepdims: Whether to keep the shape of the input tensor. Defaults to
    `False`.
    """
    super().__init__(
        name=name, input_dtype=input_dtype, output_dtype=output_dtype, **kwargs
    )
    self.axis = axis
    self.keepdims = keepdims

compatible_dtypes property ¤

compatible_dtypes

Returns the compatible dtypes of the layer.

Returns:

Type Description
Optional[List[DType]]

The compatible dtypes of the layer.

_call ¤

_call(inputs, **kwargs)

Computes the cosine similarity between two input tensors. If keepdims is True, the shape is retained. Otherwise, the shape is reduced along the specified axis.

Decorated with @enforce_multiple_tensor_input to ensure that the input is an iterable of tensors. Raises an error if a single tensor is passed.

After decoration, we check the length of the inputs to ensure we have the right number of input tensors.

Parameters:

Name Type Description Default
inputs Iterable[Tensor]

List of two tensors to compute the cosine similarity between.

required

Returns:

Type Description
Tensor

The tensor resulting from the cosine similarity.

Source code in src/kamae/tensorflow/layers/cosine_similarity.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
@enforce_multiple_tensor_input
def _call(self, inputs: Iterable[Tensor], **kwargs: Any) -> Tensor:
    """
    Computes the cosine similarity between two input tensors. If `keepdims` is
    `True`, the shape is retained. Otherwise, the shape is reduced along the
    specified axis.

    Decorated with @enforce_multiple_tensor_input to ensure that the input
    is an iterable of tensors. Raises an error if a single tensor is passed.

    After decoration, we check the length of the inputs to ensure we have the right
    number of input tensors.

    :param inputs: List of two tensors to compute the cosine similarity between.
    :returns: The tensor resulting from the cosine similarity.
    """
    if len(inputs) != 2:
        raise ValueError(
            f"Expected 2 inputs, received {len(inputs)} inputs instead."
        )
    x = tf.nn.l2_normalize(inputs[0], axis=self.axis)
    y = tf.nn.l2_normalize(inputs[1], axis=self.axis)

    return tf.reduce_sum(tf.multiply(x, y), axis=self.axis, keepdims=self.keepdims)

get_config ¤

get_config()

Gets the configuration of the CosineSimilarity layer. Used for saving and loading from a model.

Returns:

Type Description
Dict[str, Any]

Dictionary of the configuration of the layer.

Source code in src/kamae/tensorflow/layers/cosine_similarity.py
 99
100
101
102
103
104
105
106
107
108
def get_config(self) -> Dict[str, Any]:
    """
    Gets the configuration of the CosineSimilarity layer.
    Used for saving and loading from a model.

    :returns: Dictionary of the configuration of the layer.
    """
    config = super().get_config()
    config.update({"axis": self.axis, "keepdims": self.keepdims})
    return config