Pytorch создает модель seq2seq MT, но как получить результаты перевода из выходного тензора?

Я пытаюсь реализовать свой собственный механизм MT, следуя инструкциям в https://github.com/bentrevett/pytorch-seq2seq/blob/master/1%20-%20Sequence%20to%20Sequence%20Learning%20with%20Neural%20Networks.ipynb

SRC = Field(tokenize=tokenize_en,
            init_token='<sos>',
            eos_token='<eos>',
            lower=True)

TRG = Field(tokenize=tokenize_de,
            init_token='<sos>',
            eos_token='<eos>',
            lower=True)

После обучения модели ссылка дает только способ пакетной оценки, но я хочу попробовать одну строку и получить результаты перевода. например, я хочу, чтобы моя модель переводила ввод Boys и получала немецкие переводы.

savedfilemodelpath='./pretrained_model/2020-09-27en-de.pth'
model.load_state_dict(torch.load(savedfilemodelpath))
model.eval()
inputstring = 'Boys'
processed=SRC.process([SRC.preprocess(inputstring)]).to(device)
output=model(processed,processed)
output_dim = output.shape[-1]
outputs = output[1:].view(-1, output_dim)
for item in outputs:
    print('item shape is {} and item.argmax is {}, and words is {}'.format(item.shape,item.argmax(),TRG.vocab.itos[item.argmax()]))

Итак, мой вопрос в том, что правильно получать результаты перевода:
Во-первых: преобразовать строку в тензор

inputstring = 'Boys'
processed=SRC.process([SRC.preprocess(inputstring)]).to(device)

Второе: отправить тензор в модель. Поскольку у модели есть параметр TRG. Я должен указать тензор, могу ли я не дать тензор TRG?

output=model(processed,processed)
output_dim = output.shape[-1]
outputs = output[1:].view(-1, output_dim)

В-третьих: через тензор возврата я использую argmax для получения результатов перевода? это правильно?

Или как я могу получить правильные результаты перевода?

for item in outputs:
        print('item shape is {} and item.argmax is {}, and words is {}'.format(item.shape,item.argmax(),TRG.vocab.itos[item.argmax()+1]))

person Oscar    schedule 05.11.2020    source источник


Ответы (1)


я получил ответ от translate_sentence. Большое спасибо @Aladdin Persson

def translate_sentence(model, sentence, SRC, TRG, device, max_length=50):
    # print(sentence)

    # sys.exit()
    # Create tokens using spacy and everything in lower case (which is what our vocab is)
    if type(sentence) == str:
        tokens = [token.text.lower() for token in spacy_en(sentence)]
    else:
        tokens = [token.lower() for token in sentence]

    # print(tokens)

    # sys.exit()
    # Add <SOS> and <EOS> in beginning and end respectively
    tokens.insert(0, SRC.init_token)
    tokens.append(SRC.eos_token)

    # Go through each english token and convert to an index
    text_to_indices = [SRC.vocab.stoi[token] for token in tokens]

    # Convert to Tensor
    sentence_tensor = torch.LongTensor(text_to_indices).unsqueeze(1).to(device)

    # Build encoder hidden, cell state
    with torch.no_grad():
        hidden, cell = model.encoder(sentence_tensor)

    outputs = [TRG.vocab.stoi["<sos>"]]

    for _ in range(max_length):
        previous_word = torch.LongTensor([outputs[-1]]).to(device)

        with torch.no_grad():
            output, hidden, cell = model.decoder(previous_word, hidden, cell)
            best_guess = output.argmax(1).item()

        outputs.append(best_guess)

        # Model predicts it's the end of the sentence
        if output.argmax(1).item() == TRG.vocab.stoi["<eos>"]:
            break

    translated_sentence = [TRG.vocab.itos[idx] for idx in outputs]

    # remove start token
    return translated_sentence[1:]

И перевод не генерируется один раз. На самом деле он генерируется один раз и используется несколько раз.

person Oscar    schedule 06.11.2020