liveBook · Manning

Toxicity score

As explained in Natural Language Processing in Action, Second Edition

A toxicity score is a scalar value representing the estimated degree to which a comment belongs to the toxic class.

A toxicity score is a scalar estimate of how strongly a comment resembles toxic comments. With TF–IDF vectors, project each comment onto the axis from the nontoxic centroid to the toxic centroid; larger projections indicate greater toxicity. section 4.2.1

A practical scoring workflow is:

  • Compute toxic and nontoxic centroids, then subtract them to form the toxicity axis. section 4.2.1
  • Calculate vectorized dot products between comment vectors and that axis. section 4.2.1
  • Normalize scores to 0–1 and classify comments above a chosen cutoff, such as 0.5. section 4.2.1

From score to prediction

A manually constructed score reached 89.5% accuracy on the messages, while full LDA reached 99.9% on training data but only 55.4% after a train/test split, revealing severe generalization limits.

>>> mask = comments.toxic.astype(bool).values    #1
>>> toxic_centroid = tfidf_docs[mask].mean(axis=0)    #2
>>> nontoxic_centroid = tfidf_docs[~mask].mean(axis=0)   #3
>>> centroid_axis = toxic_centroid - nontoxic_centroid
>>> toxicity_score = tfidf_docs.dot(centroid_axis)     #4
>>> toxicity_score.round(3)
array([-0.008, -0.022, -0.014, ..., -0.025, -0.001, -0.022])

Inspect the centroid axis and calculate all comment toxicity scores in one NumPy dot-product operation. section 4.2.1

How Natural Language Processing in Action, Second Edition covers it

How deep it goes
Explains centroid projections, normalization, cutoff selection, and generalization limits, then defers to full LDA internals.
Examples
Uses comment vectors, toxic and nontoxic centroids, normalized scores, confusion matrices, and train/test evaluation.
What it assumes
Assumes TF–IDF vectors and vector operations while deriving centroid projections and score normalization practically.
What you can do after
Build it from scratch with NumPy and scikit-learn, then evaluate predictions with accuracy and confusion matrices.
How it connects
Connects TF–IDF, cosine distance, centroids, dot products, binary classification, and linear discriminant analysis.

This explainer was generated by Manning's knowledge graph from the text of Natural Language Processing in Action, Second Edition. The section links point to the parts of the book it draws on.