python - pytorch中的一项热门编码文本数据

标签 python scikit-learn pytorch spacy one-hot-encoding

我想知道如何在 pytorch 中对文本数据进行热编码?

对于数字数据,你可以这样做

import torch
import torch.functional as F

t = torch.tensor([6,6,7,8,6,1,7], dtype = torch.int64)
one_hot_vector = F.one_hot(x = t, num_classes=9)
print(one_hot_vector.shape)
# Out > torch.Size([7, 9])

但是如果你有文本数据怎么办

from torchtext.data.utils import get_tokenizer
corpus = ["The cat sat the mat", "The dog ate my homework"]
tokenizer = get_tokenizer("basic_english")
tokens = [tokenizer(doc) for doc in corpus]

但是我如何使用 Pytorch 对这个词汇进行热编码呢?

使用 Scikit Learn 之类的东西我可以做到这一点,在 pytorch 中是否有类似的方法

import spacy
from spacy.lang.en import English
from sklearn.preprocessing import OneHotEncoder

corpus = ["The cat sat the mat", "The dog ate my homework"]
nlp = English()
tokenizer = spacy.tokenizer.Tokenizer(nlp.vocab)
tokens = np.array([[token for token in tokenizer(doc)] for doc in corpus])
one_hot_encoder = OneHotEncoder(sparse = False)
one_hot_encoded = one_hot_encoder.fit_transform(tokens)

最佳答案

您可以执行以下操作:

from typing import Union, Iterable
import torchtext
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator

corpus = ["The cat sat the mat", "The dog ate my homework"]
tokenizer = get_tokenizer("basic_english")
tokens = [tokenizer(doc) for doc in corpus]

voc = build_vocab_from_iterator(tokens)

def my_one_hot(voc, keys: Union[str, Iterable]):
    if isinstance(keys, str):
        keys = [keys]
    return F.one_hot(torch.tensor(voc(keys)), num_classes=len(voc))

关于python - pytorch中的一项热门编码文本数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71146270/

相关文章:

Python ConfigParser 检查选项是否为空的有效方法

python - 在 Windows 10 上从 python 运行时,ffmpeg.probe 不工作

python - 如何在google colab中提取rar文件

Python 神经网络强化学习

python - 在其他元素中受 nan 影响的张量元素上的 PyTorch 向后()

python - pandas 数据透视表 降序排列 python

machine-learning - 如何在 sklearn 中使用 SelectFromModel 查找类的积极信息特征

python - SciKit Learn - SGDClassifier 准确性不佳

pytorch - LibTorch,将 deeplabv3_resnet101 转换为 c++

python - 为什么我会收到运行时错误 : CUDA error: invalid argument in pytorch?