Great! With your data prepared, you can proceed to build and train the neural network. Here's a step-by-step guide using TensorFlow and Keras to create a sequence-to-sequence model for your task.
Step-by-Step Implementation
1. Import Required Libraries:
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, LSTM, Dense, Embedding, Masking
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
2. Data Preparation:
Assuming your data is prepared in a numbers list for input and words list for output, where both lists are aligned by index:
# Define constants
MAX_NUM_DIGITS = max(len(str(num)) for num in numbers)
MAX_SEQ_LENGTH = max(len(seq.split()) for seq in words) # Longest word sequence
INPUT_VOCAB_SIZE = 11 # 10 digits + 1 for padding
OUTPUT_VOCAB_SIZE = len(set(' '.join(words).split())) + 1 # Unique Russian words + 1 for padding
Convert input numbers to padded digit sequences:
def tokenize_numbers(numbers):
return [[int(digit) for digit in str(num)] for num in numbers]
number_sequences = tokenize_numbers(numbers)
number_sequences = pad_sequences(number_sequences, maxlen=MAX_NUM_DIGITS, padding='post')
# Tokenization for output
word_index = {word: i for i, word in enumerate(sorted(set(' '.join(words).split())), start=1)}
index_word = {i: word for word, i in word_index.items()}
word_sequences = [[word_index[word] for word in seq.split()] for seq in words]
word_sequences_padded = pad_sequences(word_sequences, maxlen=MAX_SEQ_LENGTH, padding='post')
word_sequences_categorical = to_categorical(word_sequences_padded, num_classes=OUTPUT_VOCAB_SIZE)
3. Build the Model:
# Encoder
encoder_inputs = Input(shape=(MAX_NUM_DIGITS,))
encoder_embedding = Embedding(INPUT_VOCAB_SIZE, 64, mask_zero=True)(encoder_inputs)
encoder_lstm, state_h, state_c = LSTM(128, return_state=True, dropout=0.2)(encoder_embedding)
encoder_states = [state_h, state_c]
# Decoder
decoder_inputs = Input(shape=(MAX_SEQ_LENGTH,))
decoder_embedding = Embedding(OUTPUT_VOCAB_SIZE, 64, mask_zero=True)(decoder_inputs)
decoder_lstm = LSTM(128, return_sequences=True, return_state=True, dropout=0.2)
decoder_outputs, _, _ = decoder_lstm(decoder_embedding, initial_state=encoder_states)
decoder_dense = Dense(OUTPUT_VOCAB_SIZE, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
# Define the model
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
4. Compile the Model:
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
5. Train the Model:
decoder_input_data = np.zeros_like(word_sequences_padded)
decoder_input_data[:, 1:] = word_sequences_padded[:, :-1] # Shift right
model.fit([number_sequences, decoder_input_data], word_sequences_categorical,
batch_size=64, epochs=30, validation_split=0.2)
6. Inference:
For inference, you'll need encoder and decoder models separately:
# Encoder inference model
encoder_model = Model(encoder_inputs, encoder_states)
# Decoder inference model
decoder_state_input_h = Input(shape=(128,))
decoder_state_input_c = Input(shape=(128,))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
decoder_outputs, state_h, state_c = decoder_lstm(
decoder_embedding, initial_state=decoder_states_inputs)
decoder_states = [state_h, state_c]
decoder_outputs = decoder_dense(decoder_outputs)
decoder_model = Model(
[decoder_inputs] + decoder_states_inputs,
[decoder_outputs] + decoder_states)
Generate responses using the trained model:
def decode_sequence(input_seq):
# Encode the input as state vectors.
states_value = encoder_model.predict(input_seq)
# Generate empty target sequence of length 1.
target_seq = np.zeros((1, 1))
# Populate the first character of target sequence with the start character.
target_seq[0, 0] = word_index['старт'] # Use an appropriate start token
stop_condition = False
decoded_sentence = []
while not stop_condition:
output_tokens, h, c = decoder_model.predict(
[target_seq] + states_value)
sampled_token_index = np.argmax(output_tokens[0, -1, :])
sampled_word = index_word[sampled_token_index]
decoded_sentence.append(sampled_word)
if (sampled_word == 'конец' or
len(decoded_sentence) > MAX_SEQ_LENGTH):
stop_condition = True
target_seq = np.zeros((1, 1))
target_seq[0, 0] = sampled_token_index
states_value = [h, c]
return ' '.join(decoded_sentence)
# Example usage to decode a number:
decoded_sentence = decode_sequence(np.array([[1, 2, 3]]))
print(decoded_sentence)
This implementation provides a comprehensive framework for building a sequence-to-sequence model using an encoder-decoder architecture with LSTMs. Fine-tuning might be required to improve results, such as adjusting hyperparameters or applying more data preprocessing.