What is the difference between accuracy_score and clf.score in sklearn?

Viewed 400
from sklearn.svm import SVC
from sklearn.datasets import make_blobs
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
    
X, y = make_blobs(n_samples=500, n_features=2, centers=2, random_state=34)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
clf = SVC()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(clf.score(X_test, y_test) == accuracy_score(y_test, y_pred))

The output of the above code is:

True

I don't know the difference between them, can someone tell me?


Edit: The source code of the score function is:

def score(self, X, y, sample_weight=None):
    """
    Return the mean accuracy on the given test data and labels.
    In multi-label classification, this is the subset accuracy
    which is a harsh metric since you require for each sample that
    each label set be correctly predicted.
    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Test samples.
    y : array-like of shape (n_samples,) or (n_samples, n_outputs)
        True labels for `X`.
    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.
    Returns
    -------
    score : float
        Mean accuracy of ``self.predict(X)`` wrt. `y`.
    """
    from .metrics import accuracy_score

    return accuracy_score(y, self.predict(X), sample_weight=sample_weight)

i.e., the score function is implemented with accuracy_score function, so these two functions are the same?

1 Answers

clf.score() is actually for the SVC class, and it returns the mean accuracy on the given data and labels.

accuracy_score on the other hand returns a fraction of instances where classification was done correctly. For example, if you pass-in 10 items for classification, and say 7 of them are classified correctly (whatever is the clsss - True / False, Multiclass), its return value will be 0.7. You can set a flag normalize to False and then it will return just an integer of how many instances were classified correctly.

Related