python - scikit-learn 矢量化词汇表,多个术语映射到同一索引

标签 python scikit-learn

skikit-learn 的 TfidfVectorizer 可以正确地将具有相同字典值的词汇术语映射到同一索引,但是,它会在输出中创建与词汇字典中的条目一样多的列。有没有比在转换后删除多余的列更好的方法来解决这个问题?也就是说,在下面的示例中,我不需要第三列,因为它始终为零。

from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer=TfidfVectorizer(vocabulary={'surgery':0, 'sx':0, 'radiology':1})
text=['i had surgery','patient sx went well','radiology department']
vectorizer.fit(text)
vectorizer.transform(text).todense()

>>> matrix([[ 1.,  0.,  0.],
            [ 1.,  0.,  0.],
            [ 0.,  1.,  0.]])

最佳答案

sklearn.feature_selection.VarianceThreshold (scikit-learn >= 0.15) 将删除全零特征(以及更普遍的常量特征)。

>>> X = np.array([[1, 0, 0], [1, 0, 0], [0, 1, 0]])
>>> VarianceThreshold().fit_transform(X)
array([[1, 0],
       [1, 0],
       [0, 1]])

关于python - scikit-learn 矢量化词汇表,多个术语映射到同一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26149273/

相关文章:

python - 与 Scikit-Learn 的 Logistic 回归相比,Tensorflow 的性能要差得多

python - 为什么我收到 AttributeError : 'LinearRegressionGD' object has no attribute 'n_iter'

python - 如何使用新数据在 sklearn 中重新训练逻辑回归模型

python - 是否有与 Linux/Unix "fold"命令等效的 Vim?

Python 在保持顺序的同时从列表中删除一些重复项?

python - 将 Matplotlib 图像作为字符串返回

python - kNN 在 Python 中具有大的稀疏矩阵

python - 为什么 scikit-learn 对不同的回归器要求不同的数据形状?

python - 构建 Python C 扩展

python - 将参数传递给 fixture 函数