Software Sushi JournalText classification
Build a Content Moderation Classifier with scikit-learn and LightGBM
Train a baseline, see how scores become review flags, and check whether extra text features improve the result.

Which labels go to review?
Move the threshold to see which labels would be flagged for one message. The example uses fictional scores.
- Harassment0.72Review
- Threat0.38Below threshold
- Graphic violence0.12Below threshold
1 of 3 labels flagged for review
A moderation model assigns a score to each label. The review policy decides what happens next. Start with a TF-IDF and LightGBM baseline, then use the same evaluation protocol to test whether more text features are worth keeping.
Prepare the labeled data
Use one text and one set of labels per record. Several labels can apply to the same message, or none may apply. Encode each label independently as 0 or 1.
See the input format
This fictional record shows the shape of data.json. Use your own labeled records to train both models.
[
{
"text": "Thanks for the reminder. I updated the discussion title.",
"labels": {"HARASSMENT": 0, "THREAT": 0}
}
]Use training data to fit the model, validation data to select the review threshold, and a separate test set to report results. The snippets assume you have these three splits and enough positives and negatives for the labels you evaluate.
Build a baseline
TF-IDF represents a message using weighted word and phrase counts. The scikit-learn pipeline passes those features to LightGBM. MultiOutputRegressor fits one regressor per label, so the labels can score independently.
Install the dependencies
python -m pip install scikit-learn lightgbm numpy spacy nltk
python -m spacy download en_core_web_sm
python -m nltk.downloader vader_lexiconLoad the records and train the baseline
Put your labeled records in data.json. Use the same label set in every record. Verify coverage for each label in all three splits, especially if some labels are rare.
import json
import numpy as np
from lightgbm import LGBMRegressor
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.multioutput import MultiOutputRegressor
from sklearn.pipeline import make_pipeline
with open("data.json", encoding="utf-8") as file:
records = json.load(file)
labels = sorted(records[0]["labels"])
texts = [record["text"] for record in records]
targets = np.array([
[record["labels"][label] for label in labels]
for record in records
])
train_texts, held_texts, train_targets, held_targets = train_test_split(
texts, targets, test_size=0.4, random_state=42
)
val_texts, test_texts, val_targets, test_targets = train_test_split(
held_texts, held_targets, test_size=0.5, random_state=42
)
def fit_model(features):
pipeline = make_pipeline(
features,
MultiOutputRegressor(LGBMRegressor(random_state=42)),
)
return pipeline.fit(train_texts, train_targets)
baseline = fit_model(
TfidfVectorizer(max_features=20_000, ngram_range=(1, 2), sublinear_tf=True)
)Turn scores into review flags
A review threshold marks every label at or above the chosen score. Lowering the threshold can catch more cases and send more items to review. These regressors produce scores that the example clips to 0–1. Treat them as model scores, and evaluate calibration separately if you need probability estimates.
For a first comparison, pick the threshold that maximizes micro F1 on the validation split. Micro F1 pools label decisions before combining precision and recall. Then check each label separately so a strong overall result does not obscure poor performance on a rare category.
Tune the threshold and score the test set
from sklearn.metrics import f1_score, mean_squared_error, roc_auc_score
def scores_for(pipeline, texts):
return np.clip(pipeline.predict(texts), 0, 1)
def evaluate(pipeline):
val_scores = scores_for(pipeline, val_texts)
threshold = max(
np.arange(0.10, 0.90, 0.01),
key=lambda cut: f1_score(
val_targets, val_scores >= cut, average="micro", zero_division=0
),
)
test_scores = scores_for(pipeline, test_texts)
return {
"threshold": float(threshold),
"micro_f1": f1_score(
test_targets, test_scores >= threshold,
average="micro", zero_division=0
),
"micro_roc_auc": roc_auc_score(test_targets, test_scores, average="micro"),
"mse": mean_squared_error(test_targets, test_scores),
}
baseline_metrics = evaluate(baseline)Score a new message
new_text = "Please stop sending me insulting messages."
threshold = baseline_metrics["threshold"]
scores = scores_for(baseline, [new_text])[0]
for label, score in zip(labels, scores):
status = "review" if score >= threshold else "below threshold"
print(f"{label}: {score:.3f} ({status})")Scikit-learn's guide to decision thresholds explains how to tune the cutoff with separate validation data.
Test additional text features
Try two feature branches. One groups word forms such as “sending” and “sent” under a common lemma. The other measures sentiment, text length, and the share of letters in uppercase. These are inputs to test. Quoting an insult or typing in capitals can change the inputs without violating a policy.
FeatureUnion joins the two feature sets for the same LightGBM model. Keep the data splits and scoring procedure fixed so you can compare the features fairly.
Combine the feature branches
import spacy
from nltk.sentiment import SentimentIntensityAnalyzer
from sklearn.pipeline import FeatureUnion
from sklearn.preprocessing import FunctionTransformer, StandardScaler
nlp = spacy.load("en_core_web_sm", disable=["parser", "ner"])
sentiment = SentimentIntensityAnalyzer()
def lemmas(text):
return [token.lemma_ for token in nlp(text) if token.is_alpha]
def text_features(texts):
rows = []
for text in texts:
letters = [char for char in text if char.isalpha()]
uppercase = sum(char.isupper() for char in letters)
tone = sentiment.polarity_scores(text)
rows.append([
tone["pos"], tone["neg"], tone["compound"],
len(text), uppercase / max(1, len(letters)),
])
return np.asarray(rows, dtype=float)
features = FeatureUnion([
("words", TfidfVectorizer(tokenizer=lemmas, token_pattern=None,
max_features=12_000, ngram_range=(1, 2))),
("extra", make_pipeline(FunctionTransformer(text_features), StandardScaler())),
])
enhanced = fit_model(features)
enhanced_metrics = evaluate(enhanced)Compare the reported runs
In the original experiment, the two models returned similar aggregate scores. The baseline had a slightly higher micro F1. The additional features changed some example scores, which is a reason to inspect errors by label before choosing a model.
| Metric | Baseline | Extra features |
|---|---|---|
| Micro F1 | 0.6978 | 0.6948 |
| Micro ROC AUC | 0.8923 | 0.8924 |
| Mean squared error | 0.0565 | 0.0567 |
| Selected threshold | 0.34 | 0.35 |
The original run selected each threshold and reported its F1 on the same validation set. Before relying on either model, check the chosen threshold on untouched data and confirm that reviewers can handle the resulting queue.
Where to go next
Review disagreements by label, and sample cases near the threshold to see what the review queue will contain. Once the classifier is running, monitor for changes in model performance as user content evolves.
For project planning, see how to choose between RAG and fine-tuning or explore our custom machine learning development services.


