Repository navigation
Description
Describe the workflow you want to enable
I'm concerned with slow execution speed of the classification_report procedure which makes it barely suitable for production-grade workloads.
On a 8M sample it already takes 15 seconds whereas simple POC numba implementation takes 20 to 40 milliseconds. I understand that sklearn code is well covered with tests, has wide functionality, follows style guildlines and best practices, but there should be no excuse for the performace leap with simple POC of magnitude that big (x1000).
import numpy as np
from sklearn.metrics import classification_report
y_true = np.random.randint(0, 2, size=2 ** 23)
y_pred = y_true.copy()
np.random.shuffle(y_pred[2 ** 20 : 2 ** 21])
print(classification_report(y_true=y_true, y_pred=y_pred, digits=10, output_dict=False, zero_division=0,))precision recall f1-score support 0 0.9373906697 0.9373906697 0.9373906697 4192570 1 0.9374424159 0.9374424159 0.9374424159 4196038 accuracy 0.9374165535 8388608 macro avg 0.9374165428 0.9374165428 0.9374165428 8388608 weighted avg 0.9374165535 0.9374165535 0.9374165535 8388608time: 18.6 s (started: 2023-07-08 16:10:08 +03:00)
print(own_classification_report(y_true=y_true, y_pred=y_pred, zero_division=0))
(3930076, 3933544, 262494, 262494, 0.9374165534973145, array([4192570, 4196038], dtype=int64), array([0.93739067, 0.93744242]), array([0.93739067, 0.93744242]), array([0.93739067, 0.93744242]))
time: 16 ms (started: 2023-07-08 16:11:18 +03:00)
Describe your proposed solution
import numpy as np
from numba import njit
@njit()
def own_classification_report(y_true: np.ndarray, y_pred: np.ndarray, nclasses: int = 2, zero_division: int = 0):
correct = np.zeros(nclasses, dtype=np.int64)
wrong = np.zeros(nclasses, dtype=np.int64)
for truth, pred in zip(y_true, y_pred):
if pred == truth:
correct[pred] += 1
else:
wrong[pred] += 1
tn, tp = correct
fn, fp = wrong
accuracy = (tn + tp) / len(y_true)
groups = np.array([(tn + fn), (tp + fp)])
supports = np.array([(tn + fp), (tp + fn)])
precisions = np.array([tn, tp]) / groups
recalls = np.array([tn, tp]) / supports
f1s = 2 * (precisions * recalls) / (precisions + recalls)
for arr in (precisions, recalls, f1s):
np.nan_to_num(arr, copy=False, nan=zero_division)
return tn, tp, fn, fp, accuracy, supports, precisions, recalls, f1sDescribe alternatives you've considered, if relevant
Can someone from original classification_report authors take a look please why it's taking so long?
Additional context
I have the latest versions of scikit-learn and numba to this date, an Intel CPU with AVX.
Activity
fingoldo commentedon Jul 9, 2023
I have actually improved it slightly to have more concise variable names & handle multiclasses. The only things of sklearn's classification report it does not support are micro,sample averages and sample weights (not hard to add them as well). As an extra it has balanced accuracy though.
print(fast_classification_report_numba(y_true=y_true, y_pred=y_pred, zero_division=0))%timeit fast_classification_report_numba(y_true=y_true, y_pred=y_pred, zero_division=0)adrinjalali commentedon Jul 10, 2023
Could you please do a profiling and show where in the
classification_reportmost of the time is spent? Then we can figure out what the best way improving it would be.fingoldo commentedon Jul 10, 2023
Well,
%lprun -f classification_report classification_report(y_true=...)points at line 184 in _param_validation.py for some reason.I don't know how to profile it correctly.
adrinjalali commentedon Jul 11, 2023
So it turns out the culprit is pretty much mostly numpy's
unique/unique_valueswhich does asort.There's an open issue here: numpy/numpy#11136 about that
Even pandas'
uniqueis twice as fast on even a bunch of random floats.Note that you can profile your script with
python -m cProfile -o script.prof script.pyand then visualize the results nicely withsnakeviz script.prof(needssnakevizinstalled available viapip)Looking at this table,
10.7sour of the14.4sare spent insort, and that's bad:We can maybe try to optimize the code, but the real fix would be to optimize numpy's
unique.@thomasjpfan was mentioning that pytorch doesn't sort on unique, so we might get that into numpy?
cc @rgommers
rgommers commentedon Jul 11, 2023
Agreed, adding a keyword to disable sorting to
numpy.unique& co would make sense to me.fingoldo commentedon Jul 11, 2023
Wow that's weird 'cause when I apply np.unique to either y_true or y_pred, it's never above 200 milliseconds on my 8M elements array.
Is it calling np. unique multiple times within one classification_report call, why would it do that?
Where are random floats coming from, we only have integer inputs, no?
What's making it even more sad is that I need to fit hundreds and thousands of models and then estimate their quality on a bunch of subsets like that, and I know there are only 2 classes possible 'cause it's a binary classification. Is there an option to pass nclasses directly to save on recomputing them each time?
adrinjalali commentedon Jul 11, 2023
@fingoldo sounds like it would be a win-win for everybody if you could invest some time optimizing these routines then ;)
This is definitely something which could use some optimization, but we might not have the bandwidth to get to it ATM. However, we'd appreciate your contributions.
fingoldo commentedon Jul 11, 2023
Great. Is optional numba allowed? Is optional passing nclasses directly allowed?
adrinjalali commentedon Jul 11, 2023
numba no, but passing optional n_classes makes sense.
fingoldo commentedon Jul 11, 2023
Wow. What's wrong with optional use of numba? Like, if it's installed on the user's system, it can speed up critical parts of our python/numpy code 10 to 100 times, which I have demonstrated above. Is there some general policy of not using numba in scikit-learn?
adrinjalali commentedon Jul 11, 2023
Adding dependencies to a project such as scikit-learn which has easily over 9M downloads a week is no light discussion, and numba brings a massive complexity with it. We rather use cython / C code to speed up things at this stage rather than depend on numba. It might be a better idea for you to have an in-house solution for your case instead of depending on sklearn tools in this particular case.
glemaitre commentedon Jul 11, 2023
In addition to @adrinjalali, we should also put into perspective the performance gain in regard to the full ML pipeline: the few seconds to evaluate the models are negligible in comparison to the training phase.
I don't mean that we should not have an efficient way to evaluate models but I would counter balanced it with the complexity involved. The optional
n_classesseems to be an already good approach to me to alleviate the issue.fingoldo commentedon Jul 11, 2023
Sure, I can use my custom code for now, just wanted the community to also benefit from my findings.
I looked at the source codes in more details and here's the ballpark outline of the time spent in classification_report:
params checking: 1.58 sec ( _check_targets(y_true, y_pred) +unique_labels(y_true, y_pred))
calling precision_recall_fscore_support with average=None: 3.78 sec
then calling the same precision_recall_fscore_support but for each of ('micro', 'macro', 'weighted') averages kind, which involves repeating all inner checks of precision_recall_fscore_support and computing the same multilabel_confusion_matrix again and again, that amounts to 11.3 seconds.
Can we please go with a very simple fix for start: make MCM an optional input and output parameter to the precision_recall_fscore_support function, and if it's provided as an input, naturally skip expensive steps of
labels = _check_set_wise_labels(y_true, y_pred, average, labels, pos_label)(1.56 sec)and
MCM = multilabel_confusion_matrix...(2.27 sec)each of the 3 additional times?
I guess it will already take away a lion's share of repetitive computing, if my math is correct it will reduce the report building time from 18 to like 5 seconds.
To address @glemaitre 's point, I indeed met the case when the model's training time is comparable to performance estimation time. It happened because I am using additional group-wise estimation, that is, I compute metrics not only for the whole set but also for 30 of its subgroups separately. I literally stuck at situation where quality estimation takes up to 5 minutes, and all that time the (quite costly) Dask cluster has to wait idle. Multiply it by the number of models I want to train (hundreds), and it becomes a substantial concern cost-wise.
Imho it's very important to have fast metrics implementations in sklearn 'cause it's a de facto gold standard in modern ML, and many 3rd party libs rely on it, for example, Catboost. Not only classification_report can be sped up, I also just had good results with roc_auc (x8 speedup over sklearn with numba and numpy).
Why it might be important, again, is for example 'cause Catboost does not yet have roc_auc GPU implementation and has to rely on CPU implementation (from sklearn, it seems, as their roc_auc timings are very comparable), and training implicitly often includes computing metrics regularly (it would be not fair to only count metrics evaluation as a post-training process, 'cause early stopping is used very often and it requires computing metrics regularly, i.e., hundreds and thousands of times per training cycle). On a big dataset that becomes a significant overhead if not implemented efficiently.
adrinjalali commentedon Jul 11, 2023
So I put up a draft PR for this, I'm not sure of the added public args or their names. Might require more refactoring, but this reduces the time from 15-16s to ~5s on my machine. PR: #26820
fingoldo commentedon Jul 11, 2023
Amazing! Might save a few more CPU cycles on keeping MCM as well, but already a great improvement, x3 times. Thanks a lot for your prompt and elegant work, Adrin. This thread was not in vain.
fingoldo commentedon Jul 25, 2023
I hope it gets merged. By the way, my friend wrote a pure Numpy implementation that computes the same quantities as my Numba fast_classification_report. It is not as fast, but still surpasses current sklearn's approach by a sensible margin. Maybe it could serve as a base for some future refactoring.