算法过程很慢

时间:2016-02-17 12:09:33

标签: python algorithm performance weighted-average

考虑一个用户选择更重要的因素的平台。例如,标准A, B, C, D, E

的5个因素

然后每个产品评论的权重为A1, B1, C1, D1, E1。因此,如果他更重视A,那么称重将考虑到这一点。结果是每个评论对每个用户可以有不同的总体。

我的问题是关于算法。目前处理速度很慢。

对于每个类别摘要,我需要遍历该类别的所有公司以及每个公司的所有评论。

#1 step
find companies of category X with more than 1 review published

companies_X = [1, 2, 3, 5, n]
#2 step 
iterate all companies, and all reviews of these companies

for company in companies:
   for review in company:
      #calculate the weighing of the review for the current user criteria
      #give more importance to recent reviews
#3 step 
avg of all reviews for each company data
#4 step 
make the avg of all companies of this category to create a final score for the category x

这样可行,但我的页面无法加载30秒。

我正在考虑缓存此页面,但在这种情况下,我需要在后台为所有用户处理此页面。绝对不是一个好的解决方案。

有关改进的任何想法?欢迎任何见解。

1 个答案:

答案 0 :(得分:2)

第一个选项:使用numpy和pandas可以提高您的速度,如果以智能方式利用,那么尽可能避免循环。这可以通过使用apply方法进行,同时处理numpypandas,以及一些条件或lambda函数。

for company in companies:
    for review in company:

可以替换为review_data["note"] = note_formula(review_data["number_reviews"])

修改:此处note_formula是一个返回评论权重的函数,如问题评论中所示:

  # calculate the weighing of the review for the current user criteria
  # give more importance to recent reviews 

您可以使用pandas中的groupby方法以及平均值计算来执行第4步。

第二个选项:您的数据存储在哪里?如果它们位于数据库中,提高性能的一个好规则是:尽可能少地移动数据,因此直接在数据库中执行请求,我认为所有操作都可以用SQL编写,然后只重定向结果到python脚本。如果您的数据以其他方式存储,请考虑使用数据库引擎,例如,如果您不想快速扩展,请使用SQLite