After running this python code: import tensorflow as tf from keras.layers import…
- User
After running this python code: import tensorflow as tf from keras.layers import TextVectorization, Embedding, LayerNormalization, Dropout, Dense, MultiHeadAttention, GlobalAveragePooling1D, Input from keras.models import Sequential, Model from keras import Sequential
Standard imports for saving tokenizer configuration
import json
Define some constants
MAX_TOKENS = 250 # Size of the vocabulary EMBED_DIM = 64 # Embedding size NUM_HEADS = 4 # Number of attention heads FF_DIM = 64 # Hidden layer size in feed forward network MAX_LEN = 40 # Max length of sequence BATCH_SIZE = 64 # Training batch size
Prepare your dataset text file
text_file_path = "dataset.txt"
Define the text vectorization layer with padding
vectorize_layer = TextVectorization( max_tokens=MAX_TOKENS, output_mode="int", output_sequence_length=MAX_LEN, pad_to_max_tokens=True )
Load the text data and adapt the vectorization layer
with open(text_file_path, "r", encoding="utf-8") as f: lines = f.readlines() vectorize_layer.adapt(lines)
Token and position embedding as a custom layer
class TokenAndPositionEmbedding(tf.keras.layers.Layer): def init(self, maxlen, vocab_size, embed_dim): super().init() self.token_emb = Embedding(input_dim=vocab_size, output_dim=embed_dim) self.pos_emb = Embedding(input_dim=maxlen, output_dim=embed_dim)
def call(self, x): maxlen = tf.shape(x)[-1] positions = tf.range(start=0, limit=maxlen, delta=1) positions = self.pos_emb(positions) x = self.token_emb(x) return x + positionsDefine the Transformer block as a function
def transformer_encoder(inputs, embed_dim, num_heads, ff_dim, rate=0.1): # Reshape the input tensor inputs = tf.expand_dims(inputs, axis=2)
# Multi-headed self-attention attention_output = MultiHeadAttention( num_heads=num_heads, key_dim=embed_dim )(inputs, inputs) attention_output = Dropout(rate)(attention_output) attention_output = LayerNormalization(epsilon=1e-6)(inputs + attention_output) # Feed-forward layer ff_output = Sequential( [ Dense(ff_dim, activation="relu"), Dense(embed_dim), ] )(attention_output) ff_output = Dropout(rate)(ff_output) ff_output = LayerNormalization(epsilon=1e-6)(attention_output + ff_output) # Reshape the output tensor ff_output = tf.squeeze(ff_output, axis=2) return ff_outputCreate the Transformer model
def create_transformer_model(maxlen, vocab_size, embed_dim, num_heads, ff_dim): inputs = Input(shape=(maxlen,)) embedding_layer = TokenAndPositionEmbedding(maxlen, vocab_size, embed_dim)(inputs) transformer_block_output = transformer_encoder(embedding_layer, embed_dim, num_heads, ff_dim) outputs = GlobalAveragePooling1D()(transformer_block_output) outputs = Dropout(0.1)(outputs) outputs = Dense(vocab_size, activation="softmax")(outputs) # Assuming next-token prediction model = Model(inputs=inputs, outputs=outputs) return model
- Assistant
- User
After doing all the things you wrote, i got this shape mismatch error: ValueError: Input 0 of layer "model" is incompatible with the layer: expected shape=(None, 40), found shape=(None, 39)
- Assistant
The error message you're encountering indicates that there is a shape mismatch when feeding inputs into the model. Specifically, the model expects inputs of shape
(None, 40), which corresponds to sequences of length 40, but it is receiving inputs of shape(None, 39), which corresponds to sequences of length 39.This problem is caused by the way you're splitting the inputs and labels in the function. You are correctly creating input sequences by excluding the last token and labels by excluding the first token, which effectively reduces the sequence length by 1.
- User
- Assistant