1
$\begingroup$

Hello PyTorch experts:

Sentences and documents both can be variable length.

Lets say, we have following 2 docs:

doc1=[torch.tensor([1,2,3,4]),torch.tensor([4,5,6]),torch.tensor([7,5])]
doc2=[torch.tensor([1,2,3]),torch.tensor([4,5])]

(Here, each tensor is a sentence and each number in the tensor is an index of embedding matrix)

doc1=pad_sequence(doc1,batch_first=True)
doc2=pad_sequence(doc2,batch_first=True)

batch=pad_sequence([doc1,doc2],batch_first=True)

This will throw an error because the length of the longest sentence in the first document is greater than the length of the longest sentence in the second sentence.

So, we need to pad each sentence to the longest sentence of the batch.

One solution would be, find the length of the longest sentence in each batch and pad each sentence to that fixed length. But the pad_sequence function of PyTorch does not support that.

Am I missing something? Is there any other PyTorch way to do this?

$\endgroup$
0
$\begingroup$

I solved this problem by using a keras function:

torch.tensor(tf.keras.preprocessing.sequence.pad_sequences(doc1,maxlen=longest_sent,padding='post')

torch.tensor(tf.keras.preprocessing.sequence.pad_sequences(doc2,maxlen=longest_sent,padding='post')
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.