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

2024-09-28 20:50:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用

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]
] 

正如你所看到的,词汇表的顺序和我上面设置的不一样。有没有办法改变这种状况?谢谢


Tags: thedevelopersqlnetnodejscorpusjavathis
1条回答
网友
1楼 · 发布于 2024-09-28 20:50:31

您将词汇表作为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]]

相关问题 更多 >