【发布时间】:2023-03-21 21:48:01
【问题描述】:
我认为用一个例子来解释我的问题会更容易。
我有一张包含食谱成分的表格,并且我实现了一个函数来计算成分之间的Tanimoto coefficient。计算两种成分之间的系数已经足够快了(需要 3 个 sql 查询),但它不能很好地扩展。要计算所有可能成分组合之间的系数,它需要 N + (N*(N-1))/2 次查询或 500500 次查询,只需 1k 种成分。有没有更快的方法来做到这一点?到目前为止,这是我得到的:
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)
【问题讨论】:
-
真的很好奇你为什么选择使用谷本而不是余弦或其他相似度算法。我正在考虑执行类似的计算,很想听听您的理由。
标签: python sql collaborative-filtering