0

我想知道使用torchtext推理的正确方法是什么。

假设我已经dump用内置词汇训练了模型和所有字段。下一步似乎是使用torchtext.data.Example加载一个示例。不知何故,我应该通过使用加载的字段来数字化它并创建一个迭代器。

我将不胜感激使用torchtext推理的任何简单示例。

4

1 回答 1

4

对于经过训练的模型和词汇(这是文本字段的一部分,您不必保存整个课程):

    def read_vocab(path):
        #read vocabulary pkl 
        import pickle
        pkl_file = open(path, 'rb')
        vocab = pickle.load(pkl_file)
        pkl_file.close()
        return vocab



    def load_model_and_vocab():
        import torch
        import os.path
    
        my_path = os.path.abspath(os.path.dirname(__file__))
        vocab_path = os.path.join(my_path, vocab_file)
        weights_path = os.path.join(my_path, WEIGHTS)
    
        vocab = read_vocab(vocab_path)
        model = classifier(vocab_size=len(vocab))
        model.load_state_dict(torch.load(weights_path))
        model.eval()
        return model, vocab
    
    
    def predict(model, vocab, sentence):
        tokenized = [w.text.lower() for w in nlp(sentence)]  # tokenize the sentence
        indexed = [vocab.stoi[t] for t in tokenized]         # convert to integer sequence
        length = [len(indexed)]                              # compute no. of words
        tensor = torch.LongTensor(indexed).to('cpu')         # convert to tensor
        tensor = tensor.unsqueeze(1).T                       # reshape in form of batch,no. of words
        length_tensor = torch.LongTensor(length)             # convert to tensor
        prediction = model(tensor, length_tensor)            # prediction
        return round(1-prediction.item())

“分类器”是我为我的模型定义的类。

为了保存词汇 pkl :

    def save_vocab(vocab):
        import pickle
        output = open('vocab.pkl', 'wb')
        pickle.dump(vocab, output)
        output.close()

为了在训练后保存模型,您可以使用:

    torch.save(model.state_dict(), 'saved_weights.pt')

告诉我它是否对你有用!

于 2020-07-06T04:24:53.813 回答