Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
In scikit-learn, accuracy_score(y_true, y_pred) from sklearn.metrics returns the fraction of samples whose predicted label exactly matches the true label, a float between 0.0 and 1.0 where 1.0 is best. Pass the true labels first and the predicted labels second; set normalize=False to get the count of correct samples instead of the fraction. The same function is what people also search for as “accuracy score sklearn”, and this guide shows its syntax, each argument, a worked example on an imbalanced label set with real output, and the errors you are most likely to meet.
What accuracy_score is used for in research
Accuracy is the simplest summary of a classifier: out of all samples, how many did the model label correctly. The scikit-learn user guide defines it as the average, over n samples, of an indicator that is 1 when the predicted label ŷi equals the true label yi and 0 otherwise. In research it appears in methods and results sections as a headline figure for a classification model, as the default way a classifier’s score method is reported, and as the scoring target in model selection.
Two points from the official documentation shape how you should use it. First, the user guide states that the scoring string 'accuracy' maps to metrics.accuracy_score, so the metric you compute by hand and the one used inside cross-validation are the same function. Second, accuracy counts every correct prediction equally, which is exactly why it can mislead when one class dominates; the worked example below shows a model that scores 0.9 while finding none of the cases of interest. For a deeper look at the error types behind a single number, see our guide to the scikit-learn confusion matrix, and for the wider workflow see the scikit-learn tutorial.
How to install or access it
accuracy_score ships with scikit-learn, so there is nothing separate to install. The official installation page (current stable release 1.9.1 when read) describes two routes. With pip, create and activate a virtual environment, then install:
python -m venv sklearn-env
source sklearn-env/bin/activate
pip install -U scikit-learn
On Windows the activation command is sklearn-envScriptsactivate. With conda, use the conda-forge channel:
conda create -n sklearn-env -c conda-forge scikit-learn
conda activate sklearn-env
Check the installation with python -c "import sklearn; sklearn.show_versions()", which prints the installed scikit-learn version and its dependencies. Record that version in your methods section: the behaviour described here is that of the 1.9.1 documentation, and quoting the version you ran keeps your result reproducible.
Step-by-step: compute accuracy with accuracy_score
The signature in the 1.9.1 API reference is accuracy_score(y_true, y_pred, *, normalize=True, sample_weight=None). The bare * means normalize and sample_weight must be passed by keyword.
- Import the function.
from sklearn.metrics import accuracy_score - Get predictions from a fitted model. Call
y_pred = model.predict(X_test)on data the model did not train on. The documentation describesy_predas the predicted labels as returned by a classifier, not probabilities or scores. - Call the metric with the true labels first.
accuracy_score(y_true, y_pred). Ground-truth labels come first, predictions second. - Choose fraction or count. Leave
normalize=Truefor a fraction, or passnormalize=Falsefor the number of correctly classified samples. - Optionally weight samples. Pass
sample_weightas an array of shape (n_samples,) to count some samples more than others. - Report it with the sample size. A fraction such as 0.94 means little without the number of test samples behind it.
Arguments in detail
y_true and y_pred are either 1d array-likes of labels or label indicator arrays (multilabel). The documentation notes that a sparse matrix is supported only when the labels are of multilabel type. Labels need not be numbers: string labels such as "cat" and "dog" work, as the examples later show. normalize is a bool defaulting to True. sample_weight defaults to None, meaning every sample counts equally. The return value is a float; with normalize=True its best value is 1.0, and with normalize=False its best value is the number of samples.
Worked example: why accuracy can look good while the model fails
The following example is an illustrative composite built from synthetic labels, not data from any study: 100 test samples, of which 90 belong to class 0 (the common outcome) and 10 to class 1 (the outcome of interest). It was run with scikit-learn 1.9.1.
from sklearn.metrics import accuracy_score, balanced_accuracy_score
y_true = [0]*90 + [1]*10
# Model A: predicts class 0 for every sample
y_pred_a = [0]*100
print(accuracy_score(y_true, y_pred_a)) # 0.9
print(balanced_accuracy_score(y_true, y_pred_a)) # 0.5
# Model B: 2 false positives, 6 true positives, 4 false negatives
y_pred_b = [0]*88 + [1]*2 + [1]*6 + [0]*4
print(accuracy_score(y_true, y_pred_b)) # 0.94
print(accuracy_score(y_true, y_pred_b, normalize=False)) # 94.0
print(balanced_accuracy_score(y_true, y_pred_b)) # 0.7888888888888889
Model A never detects a single positive case yet reports an accuracy of 0.9, because 90 of 100 samples are class 0. Model B finds 6 of the 10 positives and reaches 0.94. Accuracy ranks B above A, but the gap understates the difference in what the models can do: balanced accuracy moves from 0.5 to about 0.79. The scikit-learn user guide defines balanced accuracy as the macro-average of recall over classes, notes that it equals accuracy on balanced data, and describes the chance-level case as 1/n_classes. In the binary case it is the mean of sensitivity, TP/(TP+FN), and specificity, TN/(TN+FP); for Model B that is (88/90 + 6/10)/2.
Practical consequence for a results section: when classes are imbalanced, report accuracy together with per-class measures, or with balanced accuracy, and give the class counts. A single accuracy figure on its own invites exactly the misreading Model A demonstrates. Resampling before training is another common response; check that any resampling happens only inside the training data.
Output and how to read it
accuracy_score returns a plain float. Read it as “the share of test samples classified exactly right”. Using the four-sample example from the official API reference (y_true = [0, 1, 2, 3], y_pred = [0, 2, 1, 3]), two of four predictions match, so the result is 0.5 and, with normalize=False, 2.0. The data table below compares what the function returns for each argument setting, each row verified by running the call.
Multilabel input: subset accuracy
For multilabel data the documentation says the function computes subset accuracy: the predicted set of labels for a sample must exactly match the corresponding true set. A sample with one of two labels wrong counts as entirely wrong. The reference example, accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2))), returns 0.5, because only the second row matches exactly. If partial credit is what you want, the See Also list in the documentation points to hamming_loss and jaccard_score.
Weighted samples
With sample_weight=[1, 1, 1, 3] on the four-sample example, the correct samples are the first (weight 1) and the last (weight 3), so the result is (1 + 3) / 6 = 0.6667 rather than 0.5. Weights are useful when test samples represent unequal numbers of real units; state the weighting scheme when you report the figure.
Accuracy inside cross-validation and grid search
The user guide states that accuracy is the default score for classifiers and that scorers follow the convention that higher is better. In cross_val_score or a search object you refer to it by the string 'accuracy'. Each fold returns its own accuracy, so report the mean and the spread across folds rather than one number. For the evaluation design itself, see cross-validation in statistics, and for tuning with an accuracy scorer see scikit-learn GridSearchCV. If you pass an invalid scoring name, scikit-learn raises an InvalidParameterError, and sklearn.metrics.get_scorer_names() lists the valid names.
Troubleshooting common errors
ValueError: inconsistent numbers of samples
Calling accuracy_score([0, 1, 2], [0, 1]) in 1.9.1 raised ValueError: Found input variables with inconsistent numbers of samples: [3, 2]. The two arrays must have the same length; check that predictions were made on the same rows as the labels, for example after any filtering or train-test split.
ValueError: mix of continuous and binary targets
Passing continuous values as one argument, such as accuracy_score([0.5, 1.2], [0, 1]), raised ValueError: Classification metrics can't handle a mix of continuous and binary targets. Accuracy is a classification metric: convert probabilities to labels first (for example with predict rather than predict_proba), or use a regression metric if your target is a continuous quantity.
Swapped arguments
For the plain accuracy score the result is the same if you swap the two arguments, because it only counts matches. The habit still matters: the documentation names the first argument y_true, and many other metrics in sklearn.metrics are not symmetric, so keep one consistent order.
TypeError when passing normalize or sample_weight positionally
Because the signature contains a bare *, write normalize=False and sample_weight=... as keyword arguments.
Related metrics in scikit-learn
scikit-learn is free, open-source software, so the practical alternatives to accuracy_score are the sibling functions in the same module. The API reference lists these under See Also, with its own one-line descriptions:
| Function | What the documentation says it computes |
|---|---|
balanced_accuracy_score |
Balanced accuracy, to deal with imbalanced datasets |
jaccard_score |
The Jaccard similarity coefficient score |
hamming_loss |
The average Hamming loss or Hamming distance between two sets of samples |
zero_one_loss |
The zero-one classification loss; by default it returns the percentage of imperfectly predicted subsets |
The model evaluation chapter of the user guide places all of these, together with precision, recall and the confusion matrix, in one metrics toolbox, which is the right place to decide which numbers your study needs.
Frequently asked questions
What does sklearn accuracy_score return?
A float: the fraction of correctly classified samples when normalize=True (the default), or the number of correctly classified samples when normalize=False. The best value is 1.0 or the sample count respectively.
Is accuracy score sklearn the same as the ‘accuracy’ scorer?
Yes. The scikit-learn user guide maps the scoring string 'accuracy' to metrics.accuracy_score, and accuracy is the default score for classifiers.
How is accuracy_score different from balanced_accuracy_score?
Accuracy counts all samples equally; balanced accuracy is the macro-average of per-class recall. On balanced data they match, on imbalanced data they can differ widely, as in the 0.9 versus 0.5 example above.
How does accuracy_score handle multilabel data?
It computes subset accuracy: a sample is correct only if its whole predicted label set exactly matches the true set.
Can I use accuracy_score for regression?
No. It is a classification metric and raises a ValueError when given continuous targets mixed with class labels.
Sources
- scikit-learn developers, sklearn.metrics.accuracy_score (API reference, version 1.9.1), read 2026-11-15.
- scikit-learn developers, Metrics and scoring: quantifying the quality of predictions (user guide), read 2026-11-15.
- scikit-learn developers, Installing scikit-learn, read 2026-11-15.
- Outputs and error messages in the worked example and troubleshooting sections were produced by running the code with scikit-learn 1.9.1 on 2026-11-15.
Data: accuracy_score return values by argument setting (scikit-learn 1.9.1)
Return value of sklearn.metrics.accuracy_score for different argument settings and input types, compiled by running each call under scikit-learn 1.9.1 and checking the behaviour against the official API reference and user guide.
Period covered: scikit-learn 1.9.1.
| Call | Input | Result | Documented behaviour |
|---|---|---|---|
| accuracy_score(y_true, y_pred) | y_true=[0,1,2,3], y_pred=[0,2,1,3] | 0.5 | Fraction of correctly classified samples (normalize=True) |
| accuracy_score(y_true, y_pred, normalize=False) | y_true=[0,1,2,3], y_pred=[0,2,1,3] | 2 | Number of correctly classified samples |
| accuracy_score(y_true, y_pred, sample_weight=[1,1,1,3]) | y_true=[0,1,2,3], y_pred=[0,2,1,3] | 0.6667 | Weighted fraction: (1+3)/6 |
| accuracy_score(y_true, y_pred) | Multilabel: [[0,1],[1,1]] vs all ones | 0.5 | Subset accuracy: label set must match exactly |
| accuracy_score(y_true, y_pred) | String labels: cat,dog,dog vs cat,dog,cat | 0.6667 | Labels need not be numeric |
| accuracy_score(y_true, y_pred) | 90 class 0 and 10 class 1, all predicted 0 | 0.9 | Accuracy counts every sample equally |
| balanced_accuracy_score(y_true, y_pred) | Same imbalanced set, all predicted 0 | 0.5 | Macro-average of per-class recall |
| accuracy_score(y_true, y_pred) | Lengths 3 and 2 | ValueError: inconsistent numbers of samples | Both arrays must be the same length |
| accuracy_score(y_true, y_pred) | Continuous y_true [0.5,1.2], y_pred [0,1] | ValueError: mix of continuous and binary targets | Classification metric; labels required |
Sources
- sklearn.metrics.accuracy_score (scikit-learn 1.9.1) (accessed 2026-11-15)
- Metrics and scoring: quantifying the quality of predictions (accessed 2026-11-15)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







