ReversibleField 运行良好,没有 spacy
在 中使用tokenize=None
时ReversibleField
,一切正常
from torchtext.datasets import Multi30k
from torchtext.data import Field, BucketIterator, ReversibleField
import spacy
SRC = ReversibleField(tokenize=None,
init_token = '<sos>',
eos_token = '<eos>',
lower = True,
batch_first= True)
TRG = ReversibleField(tokenize=None,
init_token = '<sos>',
eos_token = '<eos>',
lower = True,
batch_first= True)
train_data, valid_data, test_data = Multi30k.splits(exts = ('.de', '.en'),
fields = (SRC, TRG))
SRC.build_vocab(train_data, min_freq = 2)
TRG.build_vocab(train_data, min_freq = 2)
device = 'cuda:2'
BATCH_SIZE = 3
train_iterator, valid_iterator, test_iterator = BucketIterator.splits(
(train_data, valid_data, test_data),
batch_size = BATCH_SIZE,
device = device)
batch = next(iter(train_iterator))
TRG.reverse(batch.trg)
output>>>
['a group of kids playing with tires.',
'seven construction workers working on a building.',
'a man is performing with fire sticks before a crowd outside.']
使用 spacy 时 ReversibleField 失败
然而,当我尝试使用 spacy 作为我的标记器时,它给了我一大段对我来说没有意义的字符串。
spacy_de = spacy.load('de')
spacy_en = spacy.load('en')
def tokenize_de(text):
"""
Tokenizes German text from a string into a list of strings (tokens) and reverses it
"""
return [tok.text for tok in spacy_de.tokenizer(text)][::-1]
def tokenize_en(text):
"""
Tokenizes English text from a string into a list of strings (tokens)
"""
return [tok.text for tok in spacy_en.tokenizer(text)]
SRC = ReversibleField(tokenize = tokenize_de,
init_token = '<sos>',
eos_token = '<eos>',
lower = True,
batch_first= True)
TRG = ReversibleField(tokenize = tokenize_en,
init_token = '<sos>',
eos_token = '<eos>',
lower = True,
batch_first= True)
train_data, valid_data, test_data = Multi30k.splits(exts = ('.de', '.en'),
fields = (SRC, TRG))
SRC.build_vocab(train_data, min_freq = 2)
TRG.build_vocab(train_data, min_freq = 2)
train_iterator, valid_iterator, test_iterator = BucketIterator.splits(
(train_data, valid_data, test_data),
batch_size = BATCH_SIZE,
device = device)
batch = next(iter(train_iterator))
TRG.reverse(batch.trg)
output >>>
['agroupofkidsplayingwithtires.',
'sevenconstructionworkersworkingonabuilding.',
'amanisperformingwithfiresticksbeforeacrowdoutside.']
这里有什么问题?使用 spacy 时如何将标记正确转换回字符串?