gpt4 book ai didi

python - python中最有效的直方图代码

转载 作者:行者123 更新时间:2023-12-01 05:44:03 25 4
gpt4 key购买 nike

我见过很多关于用简洁的单行代码制作直方图的问题,但我还没有发现有人试图尽可能高效地制作直方图。我目前正在为搜索算法创建大量 tfidf 向量,这涉及创建许多直方图和我当前的代码,虽然非常短且可读性不如我想要的那么快。遗憾的是,我尝试了许多其他方法,但结果却慢得多。你能做得更快吗? cleanStringVector 是一个字符串列表(全部小写,无标点符号),masterWordList 也是一个单词列表,应包含 cleanStringVector 中的每个单词。

from collections import Counter
def tfidfVector(cleanStringVector, masterWordList):
frequencyHistogram = Counter(cleanStringVector)
featureVector = [frequencyHistogram[word] for word in masterWordList]
return featureVector

值得注意的是,Counter 对象对于不存在的键返回零,而不是引发 KeyError,这是一个重要的优点,并且其他问题中的大多数直方图方法都无法通过此测试。

示例:如果我有以下数据:

["apple", "orange", "tomato", "apple", "apple"]
["tomato", "tomato", "orange"]
["apple", "apple", "apple", "cucumber"]
["tomato", "orange", "apple", "apple", "tomato", "orange"]
["orange", "cucumber", "orange", "cucumber", "tomato"]

还有一个主要词汇表:

["apple", "orange", "tomato", "cucumber"]

我希望每个测试用例分别返回以下内容:

[3, 1, 1, 0]
[0, 1, 2, 0]
[3, 0, 0, 1]
[2, 2, 2, 0]
[0, 2, 1, 2]

希望对您有所帮助。

最终的大概结果:

Original Method: 3.213
OrderedDict: 5.529
UnorderedDict: 0.190

最佳答案

这将我的不具代表性的微基准测试中使用 Python 3 的运行时间提高了 1 个数量级:

mapping = dict((w, i) for i, w in enumerate(masterWordList))

def tfidfVector(cleanStringVector, masterWordList):
featureVector = [0] * len(masterWordList)
for w in cleanStringVector:
featureVector[mapping[w]] += 1
return featureVector

关于python - python中最有效的直方图代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16715242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com