Random Sequence Generation with Padding

  • Share this:

Code introduction


This function takes original data, sequence length, and batch size as input, generates a random sequence, and uses the pad_sequences method from keras.preprocessing.sequence to ensure all sequences in the batch are of the same length.


Technology Stack : numpy, keras.preprocessing.sequence

Code Type : Function that generates random sequences

Code Difficulty : Intermediate


                
                    
def generate_random_sequence(data, length, batch_size):
    import numpy as np
    from keras.preprocessing.sequence import pad_sequences

    # Generate a random sequence of integers
    random_sequence = np.random.randint(0, max(data), size=length)

    # Pad the sequence to ensure all sequences in the batch are of the same length
    padded_sequence = pad_sequences([random_sequence], maxlen=length, padding='post', truncating='post', dtype='int32')

    return padded_sequence