I'm working on an NLP problem and am using PyTorch. For some reason, my dataloader is returning malformed batches. I have input data that comprises sentences and integer labels. The sentences can either a list of sentences or a list of list of tokens. I will later convert the tokens to integers in a downstream component.
list_labels = [ 0, 1, 0]
# List of sentences.
list_sentences = [ 'the movie is terrible',
'The Film was great.',
'It was just awful.']
# Or list of list of tokens.
list_sentences = [['the', 'movie', 'is', 'terrible'],
['The', 'Film', 'was', 'great.'],
['It', 'was', 'just', 'awful.']]
I created the following custom dataset:
import torch
from torch.utils.data import DataLoader, Dataset
class MyDataset(torch.utils.data.Dataset):
def __init__(self, sentences, labels):
self.sentences = sentences
self.labels = labels
def __getitem__(self, i):
result = {}
result['sentences'] = self.sentences[i]
result['label'] = self.labels[i]
return result
def __len__(self):
return len(self.labels)
When I provide input in the form of a list of sentences, the dataloader correctly returns batches of complete sentences. Note that batch_size=2
:
list_sentences = [ 'the movie is terrible', 'The Film was great.', 'It was just awful.']
list_labels = [ 0, 1, 0]
dataset = MyDataset(list_sentences, list_labels)
dataloader = DataLoader(dataset, batch_size=2)
batch = next(iter(dataloader))
print(batch)
# {'sentences': ['the movie is terrible', 'The Film was great.'], <-- Great! 2 sentences in batch!
# 'label': tensor([0, 1])}
The batch correctly contains two sentences and two labels because batch_size=2
.
However, when I instead enter the sentences as pre-tokenized list of list of token, I get weird results:
list_sentences = [['the', 'movie', 'is', 'terrible'], ['The', 'Film', 'was', 'great.'], ['It', 'was', 'just', 'awful.']]
list_labels = [ 0, 1, 0]
dataset = MyDataset(list_sentences, list_labels)
dataloader = DataLoader(dataset, batch_size=2)
batch = next(iter(dataloader))
print(batch)
# {'sentences': [('the', 'The'), ('movie', 'Film'), ('is', 'was'), ('terrible', 'great.')], <-- WHAT?
# 'label': tensor([0, 1])}
Note that this batch's sentences
is one single list with tuples of word pairs. I was expecting sentences
to be a list of two lists, like this:
{'sentences': [['the', 'movie', 'is', 'terrible'], ['The', 'Film', 'was', 'great.']
What is going on?