python - 如何使用 scikit learn 向量化标记的二元组?

标签 python machine-learning nlp scikit-learn nltk

我正在自学如何使用 scikit-learn,我决定开始 second task但是用我自己的语料库。我手工获得了一些双字母组,比方说:

training_data = [[('this', 'is'), ('is', 'a'),('a', 'text'), 'POS'],
[('and', 'one'), ('one', 'more'), 'NEG']
[('and', 'other'), ('one', 'more'), 'NEU']]

我想将它们矢量化为一种格式,这种格式可以很好地填充到 scikit-learn 提供的某些分类算法(svc、多项式朴素贝叶斯等)中。这是我试过的:

from sklearn.feature_extraction.text import CountVectorizer

count_vect = CountVectorizer(analyzer='word')

X = count_vect.transform(((' '.join(x) for x in sample)
                  for sample in training_data))

print X.toarray()

问题是我不知道如何处理标签(即 'POS'、'NEG'、'NEU'),我是否也需要“向量化”标签为了将 training_data 传递给分类算法,或者我可以让它像“POS”或任何其他类型的字符串一样?另一个问题是我得到这个:

raise ValueError("Vocabulary wasn't fitted or is empty!")
ValueError: Vocabulary wasn't fitted or is empty!

那么,我如何向量化像 training_data 这样的二元组。我也在阅读 dictvectorizerSklearn-pandas ,你们认为使用它们是完成这项任务的更好方法吗?

最佳答案

它应该是这样的:

>>> training_data = [[('this', 'is'), ('is', 'a'),('a', 'text'), 'POS'],
                 [('and', 'one'), ('one', 'more'), 'NEG'],
                 [('and', 'other'), ('one', 'more'), 'NEU']]
>>> count_vect = CountVectorizer(preprocessor=lambda x:x,
                                 tokenizer=lambda x:x)
>>> X = count_vect.fit_transform(doc[:-1] for doc in training_data)

>>> print count_vect.vocabulary_
{('and', 'one'): 1, ('a', 'text'): 0, ('is', 'a'): 3, ('and', 'other'): 2, ('this', 'is'): 5, ('one', 'more'): 4}
>>> print X.toarray()
[[1 0 0 1 0 1]
 [0 1 0 0 1 0]
 [0 0 1 0 1 0]]

然后将您的标签放入目标变量中:

y = [doc[-1] for doc in training_data] # ['POS', 'NEG', 'NEU']

现在您可以训练模型了:

model = SVC()
model.fit(X, y)

关于python - 如何使用 scikit learn 向量化标记的二元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27454767/

相关文章:

nlp - 如何将 One-Hot Encoding 值计算为实值向量?

text - 自然语言生成 - 如何测试它听起来是否自然

python - 两个字典列表的平均值

python - Pandas 重置索引未生效

python - PyMC3 多项式模型不适用于非整数观察数据

machine-learning - 用于短文本分类的 CNN 在验证集中表现不佳

python - 如何在Python中填写插入语句的列名

python - 使用opencv python从视频检测图像时如何忽略背景?

machine-learning - 为什么扩张卷积计算效率高?

nlp - 损失函数负对数似然给出损失,尽管完美的准确性