Skip to content

bin

BinLayer ¤

BinLayer(
    condition_operators,
    bin_values,
    bin_labels,
    default_label,
    name=None,
    input_dtype=None,
    output_dtype=None,
    **kwargs
)

Bases: BaseLayer

Performs a binning operation on a given input tensor.

The binning operation is performed by comparing the input tensor to a list of values using a list of operators. The bin label corresponding to the first condition that evaluates to True is returned.

If no conditions evaluate to True, the default label is returned.

Initializes the BinLayer 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
condition_operators List[str]

List of operators to use in the if statement. Can be one of: - "eq": Equal to - "neq": Not equal to - "lt": Less than - "leq": Less than or equal to - "gt": Greater than - "geq": Greater than or equal to

required
bin_values List[float]

List of values to compare the input tensor to. Must be the same length as condition_operators.

required
bin_labels List[Union[float, int, str]]

List of labels to use for each bin. Must be the same length as condition_operators.

required
default_label Union[float, int, str]

Label to use if none of the conditions are met.

required
Source code in src/kamae/tensorflow/layers/bin.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def __init__(
    self,
    condition_operators: List[str],
    bin_values: List[float],
    bin_labels: List[Union[float, int, str]],
    default_label: Union[float, int, str],
    name: Optional[str] = None,
    input_dtype: Optional[str] = None,
    output_dtype: Optional[str] = None,
    **kwargs: Any,
) -> None:
    """
    Initializes the BinLayer 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 condition_operators: List of operators to use in the if statement.
    Can be one of:
        - "eq": Equal to
        - "neq": Not equal to
        - "lt": Less than
        - "leq": Less than or equal to
        - "gt": Greater than
        - "geq": Greater than or equal to
    :param bin_values: List of values to compare the input tensor to. Must be the
    same length as condition_operators.
    :param bin_labels: List of labels to use for each bin. Must be the same length
    as condition_operators.
    :param default_label: Label to use if none of the conditions are met.
    """
    super().__init__(
        name=name, input_dtype=input_dtype, output_dtype=output_dtype, **kwargs
    )
    if len(condition_operators) != len(bin_labels) != len(bin_values):
        raise ValueError(
            f"""condition_operators, bin_labels and bin_values must be the same
            length. Got lengths: {len(condition_operators)}, {len(bin_labels)},
            {len(bin_values)}"""
        )
    self.condition_operators = condition_operators
    self.bin_values = bin_values
    self.bin_labels = bin_labels
    self.default_label = default_label

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)

Performs a binning operation on a given input tensor.

Creates a string tensor of the same shape as the input tensor, where each element is the label of the bin that the corresponding element in the input tensor belongs to. The bin labels are determined by successively applying the condition operators to the input tensor, and returning the label of the first bin that the element belongs to.

Decorated with @enforce_single_tensor_input to ensure that the input is a single tensor. Raises an error if multiple tensors are passed in as an iterable.

Parameters:

Name Type Description Default
inputs Tensor

Tensor to perform the binning operation on.

required

Returns:

Type Description
Tensor

The binned input tensor.

Source code in src/kamae/tensorflow/layers/bin.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
@enforce_single_tensor_input
def _call(self, inputs: Tensor, **kwargs: Any) -> Tensor:
    """
    Performs a binning operation on a given input tensor.

    Creates a string tensor of the same shape as the input tensor, where each
    element is the label of the bin that the corresponding element in the input
    tensor belongs to. The bin labels are determined by successively applying
    the condition operators to the input tensor, and returning the label of the
    first bin that the element belongs to.

    Decorated with `@enforce_single_tensor_input` to ensure that the input
    is a single tensor. Raises an error if multiple tensors are passed
    in as an iterable.

    :param inputs: Tensor to perform the binning operation on.
    :returns: The binned input tensor.
    """
    cond_op_fns = [get_condition_operator(op) for op in self.condition_operators]

    # Build default output tensor
    outputs = tf.constant(self.default_label)

    # Loop through the conditions.
    # Reverse the list of conditions so that we start from the last condition
    # and work backwards. This ensures that the first condition that is met
    # is the one that is used.
    conds = zip(cond_op_fns[::-1], self.bin_values[::-1], self.bin_labels[::-1])

    for cond_op, value, label in conds:
        # Ensure that the inputs and value are compatible dtypes
        cast_input, cast_value = self._force_cast_to_compatible_numeric_type(
            inputs, value
        )
        outputs = tf.where(
            cond_op(
                cast_input,
                cast_value,
            ),
            tf.constant(label),
            outputs,
        )

    return outputs

get_config ¤

get_config()

Gets the configuration of the Bin 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/bin.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def get_config(self) -> Dict[str, Any]:
    """
    Gets the configuration of the Bin layer.
    Used for saving and loading from a model.

    :returns: Dictionary of the configuration of the layer.
    """
    config = super().get_config()
    config.update(
        {
            "condition_operators": self.condition_operators,
            "bin_values": self.bin_values,
            "bin_labels": self.bin_labels,
            "default_label": self.default_label,
        }
    )
    return config