我认为用一个例子来解释我的问题会更容易。
我有一张包含食谱成分的表格,我已经实现了一个函数来计算 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/