Code: Select all
def ieee754_to_uint8(x, axis=-1):
"""
Normalize a tensor using IEEE 754 logic and map it to uint8 values.
Args:
x (tensor): A Keras tensor of shape (batch_size, seq_len).
axis (int): Axis along which to normalize.
Returns:
A Keras tensor with dtype uint8, returning the same shape as input x.
"""
# Find the maximum absolute value in x
m = np.max(np.abs(x), axis=axis, keepdims=True)
m[m==0] = 1
y = (2**7 - 1 * (x > 0)) * x / m
return (y.astype(int) + 128).astype(np.uint8)