Testing Classification Accuracy

[TOC]

Evaluating the predictive accuracy of the model is equally easy. We use the held-out test reviews from reviews_test and NumPy (np.mean) to calculate the proportion of correct predictions:

import numpy as np
predicted = text_clf.predict(reviews_test)
np.mean(predicted == labels_test)

The accuracy score will vary depending on the model and the train/test split.

Train and Test a Support Vector Machine

While Naïve Bayes treats every word as independent, linear support vector machines (SVMs) optimize a decision hyperplane across all features simultaneously and are widely regarded as one of the best text classification algorithms. We can change the learner by simply plugging a different classifier object into our pipeline. (SGDClassifier with loss='hinge' trains a linear SVM.)

from sklearn.linear_model import SGDClassifier
text_clf = Pipeline([
    ('vect', CountVectorizer()),
    ('tfidf', TfidfTransformer()),
    ('clf', SGDClassifier(loss='hinge', penalty='l2',
                          alpha=1e-3, random_state=42,
                          max_iter=5, tol=None)),
 ])

text_clf.fit(reviews_train, labels_train)

Response:
Pipeline(…)

predicted = text_clf.predict(reviews_test)
np.mean(predicted == labels_test)

The accuracy score will vary depending on the model and the train/test split.

Classification Report

scikit-learn provides further utilities for more detailed performance analysis of the results:

from sklearn import metrics
print(metrics.classification_report(labels_test, predicted,
     labels=target_names, target_names=target_names))

The columns are showing the following:

Confusion Matrix

metrics.confusion_matrix(labels_test, predicted, labels=target_names)

The confusion matrix1 is arranged as follows:

The matrix values show how many reviews of each actual class were assigned to each predicted class. These values depend on the model and train/test split.

Inspecting the Most Predictive Features

One major advantage of linear classifiers like SGDClassifier is interpretability. The learned weight array text_clf.named_steps['clf'].coef_[0] contains one weight per word in the vocabulary. Since the classes are ordered alphabetically, negative weights push predictions toward deceptive and positive weights push predictions toward truthful. We can use np.argsort to inspect the top 10 words for each class:

feature_names = text_clf.named_steps['vect'].get_feature_names_out()
weights = text_clf.named_steps['clf'].coef_[0]

print("Top 10 indicators of DECEPTIVE reviews:")
print(feature_names[np.argsort(weights)[:10]])

print("\nTop 10 indicators of TRUTHFUL reviews:")
print(feature_names[np.argsort(weights)[-10:][::-1]])

The most predictive words can vary with the training data and split. Often, truthful indicators are concrete, spatial, and transactional (such as floor numbers or rates), whereas deceptive indicators may include personal pronouns, vague narratives, and superlatives.


Creative Commons License AI Programming 1 Course Materials by Brian Bird, written in are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

  1. A confusion matrix is a table used to evaluate the performance of a classification model on a set of test data for which the true values are known. It visually summarizes the classifier’s performance by comparing the predicted categories to the actual categories. ↩