python - SQL计算几个向量的谷本系数

标签 python sql collaborative-filtering

我认为用一个例子来解释我的问题会更容易。

我有一张包含食谱成分的表格,我已经实现了一个函数来计算 Tanimoto coefficient成分之间。它足够快来计算两种成分之间的系数(需要 3 个 sql 查询),但它不能很好地扩展。要计算所有可能的成分组合之间的系数,它需要 N + (N*(N-1))/2 个查询或仅 1k 个成分的 500500 个查询。有更快的方法吗?这是我到目前为止得到的:

class Filtering():
  def __init__(self):
    self._connection=sqlite.connect('database.db')

  def n_recipes(self, ingredient_id):
    cursor = self._connection.cursor()
    cursor.execute('''select count(recipe_id) from recipe_ingredient
        where ingredient_id = ? ''', (ingredient_id, ))
    return cursor.fetchone()[0]

  def n_recipes_intersection(self, ingredient_a, ingredient_b):
    cursor = self._connection.cursor()
    cursor.execute('''select count(drink_id) from recipe_ingredient where
        ingredient_id = ? and recipe_id in (
        select recipe_id from recipe_ingredient
        where ingredient_id = ?) ''', (ingredient_a, ingredient_b))
    return cursor.fetchone()[0]

  def tanimoto(self, ingredient_a, ingredient_b):
    n_a, n_b = map(self.n_recipes, (ingredient_a, ingredient_b))
    n_ab = self.n_recipes_intersection(ingredient_a, ingredient_b)
    return float(n_ab) / (n_a + n_b - n_ab)

最佳答案

为什么不直接将所有配方提取到内存中,然后在内存中计算 Tanimoto 系数?

它更简单,也更快。

关于python - SQL计算几个向量的谷本系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1992158/

相关文章:

python - 在 python 中使用 raw_input() 输入 Unicode

python - Conda 不会安装 pdfplumber

python - 在 Python 中获取文件的哈希值(摘要)——一次读取整个文件与逐行读取

c# - 可以将实体插入多个表的ORM

java - 在 Java 中运行 MySQL 查询?

split - AttributeError: 'DatasetAutoFolds' 对象没有属性 'split'

Python np.sqrt(x-a)*np.heaviside(x,a)

sql - 在grails准备好的语句上使用like时引发异常

java - 关于推荐引擎

python - 使用 Pandas 数据框和嵌套在 Python 中的循环的基于项目的协作过滤器的瓶颈