【问题标题】:Algorithm process is slow算法过程很慢
【发布时间】:2016-02-17 12:09:33
【问题描述】:

考虑一个平台,用户可以在其中选择他更重视的因素。例如标准的5个因素A, B, C, D, E

然后每个产品评论都有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 秒才能加载的页面。

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

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

【问题讨论】:

    标签: python algorithm performance weighted-average


    【解决方案1】:

    第一种选择:使用 numpy 和 pandas 可以提高您的速度,如果以巧妙的方式加以利用,那么通过尽可能避免循环。这可以通过使用 apply 方法来实现,同时处理 numpypandas,以及一些条件或 lambda 函数。

    for company in companies:
        for review in company:
    

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

    编辑:这里note_formula是一个返回评论权重的函数,如问题的cmets所示:

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

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

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

    【讨论】:

    • 你能解释一下note_formula这行吗?我从未使用过 numpy 或 pandas,这对我来说似乎很复杂。
    • 当然,我将答案编辑为精确,note_formula() 是注释行中问题中定义的函数。无需在公司和评论上循环,您可以将该功能应用于整个 pandas 列并节省时间
    猜你喜欢
    • 2013-06-10
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    相关资源
    最近更新 更多