Skip to content

Optimizing recall calculation for micro-averaging #8126

Closed as not planned
Closed as not planned

Description

@ndomar

Description

Calculating recall using micro-averaging needs to be optimized for large scale dense arrays.

Steps/Code to Reproduce

from sklearn.metrics import recall_score

recall = recall_score(actual, predictions, average='micro')

Versions

Darwin-15.5.0-x86_64-i386-64bit
Python 3.5.2 |Anaconda custom (x86_64)| (default, Jul 2 2016, 17:52:12)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)]
NumPy 1.11.1
SciPy 0.18.1

Activity

  1. rombiee commented on Dec 28, 2016

    @rombiee
    Contributor

    precision_score will suffer from the same lag as they both are calling precision_recall_fscore_support which in turn will evaluate all four.
    Probably we can make more use of warn_for argument?
    Can I work on it and make a PR?

  2. jnothman commented on Dec 28, 2016

    @jnothman
    Member
  3. ndomar commented on Dec 28, 2016

    @ndomar
    Author

    @jnothman

    The jump from .7s to 10s seems very surprising. The calculation of F1
    should be much less burden than of p and r, which also share much of their
    work.

    I was honestly shocked as well when I found that out

    how many samples? how many classes? Or how many labels? Or just provide the
    dataset.

    I have a 5551 x 16890 numpy matrix of 0s and 1s. I am working on a dataset from citeulike to build a recommender that recommends research papers. The dataset is not publically available and I do not own it so I am sorry I can't provide it. So basically there are two labels, 1 indicates that the user has the document in his library, 0 indicates either that he disliked the paper or he didn't read it. So for me it wouldn't make sense to calculate the precision of the recommender, only the recall.

    When you say you calculate recall by itself, with what code?

    Here is a sample code that I am using somewhere in my evaluator class.

        def calculate_recall(self, ratings, predictions):
            """
            The method given original ratings and predictions returns the recall of the recommender
            @param (int[][]) ratings matrix
            @param (int[][]) predictions matrix (only 0s or 1s)
            @returns (float) recall, ranges from 0 to 1
            """
            denom = sum(sum(ratings))
            nonzeros = ratings.nonzero()
            nonzeros_predictions = predictions[nonzeros]
            return sum(nonzeros_predictions) / denom
    

    @HashCode55

    I already worked on it a bit, but if you want to go ahead please!

  4. jnothman commented on Dec 29, 2016

    @jnothman
    Member

    Clearly, our code is not optimised for micro-averaging with a sparse large-scale multilabel problem using dense arrays. But the problem is certainly not in the calculation of P and F1. See benchmarks below, where your approach is faster in all cases (though there is some overhead in scikit-learn to handle various types of input), but is little faster than calculating all of P, R and F, and not substantially faster when using a sparse data structure.

    Please update your issue description, and feel free to offer a patch.

    def recall(y_true, y_pred):
        n_true = y_true.sum()
        nonzeros = y_pred.nonzero()
        tp = y_pred[nonzeros].sum()
        return tp / n_true
    
    
    def prfs(y_true, y_pred):
        n_true = y_true.sum()
        n_pred = y_true.sum()
        nonzeros = y_pred.nonzero()
        tp = y_pred[nonzeros].sum()
        return tp / n_true, tp / n_pred, 2 * tp / (n_true + n_pred), y_true.sum(axis=0)
    
    
    from scipy import sparse
    from sklearn.metrics import recall_score
    
    
    for density in [.01, .1, .25, .5, .75, .9]:
        y_true = np.random.rand(5551, 16890) < density
        y_pred = np.random.rand(5551, 16890) < density
        y_true_sparse = sparse.csr_matrix(y_true)
        y_pred_sparse = sparse.csr_matrix(y_pred)
    
        print('density =', density)
        print('custom recall - dense')
        %timeit recall(y_true, y_pred)
        print('custom prfs - dense')
        %timeit prfs(y_true, y_pred)
        print('skl prfs - dense')
        %timeit recall_score(y_true, y_pred, average='micro')
        print('custom recall - sparse')
        %timeit recall(y_true_sparse, y_pred_sparse)
        print('custom prfs - sparse')
        %timeit prfs(y_true_sparse, y_pred_sparse)
        print('skl prfs - sparse')
        %timeit recall_score(y_true_sparse, y_pred_sparse, average='micro')

    Resutlts look like:

                  DENSE                      SPARSE
            cust rec,cust prfs,sklprfs,cust rec,cust prfs,sklprfs,
          [[  0.426,   0.649,   4.29 ,   0.041,   0.05 ,   0.084],
           [  0.687,   0.902,   5.82 ,   0.577,   0.665,   0.855],
           [  1.14 ,   1.35 ,   8.2  ,   1.55 ,   1.83 ,   2.23 ],
           [  1.9  ,   2.07 ,  12.4  ,   3.38 ,   3.93 ,   4.72 ],
           [  2.06 ,   2.26 ,  14.7  ,   5.16 ,   5.99 ,   7.18 ],
           [  2.14 ,   2.37 ,  16.3  ,   6.2  ,   7.25 ,   8.55 ]]
    
  5. changed the title [-]Calculating recall takes too much time[/-] [+]Optimizing recall calculation for micro-averaging[/+] on Dec 29, 2016
  6. ndomar commented on Dec 29, 2016

    @ndomar
    Author

    @jnothman I updated the title and the description, will provide a patch later. I have to read the wiki on contributing first. Thank you!

  7. rombiee commented on Jan 1, 2017

    @rombiee
    Contributor

    Hi @jnothman,
    Apart from the input handling, when we supply recall_score with a dense matrix we are actually casting it to compressed sparse matrix in _check_targets which might be the culprit here. I tried to check how much time it is actually taking -

    This is from routine _check_targets

    if y_type.startswith('multilabel'):
            start = time.time()
            y_true = csr_matrix(y_true)
            y_pred = csr_matrix(y_pred)
            y_type = 'multilabel-indicator'
            print ("Time taken - {}".format(time.time() - start))
    

    Results :

    
    Density is - 0.01
    Time taken - 2.71723198891
    
    Density is - 0.1
    Time taken - 5.73207402229
    
    Density is - 0.25
    Time taken - 6.15723586082
    
    Density is - 0.5
    Time taken - 5.69532895088
    
    Density is - 0.75
    Time taken - 9.40600514412
    
    Density is - 0.9
    Time taken - 13.1301279068
    

    And for the same reason, if we give it a sparse matrix already, it doesn't take any time to cast and hence the benchmarks above...

  8. jnothman commented on Jan 1, 2017

    @jnothman
    Member

    Yes, perhaps that was a poor decision on our part. However, your use of nonzero and fancy indexing shows promise against our current implementation.

  9. rombiee commented on Jan 4, 2017

    @rombiee
    Contributor

    @jnothman So how should we proceed from here?

  10. jnothman commented on Jan 4, 2017

    @jnothman
    Member
  11. rombiee commented on Jan 4, 2017

    @rombiee
    Contributor

    @jnothman Oh okay! If he's working on it then its fine. I'll find some other issue.

  12. ndomar commented on Jan 7, 2017

    @ndomar
    Author

    Yes I am already working on it, apologies if I am late or something but I just got back from my vacation.

  13. jnothman commented on Feb 11, 2018

    @jnothman
    Member

    I have proposed in #10083 (comment) how I would go about implementing and trialling this improvement.

  14. ShangwuYao commented on Jun 18, 2018

    @ShangwuYao
    Contributor

    I don't think the indexing is faster than the original implementation here, and as @HashCode55 pointed out here, the time-consuming part is actually _check_targets , which is the same conclusion as mine in #11179-comment. So changing the implementation in calculating tp will not make if faster, in fact, I know that the multiplication implementation is blazingly fast.
    Here recall1 is the indexing implementation, and recall2 is the multiplication (original) implementation. It seems like the original implementation is much faster.

    In [38]: def recall1(y_true, y_pred):
        ...:     n_true = y_true.sum()
        ...:     nonzeros = y_pred.nonzero()
        ...:     tp = y_true[nonzeros].sum()    # I think this should be y_true instead of y_pred 
        ...:     return tp / n_true
        ...:
    
    In [39]: def recall2(y_true, y_pred):
        ...:     n_true = y_true.sum()
        ...:     tp = (y_true * y_pred).sum()
        ...:     return tp / n_true
        ...:
    
    In [40]: density = 0.5
    
    In [41]: y_true = np.random.rand(5551, 16890) < density
    
    In [42]: y_pred = np.random.rand(5551, 16890) < density
    
    In [43]: %timeit recall1(y_true, y_pred)
    1.98 s ± 19.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    
    In [44]: %timeit recall2(y_true, y_pred)
    226 ms ± 5.67 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    
    In [45]: density = 0.1
    
    In [46]: y_true = np.random.rand(5551, 16890) < density
    
    In [47]: y_pred = np.random.rand(5551, 16890) < density
    
    In [48]: %timeit recall1(y_true, y_pred)
    742 ms ± 9.18 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    
    In [49]: %timeit recall2(y_true, y_pred)
    220 ms ± 5.05 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
  15. jnothman commented on Jun 18, 2018

    @jnothman
    Member

    Thanks! I'd forgotten that conclusion here.

    Let's close this, and perhaps consider opening an issue to improve efficiency around _check_targets and validation in metrics (e.g. avoiding duplication of unique_labels).

  16. thomasjpfan commented on May 30, 2022

    @thomasjpfan
    Member

    As noted in #8126 (comment), I am closing this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions