Scikit Learn - 从特征数组的语料库而不是原始文档的语料库计算 TF-IDF

Scikit Learn - Calculating TF-IDF from a corpus of arrays of features instead of from a corpus of raw documents

Scikit-Learn 的 TfidfVectorizer 将原始文档集合转换为 TF-IDF 特征矩阵。我想将特征名称矩阵转换为 TF-IDF 特征,而不是原始文档。

您提供的语料库 fit_transform() 应该是一组原始文档,但我希望能够为它(或类似的函数)提供每个文档的一组特征数组.例如:

corpus = [
    ['orange', 'red', 'blue'],
    ['orange', 'yellow', 'red'],
    ['orange', 'green', 'purple (if you believe in purple)'],
    ['orange', 'reddish orange', 'black and blue']
]

...与一维字符串数组相对。

我知道我可以为要使用的 TfidfVectorizer 定义自己的词汇表,这样我就可以轻松地在我的语料库中创建独特的特征及其在特征向量中的索引。但是该函数仍然需要原始文档,并且由于我的特征长度不同并且偶尔会重叠(例如,'orange' 和 'reddish orange'),我不能只是将我的特征连接成单个字符串并使用 ngrams .

是否有其他 Scikit-Learn 函数可供我使用,但我没有找到?有没有办法使用我没有看到的 TfidfVectorizer?还是我必须自制自己的 TF-IDF 函数才能执行此操作?

您可以编写自定义函数来覆盖内置的预处理器和分词器。

来自文档:

Preprocessor - A callable that takes an entire document as input (as a single string), and returns a possibly transformed version of the document, still as an entire string. This can be used to remove HTML tags, lowercase the entire document, etc.

Tokenizer - A callable that takes the output from the preprocessor and splits it into tokens, then returns a list of these.

在这种情况下,没有要执行的预处理(因为没有原始文档)。标记化也是不必要的,因为我们已经有了特征数组。因此,我们可以这样做:

tfidf = TfidfVectorizer(preprocessor=lambda x: x, tokenizer=lambda x: x)
tfidf_matrix = tfidf.fit_transform(corpus)

我们通过使用 lambda x: x 简单地传递整个语料库来跳过预处理器和分词器步骤。一旦内置分析器接收到特征数组,它就会自行构建词汇表,并照常在“标记化”语料库上执行 TF-IDF。