使用 Keras 3
ops
api,这个标准化函数的 Keras 3 版本是什么?
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)
def ieee754_to_uint8(x, axis=-1):
"""
Normalize a tensor using IEEE 754 logic and map it to uint8 values using Keras 3 ops.
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 along the given axis
m = ops.max(ops.abs(x), axis=axis, keepdims=True)
m = ops.where(m == 0, ops.ones_like(m), m) # Prevent division by zero
# Perform normalization
y = (2**7 - 1 * ops.cast(x > 0, dtype="float32")) * x / m
# Convert to uint8
y = ops.cast(ops.round(y + 128), dtype="uint8")
return ydef ieee754_to_uint8(x, axis=-1):
"""
Normalize a tensor using IEEE 754 logic and map it to uint8 values using Keras 3 ops.
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 along the given axis
m = ops.max(ops.abs(x), axis=axis, keepdims=True)
m = ops.where(m == 0, ops.ones_like(m), m) # Prevent division by zero
# Perform normalization
y = (2**7 - 1 * ops.cast(x > 0, dtype="float32")) * x / m
# Convert to uint8
y = ops.cast(ops.round(y + 128), dtype="uint8")
return y