def tfidf_linking(self, qry_ids, qry_mask, top_k):
    """Match questions to entities via Tf-IDF."""
    tf.logging.info("Building question count matrix...")
    question_count_matrix = search_utils.build_count_matrix([qry_ids],
                                                            [qry_mask])
    tf.logging.info("Computing question TF-IDFs...")
    qry_tfidfs = search_utils.counts_to_tfidf(question_count_matrix, self.idfs)
    qry_tfidfs = normalize(qry_tfidfs, norm="l2", axis=0)
    tf.logging.info("Searching...")
    distances = qry_tfidfs.transpose().dot(self.ent_tfidfs)[0, :].tocsr()
    if len(distances.data) <= top_k:
      o_sort = np.argsort(-distances.data)
    else:
      o_sort = np.argpartition(-distances.data, top_k)[:top_k]
    top_doc_indices = distances.indices[o_sort]
    mentions = []
    for m in range(top_k):
      mentions.append(self.id2entity[top_doc_indices[m]])
    tf.logging.info("Mentions: %r", mentions)
    return mentions
Match questions to entities via Tf-IDF.
language/labs/drkit/hotpotqa/demo.py