如何将TfidfVectorizer与PySpark一起使用



我对使用Pyspark非常陌生,并且在Pyspark Dataframe方面存在一些问题。

我正在尝试实现TF-IDF算法。我曾经用熊猫数据帧做过一次。然而,我开始使用Pyspark,现在一切都变了:(我不能像dataframe['ColumnName']那样使用PysparkDataframe。当我编写和运行代码时,它说Dataframe是不可迭代的。(。这对我来说是一个巨大的问题,至今仍未解决。当前的问题如下:

与熊猫:


tfidf = TfidfVectorizer(vocabulary=vocabulary, dtype=np.float32)
tfidf.fit(pandasDF['name'])
tfidf_tran = tfidf.transform(pandasDF['name'])

使用PySpark:

tfidf = TfidfVectorizer(vocabulary=vocabulary, dtype=np.float32)
tfidf.fit(SparkDF['name'])
tfidf_tran = tfidf.transform(SparkDF['name'])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~AppDataLocalTemp/ipykernel_19992/3734911517.py in <module>
13 vocabulary = list(vocabulary)
14 tfidf = TfidfVectorizer(vocabulary=vocabulary, dtype=np.float32)
---> 15 tfidf.fit(dataframe['name'])
16 tfidf_tran = tfidf.transform(dataframe['name'])
17 
E:Anacondalibsite-packagessklearnfeature_extractiontext.py in fit(self, raw_documents, y)
1821         self._check_params()
1822         self._warn_for_unused_params()
-> 1823         X = super().fit_transform(raw_documents)
1824         self._tfidf.fit(X)
1825         return self
E:Anacondalibsite-packagessklearnfeature_extractiontext.py in fit_transform(self, raw_documents, y)
1200         max_features = self.max_features
1201 
-> 1202         vocabulary, X = self._count_vocab(raw_documents,
1203                                           self.fixed_vocabulary_)
1204 
E:Anacondalibsite-packagessklearnfeature_extractiontext.py in _count_vocab(self, raw_documents, fixed_vocab)
1110         values = _make_int_array()
1111         indptr.append(0)
-> 1112         for doc in raw_documents:
1113             feature_counter = {}
1114             for feature in analyze(doc):
E:Anacondalibsite-packagespysparksqlcolumn.py in __iter__(self)
458 
459     def __iter__(self):
--> 460         raise TypeError("Column is not iterable")
461 
462     # string methods
TypeError: Column is not iterable

Tf-idf是术语频率乘以逆文档频率。Pyspark库中数据帧的MlLib中没有明确的tf-idf矢量器,但它们有两个有用的模型,可以帮助您了解tf-idf。使用HashingTF,您可以得到术语频率。使用IDF,您将获得相反的文档频率。将两者相乘,您应该得到一个输出矩阵,该矩阵与您最初指定的TfidfVectorizer的输出矩阵相匹配。

最新更新