Write Tensorflow Python code to convert a character array (text) into a one-hot…
- User
Write Tensorflow Python code to convert a character array (text) into a one-hot representation. Here is the current code that embeds the text into another representation: ### Vectorize the text
Before training, you need to convert the strings to a numerical representation.
The
tf.keras.layers.StringLookuplayer can convert each character into a numeric ID. It just needs the text to be split into tokens first.example_texts = ['abcdefg', 'xyz']
chars = tf.strings.unicode_split(example_texts, input_encoding='UTF-8') chars
Now create the
tf.keras.layers.StringLookuplayer:ids_from_chars = tf.keras.layers.StringLookup( vocabulary=list(vocab), mask_token=None)
It converts from tokens to character IDs:
ids = ids_from_chars(chars) ids
Since the goal of this tutorial is to generate text, it will also be important to invert this representation and recover human-readable strings from it. For this you can use
tf.keras.layers.StringLookup(..., invert=True).Note: Here instead of passing the original vocabulary generated with
sorted(set(text))use theget_vocabulary()method of thetf.keras.layers.StringLookuplayer so that the[UNK]tokens is set the same way.chars_from_ids = tf.keras.layers.StringLookup( vocabulary=ids_from_chars.get_vocabulary(), invert=True, mask_token=None)
This layer recovers the characters from the vectors of IDs, and returns them as a
tf.RaggedTensorof characters:chars = chars_from_ids(ids) chars
You can
tf.strings.reduce_jointo join the characters back into strings.tf.strings.reduce_join(chars, axis=-1).numpy()
def text_from_ids(ids): return tf.strings.reduce_join(chars_from_ids(ids), axis=-1)
- Assistant
import tensorflow as tf
def convert_to_one_hot(text): chars = tf.strings.unicode_split(text, input_encoding='UTF-8') ids_from_chars = tf.keras.layers.StringLookup( vocabulary=list(set(text)), mask_token=None)
ids = ids_from_chars(chars) chars_from_ids = tf.keras.layers.StringLookup( vocabulary=ids_from_chars.get_vocabulary(), invert=True, mask_token=None) chars = chars_from_ids(ids) one_hot = tf.one_hot(ids, len(set(text))) return one_hotexample_text = 'abcdefg' one_hot_representation = convert_to_one_hot(example_text) print(one_hot_representation)
- User
from the code you've given, how can I make the bit array fixed size? (len (vocab) = 128)
- Assistant
To make the bit array a fixed size, you can set the
depthparameter in thetf.one_hotfunction to the desired size (in this case, 128).Here's an updated version of the code with the bit array size fixed at 128:
import tensorflow as tf
def convert_to_one_hot(text): chars = tf.strings.unicode_split(text, input_encoding='UTF-8') ids_from_chars = tf.keras.layers.StringLookup( vocabulary=list(set(text)), mask_token=None)
ids = ids_from_chars(chars) chars_from_ids = tf.keras.layers.StringLookup( vocabulary=ids_from_chars.get_vocabulary(), invert=True, mask_token=None) chars = chars_from_ids(ids) one_hot = tf.one_hot(ids, depth=128) return one_hotexample_text = 'abcdefg' one_hot_representation = convert_to_one_hot(example_text) print(one_hot_representation)
In this code,
depth=128specifies the desired size of the one-hot encoded vectors. - User
Now convert the rest of the code: ### Create training examples and targets
Next divide the text into example sequences. Each input sequence will contain
seq_lengthcharacters from the text.For each input sequence, the corresponding targets contain the same length of text, except shifted one character to the right.
So break the text into chunks of
seq_length+1. For example, sayseq_lengthis 4 and our text is "Hello". The input sequence would be "Hell", and the target sequence "ello".To do this first use the
tf.data.Dataset.from_tensor_slicesfunction to convert the text vector into a stream of character indices.all_ids = ids_from_chars(tf.strings.unicode_split(text, 'UTF-8')) all_ids
- Assistant
Here's the updated code that converts the remaining part:
import tensorflow as tf def convert_to_one_hot(text): chars = tf.strings.unicode_split(text, input_encoding='UTF-8') ids_from_chars = tf.keras.layers.StringLookup( vocabulary=list(set(text)), mask_token=None) ids = ids_from_chars(chars) chars_from_ids = tf.keras.layers.StringLookup( vocabulary=ids_from_chars.get_vocabulary(), invert=True, mask_token=None) chars = chars_from_ids(ids) one_hot = tf.one_hot(ids, depth=128) return one_hot def split_input_target(sequence): input_text = sequence[:-1] target_text = sequence[1:] return input_text, target_text # Example text text = "Hello, TensorFlow!" # Convert text to one-hot representation one_hot_representation = convert_to_one_hot(text) # Create dataset of character indices ids_from_chars = tf.keras.layers.StringLookup( vocabulary=list(set(text)), mask_token=None) all_ids = ids_from_chars(tf.strings.unicode_split(text, 'UTF-8')) ids_dataset = tf.data.Dataset.from_tensor_slices(all_ids) # Define sequence length seq_length = 4 # Split text into sequences sequences = ids_dataset.batch(seq_length+1, drop_remainder=True) # Split sequences into input and target dataset = sequences.map(split_input_target) # Print input and target sequences for input_example, target_example in dataset.take(1): print("Input :", chars_from_ids(input_example).numpy().decode('utf-8')) print("Target:", chars_from_ids(target_example).numpy().decode('utf-8'))