我想知道使用torchtext进行推理的正确方式是什么。
假设我已经训练了模型,并使用构建的词汇表对所有字段进行了dump。似乎下一步是使用torchtext.data.Example加载一个示例。不知何故,我应该通过使用加载的字段来对其进行数值化,并创建一个迭代器。
如果有任何使用torchtext进行推理的简单示例,我将不胜感激。
发布于 2020-07-06 12:24:54
对于经过训练的模型和词汇表(它是文本字段的一部分,您不必保存整个类):
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')告诉我这对你有没有用!
https://stackoverflow.com/questions/62744998
复制相似问题