如何获得CountVectorizer功能名称的设置顺序,而不是字母顺序?

时间:2019-05-14 13:03:33

标签: python machine-learning scikit-learn

我正在尝试使用

将某些数据矢量化
sklearn.feature_extraction.text.CountVectorizer.

这是我要向量化的数据:

corpus = [
 'We are looking for Java developer',
 'Frontend developer with knowledge in SQL and Jscript',
 'And this is the third one.',
 'Is this the first document?',
]

矢量化器的属性由以下代码定义:

vectorizer = CountVectorizer(stop_words="english",binary=True,lowercase=False,vocabulary={'Jscript','.Net','TypeScript','SQL', 'NodeJS','Angular','Mongo','CSS','Python','PHP','Photoshop','Oracle','Linux','C++',"Java",'TeamCity','Frontend','Backend','Full stack', 'UI Design', 'Web','Integration','Database design','UX'})

我跑步后:

X = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names())
print(X.toarray()) 

我得到了理想的结果,但是词汇表中的关键字按字母顺序排列。输出看起来像这样:

['.Net', 'Angular', 'Backend', 'C++', 'CSS', 'Database design', 
'Frontend', 'Full stack', 'Integration', 'Java', 'Jscript', 'Linux', 
'Mongo', 'NodeJS', 'Oracle', 'PHP', 'Photoshop', 'Python', 'SQL', 
'TeamCity', 'TypeScript', 'UI Design', 'UX', 'Web']

[
[0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
] 

如您所见,词汇表的排列顺序与我上面设定的顺序不同。有办法改变吗?谢谢

1 个答案:

答案 0 :(得分:1)

您以set的形式传递了词汇,这意味着顺序不再重要。示例:

{'a','b'} == {'b','a'}
>>> True

因此scikit-learn使用字母顺序对其重新排序。为了防止这种情况,您需要传递词汇表中的list

vectorizer = CountVectorizer(stop_words="english",binary=True,lowercase=False,vocabulary=['Jscript','.Net','TypeScript','SQL', 'NodeJS','Angular','Mongo','CSS','Python','PHP','Photoshop','Oracle','Linux','C++',"Java",'TeamCity','Frontend','Backend','Full stack', 'UI Design', 'Web','Integration','Database design','UX'])

X = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names())
print(X.toarray()) 

>>> ['Jscript', '.Net', 'TypeScript', 'SQL', 'NodeJS', 'Angular', 'Mongo', 
'CSS', 'Python', 'PHP', 'Photoshop', 'Oracle', 'Linux', 'C++', 'Java', 
'TeamCity', 'Frontend', 'Backend', 'Full stack', 'UI Design', 'Web', 
'Integration', 'Database design', 'UX']

>>> [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0]
     [1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]