我设置batch_size
了 equals 64
,但是当我打印出 train_batch 和 val_batch 时,大小不等于 64。
首先,我定义TEXT
和LABEL
字段。
tokenize = lambda x: x.split()
TEXT = data.Field(sequential=True, tokenize=tokenize)
LABEL = data.Field(sequential=False)
然后我继续尝试遵循教程,并在下面写了一些东西:
train_data, valid_data = data.TabularDataset.splits(
path='.',
train='train_intent.csv', validation='val.csv',
format='csv',
fields= {'sentences': ('text', TEXT),
'labels': ('label',LABEL)}
)
test_data = data.TabularDataset(
path='test.csv',
format='csv',
fields={'sentences': ('text', TEXT)}
)
TEXT.build_vocab(train_data)
LABEL.build_vocab(train_data)
BATCH_SIZE = 64
train_iter, val_iter = data.BucketIterator.splits(
(train_data, valid_data),
batch_sizes=(BATCH_SIZE, BATCH_SIZE),
sort_key=lambda x: len(x.text),
sort_within_batch=False,
repeat=False,
device=device
)
但是当我想知道 iter 是否正常时,我会发现以下奇怪的事情:
train_batch = next(iter(train_iter))
print(train_batch.text.shape)
print(train_batch.label.shape)
[output]
torch.Size([15, 64])
torch.Size([64])
并且训练过程输出错误ValueError: Expected input batch_size (15) to match target batch_size (64).
:
def train(model, iterator, optimizer, criterion):
epoch_loss = 0
model.train()
for batch in iterator:
optimizer.zero_grad()
predictions = model(batch.text)
loss = criterion(predictions, batch.label)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
return epoch_loss / len(iterator)
任何人都可以给我一个提示将不胜感激。谢谢!