Ich glaube nicht, dass es einen einfacheren Weg als das, um zu erreichen, was Sie wollen. Eine Sache, die Sie tun können, ist, den Code CountVectorizer verwendet, um das Vokabular zu erstellen. Ich ging durch den Quellcode und das Verfahren ist
_count_vocab(self, raw_documents, fixed_vocab)
mit fixed_vocab=False
genannt.
Also ich schlage vor, dass Sie den folgenden Code (Source) anpassen, um das Vokabular zu erstellen, bevor Sie die TfidfVectorizer
ausführen.
def _count_vocab(self, raw_documents, fixed_vocab):
"""Create sparse feature matrix, and vocabulary where fixed_vocab=False
"""
if fixed_vocab:
vocabulary = self.vocabulary_
else:
# Add a new value when a new vocabulary item is seen
vocabulary = defaultdict()
vocabulary.default_factory = vocabulary.__len__
analyze = self.build_analyzer()
j_indices = _make_int_array()
indptr = _make_int_array()
indptr.append(0)
for doc in raw_documents:
for feature in analyze(doc):
try:
j_indices.append(vocabulary[feature])
except KeyError:
# Ignore out-of-vocabulary items for fixed_vocab=True
continue
indptr.append(len(j_indices))
if not fixed_vocab:
# disable defaultdict behaviour
vocabulary = dict(vocabulary)
if not vocabulary:
raise ValueError("empty vocabulary; perhaps the documents only"
" contain stop words")
j_indices = frombuffer_empty(j_indices, dtype=np.intc)
indptr = np.frombuffer(indptr, dtype=np.intc)
values = np.ones(len(j_indices))
X = sp.csr_matrix((values, j_indices, indptr),
shape=(len(indptr) - 1, len(vocabulary)),
dtype=self.dtype)
X.sum_duplicates()
return vocabulary, X
können Sie etwas weiter erklären? –
Hoffe das hilft! –
ja es ist jetzt sehr sauber. –