【问题标题】:tf-idf function in python need help to satisfy my outputpython中的tf-idf函数需要帮助来满足我的输出
【发布时间】:2015-02-17 10:37:41
【问题描述】:

我写了一个函数,它基本上计算逆文档频率(以 10 为底的日志(总文档数/包含特定单词的文档数))

我的代码:

def tfidf(docs,doc_freqs):
    res = []
    t = sum(isinstance(i, list) for i in docs)
    for key,val in doc_freqs.items():
        res.append(math.log10(t/val))
    pos = defaultdict(lambda:[])
    for docID, lists in enumerate(docs):
        for element in set(lists):
            pos[element].append([docID] + res)
    return pos

我的输出:

index = tfidf([['a', 'b', 'c'], ['a']], {'a': 2., 'b': 1., 'c': 1.})
index['a']
[[0, 0.0, 0.3010299956639812, 0.3010299956639812], [1, 0.0, 0.3010299956639812, 0.3010299956639812]]
index['b']
[[0, 0.0, 0.3010299956639812, 0.3010299956639812]]

期望的输出:

index = tfidf([['a', 'b', 'c'], ['a']], {'a': 2., 'b': 1., 'c': 1.})
index['a']
[[0, 0.0], [1, 0.0]]
index['b']
[[0, 0.3010299956639812]]

所以基本上我只想显示该术语出现的 docid,后跟它的 idf 值。 (即)在上面的例子中,因为 term'a' 出现在两个文档中,idf 值为 0 。

谁能建议我需要在我的代码中进行哪些修改,以便根据运行时指定的术语仅打印相应的 idf 值??

请帮忙!!! 提前致谢。

【问题讨论】:

    标签: python list dictionary tf-idf


    【解决方案1】:

    狼,

    现在您将整个res 附加到[docID],但您只关心与element 关联的值。我建议将res 更改为dict,如下代码:

    import math
    
    def tfidf(docs,doc_freqs):
        res = {}
        t = sum(isinstance(i, list) for i in docs)
        for key,val in doc_freqs.items():
            res[key] = math.log10(t/val)
        pos = defaultdict(lambda:[])
        for docID, lists in enumerate(docs):
            for element in set(lists):
                pos[element].append([docID, res[element]])
        return pos
    
    docs = [['a', 'b', 'a'], ['a']]
    doc_freqs = {'a': 2., 'b': 1., 'c': 1.}
    
    index = tfidf(docs, doc_freqs)
    

    这就是你的输出:

    index['a']
    [[0, 0.0], [1, 0.0]]
    
    index['b']
    [[0, 0.3010299956639812]]
    

    【讨论】:

      猜你喜欢
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 2020-11-30
      • 1970-01-01
      相关资源
      最近更新 更多