code: def precision_at_k(
      predicted_ranks, test_interactions, k=10, preserve_rows=False
  ):
      """
      Modified from LightFM.
      :param predicted_ranks: Numpy matrix
      The results of model.predict_rank()
      :param test_interactions: scipy.sparse matrix
      Test interactions matrix of shape [n_users, n_items]
      :param k: int
      The rank at which to stop evaluating precision.
      :param preserve_rows: bool
      If True, a value of 0 will be returned for every user without test interactions.
      If False, only users with test interactions will be returned.
      :return: np.array
      """
      positive_test_interactions = test_interactions > 0
      ranks = sp.csr_matrix(
          predicted_ranks * positive_test_interactions.A
      )
      ranks.data = np.less(ranks.data, (k + 1), ranks.data)
  
      precision = (
          np.squeeze(np.array(ranks.sum(axis=1))).astype(float) / k
      )
  
      if not preserve_rows:
          precision = precision[
              positive_test_interactions.getnnz(axis=1) > 0
          ]
  
      return precision
  
file_path: tensorrec/tensorrec/eval.py
imports: import numpy
  import scipy.sparse
  from .tensorrec import TensorRec
label_desc: Use image node_id 1 for calling a global function with example usage: precision_at_k(predicted_ranks, test_interactions, k, preserve_rows) and returns: precision