アイテムを高次元空間のポイントとして扱い、それらすべてをkdツリーなどのBSPツリーに挿入することができます。属性の重みを使用するには、対応する座標を掛けるだけです。(w1*x, w2*y, ...)
準備:(ウィキペディア、Pythonコードから)
def kdtree(point_list, depth=0):
if not point_list:
return None
# Select axis based on depth so that axis cycles through all valid values
k = len(point_list[0]) # assumes all points have the same dimension
axis = depth % k
# Sort point list and choose median as pivot element
point_list.sort(key=lambda point: point[axis])
median = len(point_list) // 2 # choose median
# Create node and construct subtrees
node = Node()
node.location = point_list[median]
node.left_child = kdtree(point_list[:median], depth + 1)
node.right_child = kdtree(point_list[median + 1:], depth + 1)
return node
検索:(要点から、ウィキペディアのアルゴリズムに基づく)
# method of the Node-class
def closest_point(self, target, point, best=None):
if target is None:
return best
if best is None:
best = target
# consider the current node
if distance(target, point) < distance(best, point):
best = target
# search the near branch
best = self.child_near(point).closest_point(point, best)
# search the away branch - maybe
if self.distance_axis(point) < distance(best, point):
best = self.child_away(point).closest_point(target, point, best)
return best
続きを読む: