Random Subsequence Selection and Padding

  • Share this:

Code introduction


This function randomly selects a subsequence of length n_steps from the input sequence and pads it to the same length as the original sequence.


Technology Stack : Keras, NumPy, Keras preprocessing sequence

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def generate_random_sequence(input_sequence, n_steps):
    """
    Generates a random sequence of n_steps length from the input sequence.
    """
    import numpy as np
    from keras.preprocessing.sequence import pad_sequences
    
    # Generate random indices for slicing the input sequence
    indices = np.random.randint(0, len(input_sequence), n_steps)
    
    # Slice the input sequence using the random indices
    random_sequence = np.array([input_sequence[i] for i in indices])
    
    # Pad the random sequence to ensure consistent length
    padded_sequence = pad_sequences([random_sequence], maxlen=len(input_sequence), padding='post')
    
    return padded_sequence[0]