Skip to content

Commit

Permalink
Improved MMR speed #56
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthewJA committed Dec 24, 2016
1 parent 6c1cd04 commit dbd8b3c
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions acton/recommenders.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"""Recommender classes."""

from abc import ABC, abstractmethod
import logging
from typing import Iterable, Sequence

import acton.database
import numpy
import scipy.spatial


def mmr_choose(features: numpy.ndarray, scores: numpy.ndarray, n: int,
Expand Down Expand Up @@ -40,11 +42,17 @@ def mmr_choose(features: numpy.ndarray, scores: numpy.ndarray, n: int,
selections = [scores.argmax()]
selections_set = set(selections)

logging.debug('Running MMR.')
dists = []

dists_matrix = None
while len(selections) < n:
dists.append([numpy.linalg.norm(features[selections[-1]] - features[i])
for i in range(len(scores))])
if len(selections) % (n // 10) == 0:
logging.debug('\rMMR epoch {}/{}.'.format(len(selections), n))
# Compute distances for last selection.
last = features[selections[-1]:selections[-1] + 1]
last_dists = numpy.linalg.norm(features - last, axis=1)
dists.append(last_dists)
dists_matrix = numpy.array(dists)

next_best = None
next_best_margin = float('-inf')
Expand All @@ -53,7 +61,7 @@ def mmr_choose(features: numpy.ndarray, scores: numpy.ndarray, n: int,
if i in selections_set:
continue

margin = l * (scores[i] - (1 - l) * max(d[i] for d in dists))
margin = l * (scores[i] - (1 - l) * dists_matrix[:, i].max())
if margin > next_best_margin:
next_best_margin = margin
next_best = i
Expand Down

0 comments on commit dbd8b3c

Please sign in to comment.