Twitter (X) Hate Speech Detection in Python: Models, Thresholds and a Real Reply Study

- Two models, two questions:
cardiffnlp/twitter-roberta-base-hate-latestasks "is this hate?" and flagged 4.1% of 736 replies at 0.5;unitary/toxic-bertasks "is this toxic?" and flagged 15.5%. - A human read changes the picture: of the 30 replies the hate model flagged, 5 targeted a protected group, 17 were insults or profanity, 8 were false hits (26.7%).
- Context drives the rate: replies under news posts from @BBCWorld were flagged by the hate model at 10.0%, replies under @NASA at 0.0%.
- Swearing is not hate: among the 114 toxic replies,
obscenefired on 59.6% andidentity_hateon only 6.1%. - Thresholds barely move the hate model: 93.9% of replies score under 0.1, so going from 0.5 to 0.9 only drops flags from 30 to 18.
- Cost: reads are $0.15 per 1,000 tweets (15 credits each); the official X API lists $0.005 per post read, about 33x more. Scoring runs free on a laptop CPU.
This page is about hate and toxicity flags, not feelings. Twitter emotion analysis asks which emotions a post carries (anger, joy, fear) and Twitter sentiment analysis asks whether it is positive or negative; an angry post is not hate speech, and a calm one can be. Hate speech detection asks a narrower question with higher stakes: does this text attack people for who they are? That narrowness is exactly why off-the-shelf models get it wrong so often, and why this guide spends as long on the review step as on the code.
You will build the whole pipeline in Python: pull the public replies under organization posts through the TwitterAPI.io REST endpoints (no X account needed for reads), clean the text, score it with two open classifiers from Hugging Face, choose a threshold, and route the flags to a reviewer. Every number on this page comes from one real run: 736 English replies under recent posts from five large organization accounts, collected in 2026, scored on a laptop CPU. We never quote, show or link a flagged reply; the page reports only aggregate shares, and a score is the model's output, not a judgment of the person who wrote the post.
5 of 30 (16.7%). The hate model flagged 4.1% of 736 replies under NASA, NFL, BBCWorld, Xbox and NBA posts (collected in 2026); 56.7% of its flags were insults or profanity and 26.7% false hits.
What Twitter hate speech detection actually measures
Hate speech is a policy term before it is a machine learning label. X's own rules (the Hateful Conduct policy at help.x.com/en/rules-and-policies/hateful-conduct-policy) say you may not directly attack other people on the basis of race, ethnicity, national origin, caste, sexual orientation, gender, gender identity, religious affiliation, age, disability, or serious disease. The key ideas are an attack and a protected characteristic. A post that swears at a football team, insults a politician, or mocks a video game is rude, but under that definition it is not hate speech.
Classifiers encode whatever definition their training data used, and those definitions differ. The Davidson et al. dataset (about 24,800 tweets, three classes: hate speech, offensive language, neither) was built precisely because its authors found that offensive language and hate speech were being lumped together. The Jigsaw Toxic Comment data behind toxic-bert labels Wikipedia comments as toxic, severe toxic, obscene, threat, insult or identity hate. A hate model and a toxicity model will therefore disagree on the same reply, and both are right according to their own training labels.
Practical consequence. Decide what you are trying to find before you pick a model. If the goal is policy-style hate (attacks on protected groups), a dedicated hate model plus a human reviewer fits. If the goal is a civility metric for a community (how much swearing and abuse lands under your posts), a toxicity model fits better. If you need both, run both and keep the sub-labels, which is what the study below does.
What this is not. A model score cannot tell you whether a post breaks X's rules, whether X will act on it, or anything about the author's intent. X enforces its own policy; a third-party classifier only ranks text for a human to look at.
The two open models we ran, and what their model cards say
Both models are free to download from Hugging Face and run on CPU. We picked them because they are widely used by practitioners for tweets and comments, they have model cards that state training data and license, and they answer different questions.
The hate model. The Cardiff NLP card reports an overall accuracy of 0.8766 and macro-F1 of 0.7531 across its 13 test sets, but the spread is wide: on the SemEval-2019 hatEval set the same model scores 0.5831 accuracy and 0.5646 macro-F1. That spread is the honest headline: a hate model's quality depends heavily on whose definition of hate the test set uses. It is a fine-tune of twitter-roberta-base-2022-154m, a RoBERTa model pre-trained on tweets, so it handles hashtags, emoji and Twitter slang better than a generic model.
The toxicity model. The Detoxify card reports 0.98636 on the Jigsaw challenge metric (the top Kaggle score was 0.98856). Its own caveat is the one that matters here: comments containing swearing or insults are likely to be classified as toxic regardless of the tone or intent of the author, and the card warns this "could present some biases towards already vulnerable minority groups." It also notes that the Hugging Face copy can give different results from the detoxify pip package. We used the Hugging Face copy, with a sigmoid per label, so every label scores on its own.
Not covered here. Large language models and hosted moderation APIs can also label text. We stayed with two open models you can run locally so the whole pipeline, including the reply text, never leaves your machine; that matters when the input is other people's posts.
Both models ran through the transformers text-classification pipeline on CPU with a batch size of 32. On a laptop CPU the hate model scored about 79.4 replies per second and toxic-bert about 80.5, so a few thousand replies take under a minute and no GPU is needed for this scale.
Keep every score. Store the raw HATE probability and all six toxicity probabilities, not just a yes/no flag. You will want to re-threshold later, and the toxicity sub-labels (obscene versus identity_hate) are the fastest way to see why a reply was flagged without re-reading it.
Use sigmoid for toxic-bert. Its six labels are independent (a reply can be obscene and an insult at once), so apply a sigmoid per label rather than a softmax across them. The hate model is a two-class softmax, so its HATE and NOT-HATE scores add up to 1.
from transformers import pipeline
hate = pipeline("text-classification",
model="cardiffnlp/twitter-roberta-base-hate-latest",
top_k=None, truncation=True) # softmax over HATE / NOT-HATE
tox = pipeline("text-classification",
model="unitary/toxic-bert",
top_k=None, function_to_apply="sigmoid", # 6 independent labels
truncation=True)
texts = [clean(t["text"]) for t in replies_en]
for h, x in zip(hate(texts, batch_size=32), tox(texts, batch_size=32)):
hate_score = {d["label"]: d["score"] for d in h}["HATE"]
tox_scores = {d["label"]: d["score"] for d in x} # toxic, severe_toxic, obscene,
# threat, insult, identity_hate - keep all six, the sub-labels explain the flagCollecting the replies: a neutral, account-anchored sample
Where you sample decides what you find. Searching for slurs or for a hot political hashtag gives you a sample designed to be hateful, which inflates every rate and puts private individuals at the center. We anchored the study on organization accounts instead: for each of @NASA, @NFL, @BBCWorld and @Xbox we read the account's latest 20 posts with /twitter/user/last_tweets, took the 3 original posts with the largest reply counts, and pulled up to 4 pages of replies for each with /twitter/tweet/replies. @NBA was added with its top 2 posts after the first pass returned fewer English replies than planned.
The replies endpoint returns a top-level tweets[] array with has_next_page and next_cursor, up to 20 replies per page, and each reply carries lang, text, createdAt and an author object. We dropped the account's own replies, kept lang = en, and replaced URLs and @handles with placeholders before scoring, which is also the preprocessing the Cardiff models expect.
What came back. The 50 requests returned 1,001 tweets, of which 901 were unique replies. 753 were tagged English; 59 were tagged qme (media or emoji only, no words to score) and 20 und. After cleaning, 736 English replies had text left to classify. Expect the same leak in your own pipeline: on popular posts a noticeable share of replies are images, GIFs or bare mentions.
If you prefer a keyword sample, /twitter/tweet/advanced_search with a neutral topic query works the same way (top-level tweets[], cursor paging). Keep the query neutral, keep the raw pages private, and report aggregates.
def replies(tweet_id, pages=4):
cursor, out = "", []
for _ in range(pages):
params = {"tweetId": tweet_id}
if cursor:
params["cursor"] = cursor
r = requests.get("https://api.twitterapi.io/twitter/tweet/replies",
headers={"X-API-Key": KEY}, params=params, timeout=30)
page = r.json()
out.extend(page.get("tweets", [])) # replies sit in a top-level tweets[] array
if not page.get("has_next_page"):
break
cursor = page.get("next_cursor", "")
return outResults: what each model flagged, by threshold and by account
The headline gap is between the models. At the usual 0.5 cut-off the hate model flagged 30 of 736 replies (4.1%) and toxic-bert flagged 114 (15.5%), almost four times as many. Toxic-bert's own identity_hate label, the closest thing it has to hate speech, fired on just 7 replies (1.0%).
Context matters more than the threshold. Replies under @BBCWorld news posts (a story on Russian sabotage claims, a South African election story and a testimony story) were flagged by the hate model at 10.0% and by toxic-bert at 22.7%. Replies under @NASA were flagged at 0.0% and 5.6%. Sports and gaming sat in between on toxicity (12.4% for @NFL, 13.6% for @Xbox) but near zero on hate (0.4% and 0.9%): fans swear a lot and rarely attack groups. The @NBA sample is small (27 replies), so treat its 7.4% as noise-prone.
Overlap. At 0.5, 19 replies were flagged by both models (2.6%), 11 by the hate model only (1.5%) and 95 by toxic-bert only (12.9%); 83.0% passed both. The hate-only replies are the interesting ones: hostile statements about a group with no swear words, which a profanity-sensitive toxicity model scores low.

The false-positive problem: a manual read of every hate flag
A flag rate means little until someone reads the flags. We read all 30 replies the hate model scored at 0.5 or above (the lowest was 0.508) and put each in one of three buckets: an attack on people for a protected characteristic (race, ethnicity, national origin, religion, sex, sexual orientation), an insult, profanity or personal attack with no protected group, or a false hit with no attack at all. One reviewer, one pass; the texts stay out of this page and out of our repository.
Reading the buckets. The 5 true positives used a slur or dehumanizing language about a racial, religious, national or gender group, or about sexual orientation. The 17 insults were aimed at one named person, a broadcaster or a government: gendered swear words, name-calling, accusations about someone's family history. They are abusive, but under X's definition they are harassment or incivility rather than hateful conduct. The 8 false hits were political complaints, sports trash talk and one all-caps post about housing, scored high because they named a country, a group or a conflict.
Why it happens. Hate datasets are full of posts that mention groups, nationalities and wars, so a model learns that those words predict the HATE label. Under news posts about geopolitics, ordinary angry commentary mentions exactly those words. The opposite error also exists: coded or sarcastic hate with no identity term scores low. Hard cases that dataset authors and moderators commonly point to are reclaimed slurs used inside a community, quotes of someone else's hate in order to condemn it, and counter-speech; all three contain the trigger words and none is an attack.
What to do about it. Never act on a score alone. Use the model to rank, and put a person on everything above your threshold. If you publish rates (for research or a dashboard), publish the reviewed rate next to the raw one, and say who reviewed and how.

Choosing a threshold and building the review queue
The hate model is confident in both directions: 691 of 736 replies (93.9%) scored under 0.1 and 18 scored 0.9 or more, with only 10 in the 0.3 to 0.7 band. Moving the threshold therefore changes little: from 0.5 to 0.9 the hate flags only drop from 30 to 18. Toxic-bert behaves the same way (74 replies at 0.9 or more out of 114 flagged at 0.5).
Pick the threshold from your review budget, not from the model. If a reviewer can read 50 replies a day, set the cut-off so the daily queue is about 50. A lower threshold catches more true positives at the cost of reading more false ones; a higher one saves time but our manual read shows high scores were still wrong or off-target in the majority of cases, so it buys precision on paper only.
Order the queue by evidence. Sort by the hate score, show the toxic-bert sub-labels next to each item (identity_hate high and obscene low points at group-directed language; obscene high and identity_hate low points at swearing), and record the reviewer's bucket. After a few hundred reviews you have a labeled set from your own domain, which is worth more than any public benchmark for tuning the threshold or fine-tuning a model.
Handle the data with care. The review queue contains other people's words. Keep it private, delete it once reviewed, and store only the scores and the reviewer's bucket, as we did with sample.json in this study (account, scores and length; no id, text or handle).
Twitter hate speech datasets for training and evaluation
The "twitter hate speech dataset" query usually means one of the labeled corpora the models above were trained or tested on. Three are worth knowing; check each card's license and terms yourself before you redistribute anything.
Watch the license fields. The Davidson card's text says MIT while its metadata says unknown, and it notes usernames are not anonymized. Older tweet datasets are often shared as IDs only, because X's terms restrict redistributing full post text; to use them you rehydrate the IDs. /twitter/tweets takes up to 50 comma-separated IDs per call and returns the posts that still exist, so expect deleted and suspended posts to drop out, a known source of bias in old hate datasets.
Build your own evaluation set. Public benchmarks age, and the Cardiff card's 0.58 to 0.99 accuracy range across datasets shows how much a domain shift costs. A few hundred replies from your own target accounts, labeled by your reviewers with the three buckets above, is the evaluation set that predicts how the model will behave on your data.
What the study costs, and how it compares to the official X API
The study made 50 requests (5 timeline pages and 45 reply pages) and returned 1,001 tweets. TwitterAPI.io bills tweet endpoints at 15 credits per tweet returned, which is $0.15 per 1,000 tweets, with a minimum of 15 credits per request; a full 20-tweet page costs $0.003. The whole collection cost $0.15. Scoring is free: both models run locally.
The official rates come from the X API pricing page (docs.x.com/x-api/getting-started/pricing): $0.005 per post read and $0.010 per user read on pay-per-usage, capped at 3 million post reads per billing cycle with Enterprise above that. Per 1,000 tweets that is about 33x the TwitterAPI.io rate. Reads on TwitterAPI.io need no X account and no developer approval; new accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days), and paid plans start with Starter at $29 a month. See pricing for current amounts.
Rate limits. Accounts get 0.2 requests per second before the first payment and 20 once paid, so a scan of a few thousand replies runs in minutes on a paid account. At the free rate, keep the page count small or schedule the scan.
How we collected this
Question. What share of public replies under large organization posts do an open hate model and an open toxicity model flag at 0.5, 0.7 and 0.9, how do they overlap, and how many hate flags hold up under a manual read?
Accounts. @NASA, @NFL, @BBCWorld and @Xbox (3 top-replied recent posts each) and @NBA (2 posts). Replies via /twitter/tweet/replies, up to 4 pages per post, after reading each account's latest posts with /twitter/user/last_tweets.
Window and size. Replies returned at collection time, collected in 2026. 901 unique replies, 736 English replies with text scored; 50 requests, $0.15.
Method. URLs and handles replaced with placeholders; scored on CPU with cardiffnlp/twitter-roberta-base-hate-latest (softmax) and unitary/toxic-bert (sigmoid per label) through transformers. One reviewer read all 30 hate flags and assigned one of three buckets. The protocol, analysis script, chart script, aggregate results and de-identified per-reply scores are in our repository under data/studies/twitter-hate-speech-detection/.
What the sample cannot show. Twelve posts from five accounts are not Twitter as a whole; the replies a single news story attracts depend on the story. Reply pages are what the endpoint returned, not every reply. The manual read is one person's judgment on 30 items, enough to show the false-positive problem, not to estimate precision tightly. We did not measure recall (hate the models missed).
Privacy. Aggregates only. Reply authors are private individuals: raw reply pages stayed on a local machine and were deleted after analysis, and no reply is quoted, paraphrased individually or linked. Model scores describe text, not people.
"""hate_scan.py - score the replies under public posts with an open hate-speech model.
pip install requests transformers torch
export TWITTERAPI_KEY=... (from your TwitterAPI.io dashboard)
python hate_scan.py NASA BBCWorld
"""
import os
import re
import sys
import time
from collections import Counter
import requests
from transformers import pipeline
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_KEY"]}
HATE_MODEL = "cardiffnlp/twitter-roberta-base-hate-latest"
THRESHOLDS = (0.5, 0.7, 0.9)
POSTS_PER_ACCOUNT = 3
PAGES_PER_POST = 4
def get(url, params):
for attempt in range(4):
r = requests.get(url, headers=HEADERS, params=params, timeout=30)
if r.status_code in (429, 503):
time.sleep(60) # fixed back-off, then retry
continue
r.raise_for_status()
return r.json()
raise RuntimeError(f"giving up on {url}")
def top_posts(account):
"""The account's own recent posts with the largest reply counts."""
data = get(f"{BASE}/twitter/user/last_tweets", {"userName": account})
tweets = data.get("data", {}).get("tweets", [])
originals = [t for t in tweets if not t.get("retweeted_tweet") and not t.get("isReply")]
originals.sort(key=lambda t: t.get("replyCount", 0), reverse=True)
return originals[:POSTS_PER_ACCOUNT]
def replies(tweet_id):
cursor, out = "", []
for _ in range(PAGES_PER_POST):
params = {"tweetId": tweet_id}
if cursor:
params["cursor"] = cursor
page = get(f"{BASE}/twitter/tweet/replies", params)
out.extend(page.get("tweets", []))
if not page.get("has_next_page"):
break
cursor = page.get("next_cursor", "")
time.sleep(0.25) # fixed pacing
return out
def clean(text):
text = re.sub(r"https?://\S+", "http", text)
text = re.sub(r"@\w+", "@user", text)
return re.sub(r"\s+", " ", text).strip()
def main(accounts):
rows, seen = [], set()
for account in accounts:
for post in top_posts(account):
for t in replies(post["id"]):
if t["id"] in seen or t.get("lang") != "en":
continue
if t["author"]["userName"].lower() == account.lower():
continue # skip the account's own replies
seen.add(t["id"])
text = clean(t["text"])
if re.sub(r"@user|http", "", text).strip():
rows.append((account, text))
print(f"{len(rows)} English replies with text")
clf = pipeline("text-classification", model=HATE_MODEL, top_k=None, truncation=True)
scores = []
for result in clf([text for _, text in rows], batch_size=32):
by_label = {d["label"]: d["score"] for d in result}
scores.append(by_label.get("HATE", 0.0))
for th in THRESHOLDS:
flagged = Counter(acc for (acc, _), s in zip(rows, scores) if s >= th)
total = Counter(acc for acc, _ in rows)
share = {a: f"{100 * flagged[a] / total[a]:.1f}%" for a in total}
print(f"threshold {th}: {sum(flagged.values())} flagged, by account {share}")
# Queue the flags for a human reviewer; keep this file private and delete it after review.
queue = sorted(zip(scores, rows), reverse=True)
with open("review_queue.tsv", "w") as f:
for s, (acc, text) in queue:
if s >= THRESHOLDS[0]:
f.write(f"{s:.3f}\t{acc}\t{text}\n")
if __name__ == "__main__":
main(sys.argv[1:] or ["NASA"])
Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
What is the best model for Twitter hate speech detection in Python?
There is no single right answer; it depends on your definition. For policy-style hate (attacks on protected groups) a tweet-trained binary model such as cardiffnlp/twitter-roberta-base-hate-latest (CC BY 4.0) is a common starting point. For a general abuse or civility measure, unitary/toxic-bert (Apache 2.0) gives six labels including insult and identity_hate. Running both and keeping all scores, as in this guide, shows you which kind of language you are actually catching.
How accurate are hate speech classifiers on tweets?
Less accurate than benchmark numbers suggest. The Cardiff model card reports 0.8766 overall accuracy but 0.5831 on the hatEval test set. In our own run, only 5 of the 30 replies the hate model flagged targeted a protected group on a human read. Use scores to rank posts for review, never as a final decision.
Is there a Twitter hate speech dataset I can download?
Yes. The Davidson et al. set (about 24,800 tweets labeled hate speech, offensive language or neither) is on Hugging Face as tdavidson/hate_speech_offensive, and the Cardiff model card lists the 13 datasets it was trained on, including SemEval-2019 hatEval. Check each license, and note that many tweet datasets ship IDs only; rehydrate them with /twitter/tweets (up to 50 IDs per call).
What is the difference between hate speech and toxic or offensive language?
Hate speech attacks people because of a protected characteristic such as race, religion, national origin, gender or sexual orientation. Toxic or offensive language covers swearing, insults and rudeness in general. In our study toxic-bert flagged 15.5% of replies while its identity_hate label fired on 1.0%: the large majority of toxic replies were obscene or insulting, not hateful in the policy sense.
What does X's hateful conduct policy prohibit?
Per X's Hateful Conduct policy page (help.x.com/en/rules-and-policies/hateful-conduct-policy), you may not directly attack other people on the basis of race, ethnicity, national origin, caste, sexual orientation, gender, gender identity, religious affiliation, age, disability, or serious disease. X enforces that policy itself; a third-party model score says nothing about whether X will act.
Which threshold should I use to flag hateful tweets?
Start at 0.5 and adjust to your review capacity. Hate scores cluster near 0 and 1 (93.9% of our replies scored under 0.1), so moving from 0.5 to 0.9 only cut flags from 30 to 18. High-scoring flags were still often insults or false hits, so a higher threshold does not remove the need for a human reviewer.
How much does it cost to collect tweets for hate speech research?
On TwitterAPI.io tweet endpoints cost $0.15 per 1,000 tweets returned (15 credits each, minimum 15 credits per request), so this study's 1,001 tweets cost $0.15. The official X API lists $0.005 per post read, $5.00 per 1,000. Reads need no X account; see /pricing for plans and the free starter credits.
Can I use these models to moderate or report accounts automatically?
Not responsibly. The model cards themselves warn about bias (Detoxify notes possible bias against vulnerable minority groups), and our manual read found a majority of high-scoring flags were not hate. Use the scores to prioritize human review, keep the raw text private, and never treat a score as a judgment of a person.
Continue
- Hugging Face model card: cardiffnlp/twitter-roberta-base-hate-latest (training sets, per-dataset scores, CC BY 4.0)
- Hugging Face model card: unitary/toxic-bert, Detoxify original (labels, Jigsaw score, limitations, Apache 2.0)
- Davidson et al. hate speech and offensive language dataset card
- X Help Center: Hateful Conduct policy
- X API pricing (pay-per-usage rates)
- TwitterAPI.io API reference (tweet replies, user last tweets)
- X (Twitter) API overview and endpoints
- Twitter emotion analysis in Python with open models
- Twitter sentiment analysis guide
- Detecting fake news on Twitter (X)
- How Community Notes work on X
- Twitter API for academic research
- TwitterAPI.io pricing per 1,000 tweets
- 01Twitter (X) Fake News Detection: Datasets, Features and Code
- 02Twitter (X) Topic Modeling in Python: BERTopic vs LDA on Real Tweets
- 03How to Make a Twitter (X) Word Cloud from Tweets in Python
- 04Spark Streaming Twitter (X) Data in 2026: PySpark Structured Streaming Without TwitterUtils
- 05Twitter (X) API to Neo4j: model, import and query a real follower and mention graph
- 06Twitter Trends API
- 07Dify vs n8n: Which One to Build On, What Each Costs, and How Each Handles Twitter (X) Data
- 08How Much Does the X (Twitter) API Cost in 2026?
Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API keyAlready building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.