import numpy as np import tensorflow as tf from tensorflow.keras.models import Model…
- User
import numpy as np import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, LSTM, Bidirectional, GRU, Concatenate, Dot, Attention, Dense,Embedding,Activation from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences
Define hyperparameters
max_sequence_length = 100 embedding_dim = 100 latent_dim = 256
Load train, validate, and test data from text files
with open('D:/PHD Papers/scientific translation/Technical/Dataset/NewDataset23-11/EngArbPreprocessTrain.txt', 'r', encoding='utf-8') as f: train_data = f.readlines() with open('D:/PHD Papers/scientific translation/Technical/Dataset/NewDataset23-11/EngArbPreprocessTest.txt', 'r', encoding='utf-8') as f: test_data = f.readlines()
Extract English and Arabic sentences from data
english_sentences_train = [] arabic_sentences_train = []
english_test = [] arabic_test = []
for line in train_data: english, arabic = line.strip().split('\t') english_sentences_train.append(english) arabic_sentences_train.append(arabic)
for line in test_data: english, arabic = line.strip().split('\t') english_test.append(english) arabic_test.append(arabic)
Tokenize sentences and convert them into numerical representations
tokenizer_en = Tokenizer() tokenizer_en.fit_on_texts(english_sentences_train) train_data_en = tokenizer_en.texts_to_sequences(english_sentences_train) train_data_en = pad_sequences(train_data_en, maxlen=max_sequence_length, padding='post', truncating='post') tokenizer_ar = Tokenizer() tokenizer_ar.fit_on_texts(arabic_sentences_train) train_data_ar = tokenizer_ar.texts_to_sequences(arabic_sentences_train) train_data_ar = pad_sequences(train_data_ar, maxlen=max_sequence_length, padding='post', truncating='post')
Define encoder inputs and BiLSTM layer
encoder_inputs = Input(shape=(max_sequence_length,)) encoder_embedding = Embedding(len(tokenizer_en.word_index) + 1, embedding_dim)(encoder_inputs) encoder_lstm, _, _ = LSTM(latent_dim, return_sequences=True, return_state=True)(encoder_embedding) encoder_lstm = Dense(latent_dim)(encoder_lstm[0])
Define decoder inputs and BiGRU layer
decoder_inputs = Input(shape=(max_sequence_length,)) decoder_embedding = Embedding(len(tokenizer_ar.word_index) + 1, embedding_dim)(decoder_inputs) decoder_lstm = Bidirectional(GRU(latent_dim, return_sequences=True, return_state=True))(decoder_embedding)
Apply Attention mechanism
#attention = Dot(axes=[2, 2])([decoder_lstm, encoder_lstm]) attention = Dot(axes=[2, 2])([decoder_lstm, tf.repeat(tf.expand_dims(encoder_lstm, axis=2), tf.shape(decoder_lstm)[2], axis=2)]) attention = Activation('softmax')(attention) context = Dot(axes=[2, 1])([attention, encoder_lstm]) decoder_combined_context = Concatenate(axis=-1)([context, tf.repeat(tf.expand_dims(decoder_lstm[0], axis=1), tf.shape(context)[1], axis=1)])
- Assistant
- User
Traceback (most recent call last): File "D:\PHD Papers\scientific translation\GPT\BiLSTM witth Attention\GRU -BiRUattention.py", line 60, in attention = Dot(axes=[2, 2])([decoder_lstm, tf.repeat(tf.expand_dims(encoder_lstm, axis=2), tf.shape(decoder_lstm)[2], axis=2)]) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\util\traceback_utils.py", line 153, in error_handler raise e.with_traceback(filtered_tb) from None File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\layers\core\tf_op_layer.py", line 119, in handle return TFOpLambda(op)(*args, **kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None ValueError: Exception encountered when calling layer "tf.shape" (type TFOpLambda).
Shapes must be equal rank, but are 3 and 2 From merging shape 0 with other shapes. for '{{node tf.shape/Shape/packed}} = Pack[N=3, T=DT_FLOAT, axis=0](Placeholder, Placeholder_1, Placeholder_2)' with input shapes: [?,100,512], [?,256], [?,256].
Call arguments received by layer "tf.shape" (type TFOpLambda): • input=['tf.Tensor(shape=(None, 100, 512), dtype=float32)', 'tf.Tensor(shape=(None, 256), dtype=float32)', 'tf.Tensor(shape=(None, 256), dtype=float32)'] • out_type=<dtype: 'int32'> • name=None
- Assistant
The error message suggests that there is a shape mismatch when calling the
tf.shapefunction within theDotlayer. It seems that the shapes of the input tensors to theDotlayer are not compatible.To fix this issue, you can revise the line where the attention is computed. Instead of using
tf.repeatandtf.expand_dimsto match the shapes ofdecoder_lstmandencoder_lstm, you can use thetf.keras.backend.expand_dimsfunction andtf.keras.backend.repeat_elementsfunction.Here's an updated version of the line causing the error:
attention = Dot(axes=[2, 2])([decoder_lstm, tf.keras.backend.repeat_elements(tf.keras.backend.expand_dims(encoder_lstm, axis=2), tf.shape(decoder_lstm)[1], axis=1)])By using the
tf.keras.backendfunctions, you ensure compatibility with theDotlayer, and the shapes of the tensors should match correctly.Make sure to import
tf.keras.backendmodule at the beginning of your script:from tensorflow.keras import backend as K
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.