encode_ternary_array¶
- keras_mml.utils.array.encoding.encode_ternary_array(x)[source]¶
Encodes a ternary array into a more space efficient format.
For a given ternary matrix, which consists of only the elements
0,1, and-1, we convert the individual elements into bit sequences. Specifically,the most common element becomes
0;the second most common element becomes
10; andthe least common element becomes
11.
We then convert these bit sequences into bytes. The first three to four bits describes which elements were converted to
0and10respectively.0will be represented by0;1will be represented by10; and-1will be represented by11.
This function will prepend this information in front of the bit sequences, and then return them as bytes.
- Parameters:
x (
ndarray) – Ternary array to encode.- Returns:
Tuple[Tuple[int,...],bytes] – A tuple. The first element is the shape of the array. The second element is the encoded representation of the array.
Examples
>>> x = np.array([1, -1, 1, 0, -1, 1]) >>> shape, encoded = encode_ternary_array(x) >>> shape (6,) >>> encoded b'\xb4\xe0'
>>> x = np.array([[0, 1, -1], [-1, 0, 0]]) >>> shape, encoded = encode_ternary_array(x) >>> shape (2, 3) >>> encoded b'n\x80'
>>> x = np.array([[[0, 1, -1], [-1, 1, 0]], [[1, 0, 0], [0, -1, 1]]]) >>> shape, encoded = encode_ternary_array(x) >>> shape (2, 2, 3) >>> encoded b'K\xe48'
>>> x = np.array([[[0, 1, -1], [-1, 1, 0]], [[1, -1, 0], [0, -1, 1]]]) >>> shape, encoded = encode_ternary_array(x) >>> shape (2, 2, 3) >>> encoded b'K\xe5\x9c'