python - 从 pytorch 的 torchtext 库中保存词汇对象

标签 python pytorch torchtext

使用 pytorch 的 torchtext 构建文本分类模型。词汇表对象在 data.field 中:

def create_tabularDataset_object(self,csv_path):
   self.TEXT = data.Field(tokenize=self.tokenizer,batch_first=True,include_lengths=True)
   self.LABEL = data.LabelField(dtype = torch.float,batch_first=True)
def get_vocab_with_glov(self,data):
   # initialize glove embeddings
   self.TEXT.build_vocab(data,min_freq=100,vectors = "glove.6B.100d")

训练后,在生产中为模型提供服务时,我如何保存 TEXT 对象?在预测时,我需要它来索引单词标记

[TEXT.vocab.stoi[t] for t in tokenizedׁ_sentence]

我是不是遗漏了什么,而且没有必要拿着那个东西?除了模型权重,我还需要任何其他文件吗?

最佳答案

实际上最好的方法(更稳定)是使用 torch 内置函数 torch.save(*)

保存文件示例:

torch.save(vocab_obj, 'vocab_obj.pth')

再次加载文件:

vocab_obj = torch.load('vocab_obj.pth')

关于python - 从 pytorch 的 torchtext 库中保存词汇对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61245215/

相关文章:

jupyter-notebook - 使用pytorch时无法在jupyter笔记本中导入 'torchtext'模块

python - 迭代 Torchtext.data.BucketIterator 对象抛出 AttributeError 'Field' 对象没有属性 'vocab'

neural-network - Torchtext 属性错误 : 'Example' object has no attribute 'text_content'

python - 正常和拉普拉斯的 KL 散度未在 TensorFlow Probability 和 PyTorch 中实现

python从shell命令输出中读取

python - 不支持的媒体类型 Django API

python - 在 Flask 应用程序中看不到 Favicon

python - 获取 pytorch 数据集的子集

python - 在 Numpy/PyTorch 中快速查找值大于阈值的索引

python - 遍历列表并在 Python 中漂亮地处理 StopIteration