dedtech.info

Information about computer technology.

Pad A Text Sequence For A Neural Network With Python

This blog post will explain how to add padding to an encoded text sequence with Python. Inputs for a neural network have to be the same size to be processed. First, a function named pad has to be defined. The function will take two arguments, the first one being the sequence that is to be padded, and the second one being the desired length of the sequence with padding. The variable num is set equal to max minus the length of sequence. That will determine how much padding will be added to the sequence. The variable padding is set equal to sequence plus the product of [0] and num. Then the result is returned by the function.

def pad(sequence, max):
    num = max - len(sequence)
    padding = sequence + ([0] * num)
    return padding

A variable is declared that holds the sequence to be padded.

sequence = [1, 2, 3]

A variable named padded_sequence holds the result of the pad function.

padded_sequence = pad(sequence, 5)

The results are printed to the screen.

print(padded_sequence)

This is what the whole source code looks like.

def pad(sequence, max):
    num = max - len(sequence)
    padding = sequence + ([0] * num)
    return padding

sequence = [1, 2, 3]
padded_sequence = pad(sequence, 5)
print(padded_sequence)

Leave a Reply

Your email address will not be published. Required fields are marked *