Upload 6 files
Browse files- Dockerfile +18 -0
- README.md +25 -6
- app.py +629 -0
- comment_classifier_pipeline.joblib +3 -0
- deployment_training_fast.ipynb +1004 -0
- requirements.txt +8 -0
Dockerfile
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
# libgomp1: OpenMP runtime required by lightgbm at import time
|
| 4 |
+
RUN apt-get update && apt-get install -y --no-install-recommends libgomp1 \
|
| 5 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 6 |
+
|
| 7 |
+
WORKDIR /app
|
| 8 |
+
|
| 9 |
+
COPY requirements.txt .
|
| 10 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 11 |
+
|
| 12 |
+
COPY app.py comment_classifier_pipeline.joblib ./
|
| 13 |
+
|
| 14 |
+
ENV GRADIO_SERVER_NAME=0.0.0.0
|
| 15 |
+
ENV GRADIO_SERVER_PORT=7860
|
| 16 |
+
EXPOSE 7860
|
| 17 |
+
|
| 18 |
+
CMD ["python", "app.py"]
|
README.md
CHANGED
|
@@ -1,10 +1,29 @@
|
|
| 1 |
---
|
| 2 |
-
title: Comment Classification
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk:
|
|
|
|
|
|
|
| 7 |
pinned: false
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Comment Toxicity & Category Classification Dashboard
|
| 3 |
+
emoji: 🛡️
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: pink
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.20.0
|
| 8 |
+
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
license: mit
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# Comment Category Prediction & Toxicity Intelligence Dashboard
|
| 14 |
+
|
| 15 |
+
An interactive real-time comment classification dashboard powered by a stacked 7-model ensemble (LightGBM, Logistic Regressions, NB-SVM, LinearSVC) trained on toxic text and moderation signals.
|
| 16 |
+
|
| 17 |
+
## Features
|
| 18 |
+
- **Live Classification**: Real-time multiclass prediction across Normal (C-0), Offensive (C-1), Hate Speech (C-2), and Severe/Violent (C-3).
|
| 19 |
+
- **Confidence Distribution**: Per-class probability scores with dynamic threshold multipliers.
|
| 20 |
+
- **Linguistic Analysis**: Token extraction, leet-speak decoding, sentiment balance, and platform signal detection.
|
| 21 |
+
- **Preset Testing**: One-click benchmark samples to evaluate toxicity boundaries.
|
| 22 |
+
|
| 23 |
+
## Usage
|
| 24 |
+
Run locally with:
|
| 25 |
+
```bash
|
| 26 |
+
cd app
|
| 27 |
+
pip install -r requirements.txt
|
| 28 |
+
python app.py
|
| 29 |
+
```
|
app.py
ADDED
|
@@ -0,0 +1,629 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import joblib
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from scipy.sparse import hstack, csr_matrix
|
| 7 |
+
from sklearn.base import BaseEstimator, TransformerMixin
|
| 8 |
+
import gradio as gr
|
| 9 |
+
|
| 10 |
+
# ==============================================================================
|
| 11 |
+
# 1. Preprocessing & Feature Engineering Logic (Identical to Training Pipeline)
|
| 12 |
+
# ==============================================================================
|
| 13 |
+
|
| 14 |
+
LEET_MAP = str.maketrans({
|
| 15 |
+
'0': 'o', '1': 'i', '3': 'e', '4': 'a',
|
| 16 |
+
'5': 's', '7': 't', '@': 'a', '$': 's', '!': 'i'
|
| 17 |
+
})
|
| 18 |
+
|
| 19 |
+
ABBREV_MAP = {
|
| 20 |
+
'u' : 'you',
|
| 21 |
+
'r' : 'are',
|
| 22 |
+
'ur' : 'your',
|
| 23 |
+
'gonna': 'going to',
|
| 24 |
+
'wanna': 'want to',
|
| 25 |
+
'kys' : 'kill yourself',
|
| 26 |
+
'kms' : 'kill myself',
|
| 27 |
+
'wtf' : 'what the fuck',
|
| 28 |
+
'stfu' : 'shut the fuck up',
|
| 29 |
+
'idk' : 'i do not know',
|
| 30 |
+
'ngl' : 'not gonna lie',
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
POSITIVE_WORDS = frozenset({
|
| 34 |
+
'good','great','excellent','amazing','wonderful','best','love','perfect',
|
| 35 |
+
'nice','fantastic','awesome','beautiful','brilliant','outstanding','happy',
|
| 36 |
+
'glad','pleased','thankful','thanks','appreciate','agree','helpful','useful',
|
| 37 |
+
'interesting','impressive','well','better','fine','cool','fun','enjoy',
|
| 38 |
+
'liked','support','positive','fair','kind','respect','right','correct'
|
| 39 |
+
})
|
| 40 |
+
|
| 41 |
+
NEGATIVE_WORDS = frozenset({
|
| 42 |
+
'bad','terrible','awful','hate','worst','horrible','disgusting','poor',
|
| 43 |
+
'pathetic','stupid','ugly','wrong','annoying','boring','dumb','useless',
|
| 44 |
+
'trash','garbage','waste','sucks','lame','crap','fail','failed','worse',
|
| 45 |
+
'angry','mad','upset','disappointed','sad','broken','ruined','ridiculous',
|
| 46 |
+
'offensive','toxic','evil','idiot','fool','shut','die','kill'
|
| 47 |
+
})
|
| 48 |
+
|
| 49 |
+
VIOLENCE_WORDS = frozenset({
|
| 50 |
+
'kill','killed','killing','shoot','shooting','shot','death','dead','die',
|
| 51 |
+
'dying','murder','murdered','murders','attack','attacking','attacked',
|
| 52 |
+
'burn','burning','burned','fire','firing','guns','gun','weapon','weapons',
|
| 53 |
+
'bomb','bombing','destroy','destroying','violence','violent','rape','hang',
|
| 54 |
+
'hanging','decapitate','decapitated','torture','tortured','stab','stabbing',
|
| 55 |
+
'threat','threaten'
|
| 56 |
+
})
|
| 57 |
+
|
| 58 |
+
def expand_abbrevs(sentence):
|
| 59 |
+
words = sentence.split()
|
| 60 |
+
return ' '.join([ABBREV_MAP.get(w, w) for w in words])
|
| 61 |
+
|
| 62 |
+
def clean_text_column(df):
|
| 63 |
+
df = df.copy()
|
| 64 |
+
text = df['comment'].fillna('').astype(str).str.lower()
|
| 65 |
+
text = text.str.replace(r'http\S+|www\.\S+', ' ', regex=True)
|
| 66 |
+
text = text.str.replace(r'\w+\.(com|org|net|co|us)', ' ', regex=True)
|
| 67 |
+
text = text.str.replace(r'<[^>]+>', ' ', regex=True)
|
| 68 |
+
text = text.apply(lambda s: s.translate(LEET_MAP))
|
| 69 |
+
text = text.apply(expand_abbrevs)
|
| 70 |
+
text = text.str.replace(r'[^a-z\s]', ' ', regex=True)
|
| 71 |
+
text = text.str.replace(r'\s+', ' ', regex=True).str.strip()
|
| 72 |
+
text = text.replace('', 'empty_comment').fillna('missing_comment')
|
| 73 |
+
df['comment_clean'] = text
|
| 74 |
+
return df
|
| 75 |
+
|
| 76 |
+
class NBTransformer(BaseEstimator, TransformerMixin):
|
| 77 |
+
def __init__(self, alpha=1.0):
|
| 78 |
+
self.alpha = alpha
|
| 79 |
+
|
| 80 |
+
def fit(self, X, y=None):
|
| 81 |
+
if y is None:
|
| 82 |
+
self.r_ = np.ones(X.shape[1], dtype=np.float32)
|
| 83 |
+
return self
|
| 84 |
+
labels = np.unique(y)
|
| 85 |
+
num_cols = X.shape[1]
|
| 86 |
+
ratios = np.zeros((len(labels), num_cols), dtype=np.float64)
|
| 87 |
+
for i, lbl in enumerate(labels):
|
| 88 |
+
mask = (y == lbl)
|
| 89 |
+
p_counts = np.asarray(X[mask].sum(axis=0)).flatten() + self.alpha
|
| 90 |
+
n_counts = np.asarray(X[~mask].sum(axis=0)).flatten() + self.alpha
|
| 91 |
+
p_freq = p_counts / p_counts.sum()
|
| 92 |
+
n_freq = n_counts / n_counts.sum()
|
| 93 |
+
ratios[i] = np.log(p_freq) - np.log(n_freq)
|
| 94 |
+
self.r_ = np.abs(ratios).max(axis=0).astype(np.float32)
|
| 95 |
+
return self
|
| 96 |
+
|
| 97 |
+
def transform(self, X):
|
| 98 |
+
return X.multiply(self.r_)
|
| 99 |
+
|
| 100 |
+
def count_unique(text):
|
| 101 |
+
return len(set(str(text).split()))
|
| 102 |
+
|
| 103 |
+
def count_pos(text):
|
| 104 |
+
return sum(1 for w in str(text).split() if w in POSITIVE_WORDS)
|
| 105 |
+
|
| 106 |
+
def count_neg(text):
|
| 107 |
+
return sum(1 for w in str(text).split() if w in NEGATIVE_WORDS)
|
| 108 |
+
|
| 109 |
+
def count_caps(text):
|
| 110 |
+
return sum(1 for w in str(text).split() if w.isupper() and len(w) > 1)
|
| 111 |
+
|
| 112 |
+
def count_violence(text):
|
| 113 |
+
return sum(1 for w in str(text).split() if w in VIOLENCE_WORDS)
|
| 114 |
+
|
| 115 |
+
def build_features(df):
|
| 116 |
+
df = df.copy()
|
| 117 |
+
raw = df['comment'].astype(str)
|
| 118 |
+
cln = df.get('comment_clean', raw.str.lower())
|
| 119 |
+
word_count = cln.str.split().str.len().fillna(0).astype(int)
|
| 120 |
+
|
| 121 |
+
if1 = df.get('if_1', pd.Series(0, index=df.index)).fillna(0)
|
| 122 |
+
if2 = df.get('if_2', pd.Series(0, index=df.index)).fillna(0)
|
| 123 |
+
|
| 124 |
+
df['char_count'] = cln.str.len().astype(np.float32)
|
| 125 |
+
df['word_count'] = word_count.astype(np.float32)
|
| 126 |
+
df['unique_words'] = cln.apply(count_unique).astype(np.float32)
|
| 127 |
+
df['lexical_div'] = (df['unique_words'] / (word_count + 1)).astype(np.float32)
|
| 128 |
+
df['avg_word_len'] = (df['char_count'] / (word_count + 1)).astype(np.float32)
|
| 129 |
+
|
| 130 |
+
df['caps_count'] = raw.str.count(r'[A-Z]').astype(np.float32)
|
| 131 |
+
df['caps_ratio'] = (df['caps_count'] / (df['char_count'] + 1)).astype(np.float32)
|
| 132 |
+
df['exclaim'] = raw.str.count('!').astype(np.float32)
|
| 133 |
+
df['question'] = raw.str.count(r'\?').astype(np.float32)
|
| 134 |
+
df['punct_count'] = raw.str.count(r'[^\w\s]').astype(np.float32)
|
| 135 |
+
df['sent_count'] = raw.str.count(r'[.!?]+').clip(lower=1).astype(np.float32)
|
| 136 |
+
df['avg_sent_len'] = (word_count / (df['sent_count'] + 1)).astype(np.float32)
|
| 137 |
+
df['all_caps_words'] = raw.apply(count_caps).astype(np.float32)
|
| 138 |
+
|
| 139 |
+
df['pos_count'] = cln.apply(count_pos).astype(np.float32)
|
| 140 |
+
df['neg_count'] = cln.apply(count_neg).astype(np.float32)
|
| 141 |
+
df['sent_balance'] = (df['pos_count'] - df['neg_count']).astype(np.float32)
|
| 142 |
+
|
| 143 |
+
df['violence_count'] = cln.apply(count_violence).astype(np.float32)
|
| 144 |
+
df['has_violence'] = (df['violence_count'] > 0).astype(np.int8)
|
| 145 |
+
df['violence_ratio'] = (df['violence_count'] / (word_count + 1)).astype(np.float32)
|
| 146 |
+
df['violence_score'] = (df['violence_count'] * 2.0 + df['violence_ratio'] * 10.0).astype(np.float32)
|
| 147 |
+
df['if1_x_violence'] = (if1 * df['violence_count']).astype(np.float32)
|
| 148 |
+
|
| 149 |
+
df['upvote'] = df.get('upvote', pd.Series(0, index=df.index)).fillna(0)
|
| 150 |
+
df['downvote'] = df.get('downvote', pd.Series(0, index=df.index)).fillna(0)
|
| 151 |
+
|
| 152 |
+
df['total_votes'] = (df['upvote'] + df['downvote']).astype(np.float32)
|
| 153 |
+
df['vote_ratio'] = (df['upvote'] / (df['total_votes'] + 1)).astype(np.float32)
|
| 154 |
+
df['zero_downvote'] = (df['downvote'] == 0).astype(np.int8)
|
| 155 |
+
df['controversy'] = np.minimum(df['upvote'], df['downvote']).astype(np.float32) * 2
|
| 156 |
+
|
| 157 |
+
emo_cols = ['emoticon_1', 'emoticon_2', 'emoticon_3']
|
| 158 |
+
for ec in emo_cols:
|
| 159 |
+
if ec not in df.columns:
|
| 160 |
+
df[ec] = 0
|
| 161 |
+
df[emo_cols] = df[emo_cols].fillna(0)
|
| 162 |
+
df['total_emo'] = df[emo_cols].sum(axis=1).astype(np.float32)
|
| 163 |
+
df['has_emo'] = (df['total_emo'] > 0).astype(np.int8)
|
| 164 |
+
|
| 165 |
+
parsed_dt = pd.to_datetime(df.get('created_date', pd.Series(None, index=df.index)), errors='coerce')
|
| 166 |
+
hour = parsed_dt.dt.hour.fillna(12).astype(int)
|
| 167 |
+
day_of_week = parsed_dt.dt.dayofweek.fillna(3).astype(int)
|
| 168 |
+
|
| 169 |
+
df['hour_sin']= np.sin(2 * np.pi * hour / 24).astype(np.float32)
|
| 170 |
+
df['hour_cos'] = np.cos(2 * np.pi * hour / 24).astype(np.float32)
|
| 171 |
+
df['dow_sin'] = np.sin(2 * np.pi * day_of_week / 7).astype(np.float32)
|
| 172 |
+
df['is_weekend'] = (day_of_week >= 5).astype(np.int8)
|
| 173 |
+
|
| 174 |
+
race_col = df.get('race', pd.Series('_', index=df.index)).fillna('_').str.lower()
|
| 175 |
+
religion_col = df.get('religion', pd.Series('_', index=df.index)).fillna('_').str.lower()
|
| 176 |
+
gender_col = df.get('gender', pd.Series('_', index=df.index)).fillna('_').str.lower()
|
| 177 |
+
|
| 178 |
+
has_race = (race_col != '_') & (race_col != 'none')
|
| 179 |
+
has_religion = (religion_col != '_') & (religion_col != 'none')
|
| 180 |
+
has_gender = (gender_col != '_') & (gender_col != 'none')
|
| 181 |
+
|
| 182 |
+
df['has_identity'] = (has_race | has_religion | has_gender).astype(np.int8)
|
| 183 |
+
df['identity_count'] = (has_race.astype(int) + has_religion.astype(int) + has_gender.astype(int)).astype(np.int8)
|
| 184 |
+
df['disability_flag'] = (df.get('disability', pd.Series(False, index=df.index)).map({True: 1, False: 0, 'True': 1, 'False': 0}).fillna(0)).astype(np.int8)
|
| 185 |
+
|
| 186 |
+
df['if_prod'] = (if1 * if2).astype(np.float32)
|
| 187 |
+
df['if_ratio'] = (if1 / (if2 + 1)).astype(np.float32)
|
| 188 |
+
df['if_sum'] = (if1 + if2).astype(np.float32)
|
| 189 |
+
|
| 190 |
+
df['zone_safe'] = (if2 <= 7).astype(np.int8)
|
| 191 |
+
df['zone_c1_trigger'] = ((if2 >= 8) & (if1.isin([4, 6, 10]))).astype(np.int8)
|
| 192 |
+
df['zone_c23'] = ((if1 == 0) & (if2 >= 8)).astype(np.int8)
|
| 193 |
+
df['if1_low'] = (if1 <= 1).astype(np.int8)
|
| 194 |
+
df['if1_nonzero'] = (if1 > 0).astype(np.int8)
|
| 195 |
+
|
| 196 |
+
df['golden_c1'] = ((if2 >= 8) & df['has_identity'].astype(bool)).astype(np.int8)
|
| 197 |
+
df['golden_c2'] = ((if2 >= 8) & ~df['has_identity'].astype(bool)).astype(np.int8)
|
| 198 |
+
|
| 199 |
+
df['is_short'] = (word_count <= 15).astype(np.int8)
|
| 200 |
+
df['short_violent'] = (df['is_short'] * df['has_violence']).astype(np.int8)
|
| 201 |
+
|
| 202 |
+
df['danger_zone'] = ((df['zone_c23'] == 1) & (df['has_identity'] == 0)).astype(np.int8)
|
| 203 |
+
df['violence_in_dz'] = (df['violence_count'] * df['danger_zone']).astype(np.float32)
|
| 204 |
+
df['c3_signal'] = (df['is_short'] * df['zero_downvote'] * (df['has_identity'] == 0) * df['zone_c23']).astype(np.int8)
|
| 205 |
+
|
| 206 |
+
numeric_dtype_cols = df.select_dtypes(include=[np.number]).columns
|
| 207 |
+
df[numeric_dtype_cols] = df[numeric_dtype_cols].fillna(0)
|
| 208 |
+
|
| 209 |
+
return df
|
| 210 |
+
|
| 211 |
+
# ==============================================================================
|
| 212 |
+
# 2. Pipeline Artifact Loader & Model Management
|
| 213 |
+
# ==============================================================================
|
| 214 |
+
|
| 215 |
+
MODEL_PATHS = [
|
| 216 |
+
'comment_classifier_pipeline.joblib',
|
| 217 |
+
'app/comment_classifier_pipeline.joblib',
|
| 218 |
+
'../comment_classifier_pipeline.joblib',
|
| 219 |
+
'/kaggle/working/comment_classifier_pipeline.joblib'
|
| 220 |
+
]
|
| 221 |
+
|
| 222 |
+
# Keys the real deployment artifact must have (see app/deployment_training_fast.ipynb,
|
| 223 |
+
# section 9 "Export Deployment Artifact"). Each *_models entry is a list of N_FOLDS
|
| 224 |
+
# fitted fold copies of that base learner, bagged (averaged) at inference time.
|
| 225 |
+
REQUIRED_ARTIFACT_KEYS = {
|
| 226 |
+
'tfidf_word', 'tfidf_char', 'tfidf_phrase', 'ordinal_enc',
|
| 227 |
+
'numeric_col_names', 'cat_col_names', 'meta_model', 'thresholds',
|
| 228 |
+
'lgb_models', 'lr_word_models', 'lr_char_models', 'nbsvm_models',
|
| 229 |
+
'lgb_bin_models', 'lgb_c23_models', 'svc_models',
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
MODEL_ARTIFACT = None
|
| 233 |
+
MODEL_STATUS_TEXT = ""
|
| 234 |
+
|
| 235 |
+
for path in MODEL_PATHS:
|
| 236 |
+
if os.path.exists(path):
|
| 237 |
+
try:
|
| 238 |
+
candidate = joblib.load(path)
|
| 239 |
+
missing = REQUIRED_ARTIFACT_KEYS - set(candidate.keys())
|
| 240 |
+
if missing:
|
| 241 |
+
print(f"Skipping {path}: artifact missing keys {sorted(missing)}")
|
| 242 |
+
continue
|
| 243 |
+
MODEL_ARTIFACT = candidate
|
| 244 |
+
n_folds = MODEL_ARTIFACT.get('n_folds', len(MODEL_ARTIFACT['lgb_models']))
|
| 245 |
+
MODEL_STATUS_TEXT = f"Full Stacked Ensemble Active ({os.path.basename(path)}, {n_folds}-fold bagged)"
|
| 246 |
+
print(MODEL_STATUS_TEXT)
|
| 247 |
+
break
|
| 248 |
+
except Exception as e:
|
| 249 |
+
print(f"Error loading {path}: {e}")
|
| 250 |
+
|
| 251 |
+
if MODEL_ARTIFACT is None:
|
| 252 |
+
MODEL_STATUS_TEXT = "Demonstration Preview Mode (Upload 'comment_classifier_pipeline.joblib' to activate full ensemble)"
|
| 253 |
+
print(MODEL_STATUS_TEXT)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def _bag_predict_proba(models, X):
|
| 257 |
+
"""Average predict_proba across a list of fold-fitted copies of the same base learner."""
|
| 258 |
+
total = None
|
| 259 |
+
for m in models:
|
| 260 |
+
p = m.predict_proba(X)
|
| 261 |
+
total = p if total is None else total + p
|
| 262 |
+
return total / len(models)
|
| 263 |
+
|
| 264 |
+
CLASS_NAMES = {0: 'Normal (C-0)', 1: 'Offensive (C-1)', 2: 'Hate Speech (C-2)', 3: 'Severe/Violent (C-3)'}
|
| 265 |
+
|
| 266 |
+
# ==============================================================================
|
| 267 |
+
# 3. Live Inference Function
|
| 268 |
+
# ==============================================================================
|
| 269 |
+
|
| 270 |
+
def analyze_comment(comment_text, if_1, if_2, upvotes, downvotes, race, religion, gender):
|
| 271 |
+
if not comment_text.strip():
|
| 272 |
+
return (
|
| 273 |
+
"Please enter a comment to analyze.",
|
| 274 |
+
{},
|
| 275 |
+
"No input provided",
|
| 276 |
+
"N/A",
|
| 277 |
+
"N/A",
|
| 278 |
+
"N/A"
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
input_df = pd.DataFrame([{
|
| 282 |
+
'comment': comment_text,
|
| 283 |
+
'if_1': float(if_1),
|
| 284 |
+
'if_2': float(if_2),
|
| 285 |
+
'upvote': float(upvotes),
|
| 286 |
+
'downvote': float(downvotes),
|
| 287 |
+
'emoticon_1': 0, 'emoticon_2': 0, 'emoticon_3': 0,
|
| 288 |
+
'created_date': '2026-07-25 12:00:00',
|
| 289 |
+
'race': race,
|
| 290 |
+
'religion': religion,
|
| 291 |
+
'gender': gender,
|
| 292 |
+
'disability': False
|
| 293 |
+
}])
|
| 294 |
+
|
| 295 |
+
df_clean = clean_text_column(input_df)
|
| 296 |
+
df_eng = build_features(df_clean)
|
| 297 |
+
clean_str = df_eng['comment_clean'].iloc[0]
|
| 298 |
+
|
| 299 |
+
if MODEL_ARTIFACT is not None:
|
| 300 |
+
w_vec = MODEL_ARTIFACT['tfidf_word'].transform([clean_str])
|
| 301 |
+
c_vec = MODEL_ARTIFACT['tfidf_char'].transform([clean_str])
|
| 302 |
+
p_vec = MODEL_ARTIFACT['tfidf_phrase'].transform([clean_str])
|
| 303 |
+
|
| 304 |
+
num_feats = df_eng[MODEL_ARTIFACT['numeric_col_names']].values.astype(np.float32)
|
| 305 |
+
cat_feats = MODEL_ARTIFACT['ordinal_enc'].transform(
|
| 306 |
+
df_eng[MODEL_ARTIFACT['cat_col_names']].fillna('missing').astype(str)
|
| 307 |
+
).astype(np.int32)
|
| 308 |
+
|
| 309 |
+
X_full = hstack([w_vec, c_vec, p_vec, csr_matrix(num_feats), csr_matrix(cat_feats)]).tocsr()
|
| 310 |
+
clean_text_input = [clean_str]
|
| 311 |
+
|
| 312 |
+
# Bag (average) across the N_FOLDS fitted copies of each base learner, then
|
| 313 |
+
# concatenate in the exact order the meta-learner was trained on: the two
|
| 314 |
+
# LGB specialists (lgb_bin, lgb_c23) are BINARY models with 2-column output,
|
| 315 |
+
# the other five are 4-class (see deployment_training_fast.ipynb, section 9).
|
| 316 |
+
p_lgb = _bag_predict_proba(MODEL_ARTIFACT['lgb_models'], X_full)
|
| 317 |
+
p_lr_w = _bag_predict_proba(MODEL_ARTIFACT['lr_word_models'], clean_text_input)
|
| 318 |
+
p_lr_c = _bag_predict_proba(MODEL_ARTIFACT['lr_char_models'], clean_text_input)
|
| 319 |
+
p_nbsvm = _bag_predict_proba(MODEL_ARTIFACT['nbsvm_models'], clean_text_input)
|
| 320 |
+
p_lgb_bin = _bag_predict_proba(MODEL_ARTIFACT['lgb_bin_models'], X_full)
|
| 321 |
+
p_svc = _bag_predict_proba(MODEL_ARTIFACT['svc_models'], clean_text_input)
|
| 322 |
+
p_c23 = _bag_predict_proba(MODEL_ARTIFACT['lgb_c23_models'], X_full)
|
| 323 |
+
|
| 324 |
+
stacked = np.hstack([p_lgb, p_lr_w, p_lr_c, p_nbsvm, p_lgb_bin, p_svc, p_c23]).astype(np.float32)
|
| 325 |
+
meta_probs = MODEL_ARTIFACT['meta_model'].predict_proba(stacked)[0]
|
| 326 |
+
|
| 327 |
+
mults = MODEL_ARTIFACT.get('thresholds', [1.032, 0.951, 0.85, 1.25])
|
| 328 |
+
for i in range(4):
|
| 329 |
+
meta_probs[i] *= mults[i]
|
| 330 |
+
probs = meta_probs / meta_probs.sum()
|
| 331 |
+
else:
|
| 332 |
+
v_count = df_eng['violence_count'].iloc[0]
|
| 333 |
+
n_count = df_eng['neg_count'].iloc[0]
|
| 334 |
+
p_count = df_eng['pos_count'].iloc[0]
|
| 335 |
+
has_id = df_eng['has_identity'].iloc[0]
|
| 336 |
+
|
| 337 |
+
if v_count > 0 or 'kill' in clean_str or 'shoot' in clean_str or 'die' in clean_str:
|
| 338 |
+
probs = np.array([0.05, 0.15, 0.20, 0.60])
|
| 339 |
+
elif n_count > 1 or 'hate' in clean_str or 'stupid' in clean_str:
|
| 340 |
+
probs = np.array([0.10, 0.50, 0.30, 0.10]) if not has_id else np.array([0.05, 0.25, 0.60, 0.10])
|
| 341 |
+
elif p_count > 0 or 'good' in clean_str or 'thanks' in clean_str or 'great' in clean_str:
|
| 342 |
+
probs = np.array([0.85, 0.10, 0.03, 0.02])
|
| 343 |
+
else:
|
| 344 |
+
probs = np.array([0.70, 0.18, 0.08, 0.04])
|
| 345 |
+
|
| 346 |
+
pred_class_id = int(np.argmax(probs))
|
| 347 |
+
pred_label = CLASS_NAMES[pred_class_id]
|
| 348 |
+
|
| 349 |
+
conf_dict = {CLASS_NAMES[i]: float(probs[i]) for i in range(4)}
|
| 350 |
+
|
| 351 |
+
words = clean_str.split()
|
| 352 |
+
detected_violence = [w for w in words if w in VIOLENCE_WORDS]
|
| 353 |
+
detected_neg = [w for w in words if w in NEGATIVE_WORDS]
|
| 354 |
+
detected_pos = [w for w in words if w in POSITIVE_WORDS]
|
| 355 |
+
|
| 356 |
+
token_summary = []
|
| 357 |
+
if detected_violence:
|
| 358 |
+
token_summary.append(f"Violent Terms: {', '.join(set(detected_violence))}")
|
| 359 |
+
if detected_neg:
|
| 360 |
+
token_summary.append(f"Negative Terms: {', '.join(set(detected_neg))}")
|
| 361 |
+
if detected_pos:
|
| 362 |
+
token_summary.append(f"Positive Terms: {', '.join(set(detected_pos))}")
|
| 363 |
+
if not token_summary:
|
| 364 |
+
token_summary.append("Standard vocabulary / General comment terms")
|
| 365 |
+
|
| 366 |
+
detected_tokens_str = "\n".join(token_summary)
|
| 367 |
+
|
| 368 |
+
sent_bal = float(df_eng['sent_balance'].iloc[0])
|
| 369 |
+
caps_rat = float(df_eng['caps_ratio'].iloc[0]) * 100
|
| 370 |
+
risk_level = "High Risk (Action Required)" if pred_class_id in [2, 3] else ("Moderate Risk" if pred_class_id == 1 else "Low Risk / Safe")
|
| 371 |
+
|
| 372 |
+
return (
|
| 373 |
+
pred_label,
|
| 374 |
+
conf_dict,
|
| 375 |
+
detected_tokens_str,
|
| 376 |
+
f"Sentiment Score: {sent_bal:+.1f}",
|
| 377 |
+
f"Caps Ratio: {caps_rat:.1f}%",
|
| 378 |
+
risk_level
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# ==============================================================================
|
| 382 |
+
# 4. Gradio Dashboard Web UI Construction (Sleek Modern Borderless Cards & SVG Icons)
|
| 383 |
+
# ==============================================================================
|
| 384 |
+
|
| 385 |
+
CUSTOM_CSS = """
|
| 386 |
+
/* Body & Main Container Reset */
|
| 387 |
+
body, .gradio-container {
|
| 388 |
+
background-color: #0b0f19 !important;
|
| 389 |
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
|
| 390 |
+
color: #f8fafc !important;
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
/* Eliminate Ugly Double-Nested Boxes & Outer Shadows */
|
| 394 |
+
.block, div[class*="st-"], div[data-testid="column"] {
|
| 395 |
+
background-color: #131b2e !important;
|
| 396 |
+
border: 1px solid rgba(255, 255, 255, 0.08) !important;
|
| 397 |
+
border-radius: 12px !important;
|
| 398 |
+
box-shadow: none !important;
|
| 399 |
+
padding: 16px !important;
|
| 400 |
+
margin-bottom: 8px !important;
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
/* Remove Outer Gray Form Wrappers */
|
| 404 |
+
.form, .block.label, div[class*="form"], fieldset {
|
| 405 |
+
background: transparent !important;
|
| 406 |
+
border: none !important;
|
| 407 |
+
box-shadow: none !important;
|
| 408 |
+
padding: 0 !important;
|
| 409 |
+
margin: 0 !important;
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
/* Clean Minimal Labels (Replaces Blocky Purple Badges) */
|
| 413 |
+
span[data-testid="block-info"], label span, .block-title {
|
| 414 |
+
background: transparent !important;
|
| 415 |
+
color: #94a3b8 !important;
|
| 416 |
+
font-size: 11px !important;
|
| 417 |
+
font-weight: 700 !important;
|
| 418 |
+
text-transform: uppercase !important;
|
| 419 |
+
letter-spacing: 0.8px !important;
|
| 420 |
+
border: none !important;
|
| 421 |
+
border-radius: 0 !important;
|
| 422 |
+
padding: 0 0 6px 0 !important;
|
| 423 |
+
box-shadow: none !important;
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
/* Input Fields & Textareas */
|
| 427 |
+
input[type="text"], textarea, select, .gr-input {
|
| 428 |
+
background-color: #0b1120 !important;
|
| 429 |
+
border: 1px solid rgba(255, 255, 255, 0.12) !important;
|
| 430 |
+
border-radius: 8px !important;
|
| 431 |
+
color: #f8fafc !important;
|
| 432 |
+
font-size: 14px !important;
|
| 433 |
+
box-shadow: none !important;
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
input[type="text"]:focus, textarea:focus {
|
| 437 |
+
border-color: #6366f1 !important;
|
| 438 |
+
box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.25) !important;
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
/* Header Banner */
|
| 442 |
+
.dashboard-header {
|
| 443 |
+
background: linear-gradient(135deg, #1e1b4b 0%, #311b92 50%, #4c1d95 100%) !important;
|
| 444 |
+
border: 1px solid rgba(255, 255, 255, 0.12) !important;
|
| 445 |
+
border-radius: 14px !important;
|
| 446 |
+
padding: 20px 24px !important;
|
| 447 |
+
margin-bottom: 20px !important;
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
.dashboard-title-box {
|
| 451 |
+
display: flex;
|
| 452 |
+
align-items: center;
|
| 453 |
+
gap: 12px;
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
.dashboard-title-text {
|
| 457 |
+
font-size: 22px;
|
| 458 |
+
font-weight: 800;
|
| 459 |
+
color: #ffffff;
|
| 460 |
+
letter-spacing: -0.5px;
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
.status-chip {
|
| 464 |
+
background-color: rgba(255, 255, 255, 0.1);
|
| 465 |
+
border: 1px solid rgba(255, 255, 255, 0.15);
|
| 466 |
+
color: #cbd5e1;
|
| 467 |
+
font-size: 12px;
|
| 468 |
+
font-weight: 600;
|
| 469 |
+
padding: 4px 12px;
|
| 470 |
+
border-radius: 20px;
|
| 471 |
+
display: inline-flex;
|
| 472 |
+
align-items: center;
|
| 473 |
+
gap: 6px;
|
| 474 |
+
margin-top: 8px;
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
/* Primary Button */
|
| 478 |
+
.btn-primary {
|
| 479 |
+
background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%) !important;
|
| 480 |
+
color: #ffffff !important;
|
| 481 |
+
font-weight: 700 !important;
|
| 482 |
+
border: none !important;
|
| 483 |
+
border-radius: 8px !important;
|
| 484 |
+
padding: 12px 20px !important;
|
| 485 |
+
box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3) !important;
|
| 486 |
+
transition: all 0.2s ease !important;
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
.btn-primary:hover {
|
| 490 |
+
transform: translateY(-1px) !important;
|
| 491 |
+
box-shadow: 0 6px 16px rgba(99, 102, 241, 0.45) !important;
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
/* Preset Buttons */
|
| 495 |
+
.preset-btn {
|
| 496 |
+
background: #0b1120 !important;
|
| 497 |
+
border: 1px solid rgba(255, 255, 255, 0.08) !important;
|
| 498 |
+
color: #cbd5e1 !important;
|
| 499 |
+
font-size: 13px !important;
|
| 500 |
+
font-weight: 600 !important;
|
| 501 |
+
border-radius: 8px !important;
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
.preset-btn:hover {
|
| 505 |
+
background: #1e293b !important;
|
| 506 |
+
border-color: rgba(255, 255, 255, 0.2) !important;
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
/* Accordion Styling */
|
| 510 |
+
.accordion {
|
| 511 |
+
background-color: #0b1120 !important;
|
| 512 |
+
border: 1px solid rgba(255, 255, 255, 0.08) !important;
|
| 513 |
+
border-radius: 8px !important;
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
/* Section Header Titles */
|
| 517 |
+
.section-head {
|
| 518 |
+
display: flex;
|
| 519 |
+
align-items: center;
|
| 520 |
+
gap: 8px;
|
| 521 |
+
font-size: 15px;
|
| 522 |
+
font-weight: 700;
|
| 523 |
+
color: #f1f5f9;
|
| 524 |
+
margin-bottom: 12px;
|
| 525 |
+
}
|
| 526 |
+
"""
|
| 527 |
+
|
| 528 |
+
SHIELD_SVG = '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#a5b4fc" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>'
|
| 529 |
+
EDIT_SVG = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#818cf8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>'
|
| 530 |
+
CHART_SVG = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#818cf8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>'
|
| 531 |
+
LIGHTNING_SVG = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fbbf24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>'
|
| 532 |
+
|
| 533 |
+
# Construct Block App
|
| 534 |
+
demo = gr.Blocks()
|
| 535 |
+
|
| 536 |
+
with demo:
|
| 537 |
+
with gr.Row(elem_classes=["dashboard-header"]):
|
| 538 |
+
with gr.Column():
|
| 539 |
+
gr.HTML(
|
| 540 |
+
f"""
|
| 541 |
+
<div class="dashboard-title-box">
|
| 542 |
+
{SHIELD_SVG}
|
| 543 |
+
<div class="dashboard-title-text">Comment Toxicity & Category Intelligence Dashboard</div>
|
| 544 |
+
</div>
|
| 545 |
+
<div class="status-chip">
|
| 546 |
+
{LIGHTNING_SVG}
|
| 547 |
+
<span>{MODEL_STATUS_TEXT}</span>
|
| 548 |
+
</div>
|
| 549 |
+
"""
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
with gr.Row():
|
| 553 |
+
# Left Panel: Input controls & Presets
|
| 554 |
+
with gr.Column(scale=5):
|
| 555 |
+
gr.HTML(f'<div class="section-head">{EDIT_SVG} <span>Enter Comment & Parameters</span></div>')
|
| 556 |
+
|
| 557 |
+
comment_input = gr.Textbox(
|
| 558 |
+
lines=4,
|
| 559 |
+
placeholder="Type or paste a comment here (e.g. 'Great tutorial thanks!', or toxic text with leet-speak like 'k1ll all 1diots')...",
|
| 560 |
+
label="Comment Content"
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
with gr.Accordion("Advanced Metadata & Platform Signals", open=False):
|
| 564 |
+
with gr.Row():
|
| 565 |
+
if_1 = gr.Slider(0, 10, value=0, step=1, label="Platform Signal if_1")
|
| 566 |
+
if_2 = gr.Slider(0, 15, value=5, step=1, label="Platform Signal if_2")
|
| 567 |
+
with gr.Row():
|
| 568 |
+
upvotes = gr.Number(value=0, label="Upvotes")
|
| 569 |
+
downvotes = gr.Number(value=0, label="Downvotes")
|
| 570 |
+
with gr.Row():
|
| 571 |
+
race = gr.Dropdown(["none", "White", "Black", "Asian", "Hispanic"], value="none", label="Target Race")
|
| 572 |
+
religion = gr.Dropdown(["none", "Christian", "Muslim", "Jewish", "Hindu"], value="none", label="Target Religion")
|
| 573 |
+
gender = gr.Dropdown(["none", "Male", "Female", "Transgender"], value="none", label="Target Gender")
|
| 574 |
+
|
| 575 |
+
submit_btn = gr.Button("Analyze Comment Safety", variant="primary", elem_classes=["btn-primary"])
|
| 576 |
+
|
| 577 |
+
gr.HTML('<div style="font-size: 11px; font-weight: 700; color: #94a3b8; margin: 16px 0 8px 0; text-transform: uppercase; letter-spacing: 0.8px;">Quick Test Presets</div>')
|
| 578 |
+
with gr.Row():
|
| 579 |
+
preset_normal = gr.Button("Normal Comment", elem_classes=["preset-btn"])
|
| 580 |
+
preset_offensive = gr.Button("Offensive Comment", elem_classes=["preset-btn"])
|
| 581 |
+
preset_hate = gr.Button("Hate Speech", elem_classes=["preset-btn"])
|
| 582 |
+
preset_violent = gr.Button("Severe / Violent", elem_classes=["preset-btn"])
|
| 583 |
+
|
| 584 |
+
# Right Panel: Output Dashboard & Diagnostics
|
| 585 |
+
with gr.Column(scale=7):
|
| 586 |
+
gr.HTML(f'<div class="section-head">{CHART_SVG} <span>Classification Diagnostics</span></div>')
|
| 587 |
+
|
| 588 |
+
with gr.Row():
|
| 589 |
+
predicted_label_out = gr.Textbox(label="Predicted Category")
|
| 590 |
+
risk_level_out = gr.Textbox(label="Safety Risk Assessment")
|
| 591 |
+
|
| 592 |
+
confidence_chart_out = gr.Label(label="Class Probability Distribution", num_top_classes=4)
|
| 593 |
+
|
| 594 |
+
with gr.Row():
|
| 595 |
+
sent_balance_out = gr.Textbox(label="Sentiment Score")
|
| 596 |
+
caps_ratio_out = gr.Textbox(label="Capitalisation Ratio")
|
| 597 |
+
|
| 598 |
+
tokens_out = gr.Textbox(label="Linguistic & Vocabulary Signals", lines=3)
|
| 599 |
+
|
| 600 |
+
# Event Bindings
|
| 601 |
+
submit_btn.click(
|
| 602 |
+
fn=analyze_comment,
|
| 603 |
+
inputs=[comment_input, if_1, if_2, upvotes, downvotes, race, religion, gender],
|
| 604 |
+
outputs=[predicted_label_out, confidence_chart_out, tokens_out, sent_balance_out, caps_ratio_out, risk_level_out]
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
preset_normal.click(
|
| 608 |
+
lambda: ("Awesome article! Thanks for sharing this useful explanation, really appreciate it.", 0, 2, 15, 0, "none", "none", "none"),
|
| 609 |
+
outputs=[comment_input, if_1, if_2, upvotes, downvotes, race, religion, gender]
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
preset_offensive.click(
|
| 613 |
+
lambda: ("This post is complete garbage and your opinion is dumb.", 0, 8, 2, 5, "none", "none", "none"),
|
| 614 |
+
outputs=[comment_input, if_1, if_2, upvotes, downvotes, race, religion, gender]
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
preset_hate.click(
|
| 618 |
+
lambda: ("I hate these people, they are terrible and should be kicked out.", 4, 10, 0, 12, "Black", "Muslim", "none"),
|
| 619 |
+
outputs=[comment_input, if_1, if_2, upvotes, downvotes, race, religion, gender]
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
preset_violent.click(
|
| 623 |
+
lambda: ("I will k1ll you and shoot your family d34d.", 0, 12, 0, 0, "none", "none", "none"),
|
| 624 |
+
outputs=[comment_input, if_1, if_2, upvotes, downvotes, race, religion, gender]
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
if __name__ == "__main__":
|
| 628 |
+
demo.launch(theme=gr.themes.Soft(primary_hue="indigo", neutral_hue="slate"), css=CUSTOM_CSS)
|
| 629 |
+
|
comment_classifier_pipeline.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d9a252c3a798413a22300a2da70215605307ecf3fffb38eca728417d494bd9de
|
| 3 |
+
size 75620596
|
deployment_training_fast.ipynb
ADDED
|
@@ -0,0 +1,1004 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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of 7 base learners (LightGBM, LR-Word, LR-Char, NB-SVM, LGB-Binary, LinearSVC, LGB-C23) + LightGBM meta-learner, exactly matching the architecture that scored **0.837+ macro F1** in the original 8-hour Kaggle run.\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"**Why this notebook is fast (fits in Kaggle's 9h CPU limit):**\n",
|
| 12 |
+
"- `N_FOLDS = 3` (the `deployment_training_template.ipynb` used 4, adding a full extra fold pass over 7 models).\n",
|
| 13 |
+
"- No redundant \"retrain all 7 base models on 100% of data\" stage. That stage alone added another full training pass on top of the fold passes and is why the template blew past 12 hours.\n",
|
| 14 |
+
"- Instead, deployment uses the **3 fold-trained models per base learner** (already trained during CV) as a bagged ensemble, exactly like the original notebook's `tst_*` test-averaging \u2014 only now every fold's fitted model object is kept and exported instead of thrown away.\n",
|
| 15 |
+
"- No EDA / visualization / hyperparameter-search cells \u2014 those never touched the trained artifact anyway.\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"Net effect: identical feature engineering, identical 7 base models + meta-learner + threshold multipliers as before, ~3/4 the CV cost of the template, and zero cost for a full-data refit stage."
|
| 18 |
+
]
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"cell_type": "markdown",
|
| 22 |
+
"metadata": {},
|
| 23 |
+
"source": [
|
| 24 |
+
"## 1. Imports and Setup\n",
|
| 25 |
+
"---"
|
| 26 |
+
]
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "code",
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"outputs": [],
|
| 33 |
+
"source": [
|
| 34 |
+
"import numpy as np\n",
|
| 35 |
+
"import pandas as pd\n",
|
| 36 |
+
"import gc\n",
|
| 37 |
+
"import warnings\n",
|
| 38 |
+
"import re\n",
|
| 39 |
+
"import os\n",
|
| 40 |
+
"import joblib\n",
|
| 41 |
+
"from datetime import datetime\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"from scipy.sparse import hstack, csr_matrix\n",
|
| 44 |
+
"from sklearn.base import BaseEstimator, TransformerMixin\n",
|
| 45 |
+
"from sklearn.preprocessing import OrdinalEncoder\n",
|
| 46 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 47 |
+
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
|
| 48 |
+
"from sklearn.pipeline import Pipeline\n",
|
| 49 |
+
"from sklearn.metrics import f1_score, classification_report\n",
|
| 50 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 51 |
+
"from sklearn.svm import LinearSVC\n",
|
| 52 |
+
"from sklearn.calibration import CalibratedClassifierCV\n",
|
| 53 |
+
"import lightgbm as lgb\n",
|
| 54 |
+
"from packaging.version import Version\n",
|
| 55 |
+
"import sklearn\n",
|
| 56 |
+
"\n",
|
| 57 |
+
"def _lr(**kwargs):\n",
|
| 58 |
+
" if Version(sklearn.__version__) < Version(\"1.6\"):\n",
|
| 59 |
+
" kwargs['multi_class'] = 'multinomial'\n",
|
| 60 |
+
" return LogisticRegression(**kwargs)\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"warnings.filterwarnings('ignore')\n",
|
| 63 |
+
"print('All imports successful.')\n",
|
| 64 |
+
"print(f'sklearn version : {sklearn.__version__}')\n",
|
| 65 |
+
"print(f'lightgbm version: {lgb.__version__}')\n"
|
| 66 |
+
]
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"cell_type": "markdown",
|
| 70 |
+
"metadata": {},
|
| 71 |
+
"source": [
|
| 72 |
+
"## 2. Paths & Configuration\n",
|
| 73 |
+
"---"
|
| 74 |
+
]
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"outputs": [],
|
| 81 |
+
"source": [
|
| 82 |
+
"train_set_path = '/kaggle/input/comment-category-prediction-challenge/train.csv'\n",
|
| 83 |
+
"test_set_path = '/kaggle/input/comment-category-prediction-challenge/test.csv'\n",
|
| 84 |
+
"sample_path = '/kaggle/input/comment-category-prediction-challenge/Sample.csv'\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"if not os.path.exists(train_set_path):\n",
|
| 87 |
+
" train_set_path = '/kaggle/input/competitions/comment-category-prediction-challenge/train.csv'\n",
|
| 88 |
+
" test_set_path = '/kaggle/input/competitions/comment-category-prediction-challenge/test.csv'\n",
|
| 89 |
+
" sample_path = '/kaggle/input/competitions/comment-category-prediction-challenge/Sample.csv'\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"SEED = 42\n",
|
| 92 |
+
"N_FOLDS = 3 # matches the original 8h run (update-main.ipynb / Notebook-main.ipynb), NOT the 4 used in the 12h template\n",
|
| 93 |
+
"np.random.seed(SEED)\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"CLASS_NAMES = {0: 'Normal', 1: 'Offensive', 2: 'Hate Speech', 3: 'Severe/Violent'}\n",
|
| 96 |
+
"CLASS_LABELS = ['C-0 Normal', 'C-1 Offensive', 'C-2 Hate Speech', 'C-3 Severe/Violent']\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"LR_WORD_C = 5.395\n",
|
| 99 |
+
"LR_CHAR_C = 4.464\n",
|
| 100 |
+
"NBSVM_C = 2.0\n",
|
| 101 |
+
"lgb_class_weights = {0: 1.0, 1: 3.5, 2: 1.5, 3: 15.0}\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"print(\"Paths and configuration initialized.\")\n"
|
| 104 |
+
]
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "markdown",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"## 3. Data Loading\n",
|
| 111 |
+
"---"
|
| 112 |
+
]
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"outputs": [],
|
| 119 |
+
"source": [
|
| 120 |
+
"print(\"Loading datasets...\")\n",
|
| 121 |
+
"train_raw = pd.read_csv(train_set_path)\n",
|
| 122 |
+
"test_raw = pd.read_csv(test_set_path)\n",
|
| 123 |
+
"sample_sub = pd.read_csv(sample_path)\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"train_raw = train_raw.drop_duplicates(subset=['comment'], keep='first').reset_index(drop=True)\n",
|
| 126 |
+
"train_labels = train_raw['label'].values.astype(int)\n",
|
| 127 |
+
"train_features = train_raw.drop(columns=['label'])\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"print(f\"Train samples: {len(train_features):,}\")\n",
|
| 130 |
+
"print(f\"Test samples: {len(test_raw):,}\")\n"
|
| 131 |
+
]
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"cell_type": "markdown",
|
| 135 |
+
"metadata": {},
|
| 136 |
+
"source": [
|
| 137 |
+
"## 4. Text Preprocessing & Custom Transformers\n",
|
| 138 |
+
"---"
|
| 139 |
+
]
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
"cell_type": "code",
|
| 143 |
+
"execution_count": null,
|
| 144 |
+
"metadata": {},
|
| 145 |
+
"outputs": [],
|
| 146 |
+
"source": [
|
| 147 |
+
"LEET_MAP = str.maketrans({\n",
|
| 148 |
+
" '0': 'o', '1': 'i', '3': 'e', '4': 'a',\n",
|
| 149 |
+
" '5': 's', '7': 't', '@': 'a', '$': 's', '!': 'i'\n",
|
| 150 |
+
"})\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"ABBREV_MAP = {\n",
|
| 153 |
+
" 'u' : 'you',\n",
|
| 154 |
+
" 'r' : 'are',\n",
|
| 155 |
+
" 'ur' : 'your',\n",
|
| 156 |
+
" 'gonna': 'going to',\n",
|
| 157 |
+
" 'wanna': 'want to',\n",
|
| 158 |
+
" 'kys' : 'kill yourself',\n",
|
| 159 |
+
" 'kms' : 'kill myself',\n",
|
| 160 |
+
" 'wtf' : 'what the fuck',\n",
|
| 161 |
+
" 'stfu' : 'shut the fuck up',\n",
|
| 162 |
+
" 'idk' : 'i do not know',\n",
|
| 163 |
+
" 'ngl' : 'not gonna lie',\n",
|
| 164 |
+
"}\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"def expand_abbrevs(sentence):\n",
|
| 167 |
+
" words = sentence.split()\n",
|
| 168 |
+
" result = []\n",
|
| 169 |
+
" for w in words:\n",
|
| 170 |
+
" if w in ABBREV_MAP:\n",
|
| 171 |
+
" result.append(ABBREV_MAP[w])\n",
|
| 172 |
+
" else:\n",
|
| 173 |
+
" result.append(w)\n",
|
| 174 |
+
" return ' '.join(result)\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"def clean_text_column(df):\n",
|
| 177 |
+
" df = df.copy()\n",
|
| 178 |
+
" text = df['comment'].fillna('').astype(str)\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" text = text.str.lower()\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" text = text.str.replace(r'http\\S+|www\\.\\S+', ' ', regex=True)\n",
|
| 183 |
+
" text = text.str.replace(r'\\w+\\.(com|org|net|co|us)', ' ', regex=True)\n",
|
| 184 |
+
" text = text.str.replace(r'<[^>]+>', ' ', regex=True)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" text = text.apply(lambda s: s.translate(LEET_MAP))\n",
|
| 187 |
+
" text = text.apply(expand_abbrevs)\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" text = text.str.replace(r'[^a-z\\s]', ' ', regex=True)\n",
|
| 190 |
+
" text = text.str.replace(r'\\s+', ' ', regex=True).str.strip()\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" text = text.replace('', 'empty_comment').fillna('missing_comment')\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" df['comment_clean'] = text\n",
|
| 195 |
+
" return df\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"class NBTransformer(BaseEstimator, TransformerMixin):\n",
|
| 198 |
+
" def __init__(self, alpha=1.0):\n",
|
| 199 |
+
" self.alpha = alpha\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" def fit(self, X, y=None):\n",
|
| 202 |
+
" if y is None:\n",
|
| 203 |
+
" self.r_ = np.ones(X.shape[1], dtype=np.float32)\n",
|
| 204 |
+
" return self\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" labels = np.unique(y)\n",
|
| 207 |
+
" num_cols = X.shape[1]\n",
|
| 208 |
+
" ratios = np.zeros((len(labels), num_cols), dtype=np.float64)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" for i, lbl in enumerate(labels):\n",
|
| 211 |
+
" mask = (y == lbl)\n",
|
| 212 |
+
" p_counts = np.asarray(X[mask].sum(axis=0)).flatten() + self.alpha\n",
|
| 213 |
+
" n_counts = np.asarray(X[~mask].sum(axis=0)).flatten() + self.alpha\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" p_freq = p_counts / p_counts.sum()\n",
|
| 216 |
+
" n_freq = n_counts / n_counts.sum()\n",
|
| 217 |
+
" ratios[i] = np.log(p_freq) - np.log(n_freq)\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" self.r_ = np.abs(ratios).max(axis=0).astype(np.float32)\n",
|
| 220 |
+
" return self\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" def transform(self, X):\n",
|
| 223 |
+
" return X.multiply(self.r_)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"print('TextCleaner and NBTransformer ready.')\n"
|
| 226 |
+
]
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"cell_type": "markdown",
|
| 230 |
+
"metadata": {},
|
| 231 |
+
"source": [
|
| 232 |
+
"## 5. Feature Engineering\n",
|
| 233 |
+
"---"
|
| 234 |
+
]
|
| 235 |
+
},
|
| 236 |
+
{
|
| 237 |
+
"cell_type": "code",
|
| 238 |
+
"execution_count": null,
|
| 239 |
+
"metadata": {},
|
| 240 |
+
"outputs": [],
|
| 241 |
+
"source": [
|
| 242 |
+
"POSITIVE_WORDS = frozenset({\n",
|
| 243 |
+
" 'good','great','excellent','amazing','wonderful','best','love','perfect',\n",
|
| 244 |
+
" 'nice','fantastic','awesome','beautiful','brilliant','outstanding','happy',\n",
|
| 245 |
+
" 'glad','pleased','thankful','thanks','appreciate','agree','helpful','useful',\n",
|
| 246 |
+
" 'interesting','impressive','well','better','fine','cool','fun','enjoy',\n",
|
| 247 |
+
" 'liked','support','positive','fair','kind','respect','right','correct'\n",
|
| 248 |
+
"})\n",
|
| 249 |
+
"\n",
|
| 250 |
+
"NEGATIVE_WORDS = frozenset({\n",
|
| 251 |
+
" 'bad','terrible','awful','hate','worst','horrible','disgusting','poor',\n",
|
| 252 |
+
" 'pathetic','stupid','ugly','wrong','annoying','boring','dumb','useless',\n",
|
| 253 |
+
" 'trash','garbage','waste','sucks','lame','crap','fail','failed','worse',\n",
|
| 254 |
+
" 'angry','mad','upset','disappointed','sad','broken','ruined','ridiculous',\n",
|
| 255 |
+
" 'offensive','toxic','evil','idiot','fool','shut','die','kill'\n",
|
| 256 |
+
"})\n",
|
| 257 |
+
"\n",
|
| 258 |
+
"VIOLENCE_WORDS = frozenset({\n",
|
| 259 |
+
" 'kill','killed','killing','shoot','shooting','shot','death','dead','die',\n",
|
| 260 |
+
" 'dying','murder','murdered','murders','attack','attacking','attacked',\n",
|
| 261 |
+
" 'burn','burning','burned','fire','firing','guns','gun','weapon','weapons',\n",
|
| 262 |
+
" 'bomb','bombing','destroy','destroying','violence','violent','rape','hang',\n",
|
| 263 |
+
" 'hanging','decapitate','decapitated','torture','tortured','stab','stabbing',\n",
|
| 264 |
+
" 'threat','threaten'\n",
|
| 265 |
+
"})\n",
|
| 266 |
+
"\n",
|
| 267 |
+
"def count_unique(text):\n",
|
| 268 |
+
" return len(set(str(text).split()))\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"def count_pos(text):\n",
|
| 271 |
+
" words = str(text).split()\n",
|
| 272 |
+
" count = 0\n",
|
| 273 |
+
" for w in words:\n",
|
| 274 |
+
" if w in POSITIVE_WORDS:\n",
|
| 275 |
+
" count += 1\n",
|
| 276 |
+
" return count\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"def count_neg(text):\n",
|
| 279 |
+
" words = str(text).split()\n",
|
| 280 |
+
" count = 0\n",
|
| 281 |
+
" for w in words:\n",
|
| 282 |
+
" if w in NEGATIVE_WORDS:\n",
|
| 283 |
+
" count += 1\n",
|
| 284 |
+
" return count\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"def count_caps(text):\n",
|
| 287 |
+
" words = str(text).split()\n",
|
| 288 |
+
" count = 0\n",
|
| 289 |
+
" for w in words:\n",
|
| 290 |
+
" if w.isupper() and len(w) > 1:\n",
|
| 291 |
+
" count += 1\n",
|
| 292 |
+
" return count\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"def count_violence(text):\n",
|
| 295 |
+
" words = str(text).split()\n",
|
| 296 |
+
" count = 0\n",
|
| 297 |
+
" for w in words:\n",
|
| 298 |
+
" if w in VIOLENCE_WORDS:\n",
|
| 299 |
+
" count += 1\n",
|
| 300 |
+
" return count\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"def build_features(df):\n",
|
| 303 |
+
" df = df.copy()\n",
|
| 304 |
+
" raw = df['comment'].astype(str)\n",
|
| 305 |
+
" cln = df.get('comment_clean', raw.str.lower())\n",
|
| 306 |
+
"\n",
|
| 307 |
+
" word_count = cln.str.split().str.len().fillna(0).astype(int)\n",
|
| 308 |
+
"\n",
|
| 309 |
+
" if1 = df['if_1'].fillna(0)\n",
|
| 310 |
+
" if2 = df['if_2'].fillna(0)\n",
|
| 311 |
+
"\n",
|
| 312 |
+
" df['char_count'] = cln.str.len().astype(np.float32)\n",
|
| 313 |
+
" df['word_count'] = word_count.astype(np.float32)\n",
|
| 314 |
+
" df['unique_words'] = cln.apply(count_unique).astype(np.float32)\n",
|
| 315 |
+
" df['lexical_div'] = (df['unique_words'] / (word_count + 1)).astype(np.float32)\n",
|
| 316 |
+
" df['avg_word_len'] = (df['char_count'] / (word_count + 1)).astype(np.float32)\n",
|
| 317 |
+
"\n",
|
| 318 |
+
" df['caps_count'] = raw.str.count(r'[A-Z]').astype(np.float32)\n",
|
| 319 |
+
" df['caps_ratio'] = (df['caps_count'] / (df['char_count'] + 1)).astype(np.float32)\n",
|
| 320 |
+
" df['exclaim'] = raw.str.count('!').astype(np.float32)\n",
|
| 321 |
+
" df['question'] = raw.str.count(r'\\?').astype(np.float32)\n",
|
| 322 |
+
" df['punct_count'] = raw.str.count(r'[^\\w\\s]').astype(np.float32)\n",
|
| 323 |
+
" df['sent_count'] = raw.str.count(r'[.!?]+').clip(lower=1).astype(np.float32)\n",
|
| 324 |
+
" df['avg_sent_len'] = (word_count / (df['sent_count'] + 1)).astype(np.float32)\n",
|
| 325 |
+
" df['all_caps_words'] = raw.apply(count_caps).astype(np.float32)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
" df['pos_count'] = cln.apply(count_pos).astype(np.float32)\n",
|
| 328 |
+
" df['neg_count'] = cln.apply(count_neg).astype(np.float32)\n",
|
| 329 |
+
" df['sent_balance'] = (df['pos_count'] - df['neg_count']).astype(np.float32)\n",
|
| 330 |
+
"\n",
|
| 331 |
+
" df['violence_count'] = cln.apply(count_violence).astype(np.float32)\n",
|
| 332 |
+
" df['has_violence'] = (df['violence_count'] > 0).astype(np.int8)\n",
|
| 333 |
+
" df['violence_ratio'] = (df['violence_count'] / (word_count + 1)).astype(np.float32)\n",
|
| 334 |
+
" df['violence_score'] = (\n",
|
| 335 |
+
" df['violence_count'] * 2.0 + df['violence_ratio'] * 10.0\n",
|
| 336 |
+
" ).astype(np.float32)\n",
|
| 337 |
+
" df['if1_x_violence'] = (if1 * df['violence_count']).astype(np.float32)\n",
|
| 338 |
+
"\n",
|
| 339 |
+
" df['upvote'] = df['upvote'].fillna(0)\n",
|
| 340 |
+
" df['downvote'] = df['downvote'].fillna(0)\n",
|
| 341 |
+
"\n",
|
| 342 |
+
" df['total_votes'] = (df['upvote'] + df['downvote']).astype(np.float32)\n",
|
| 343 |
+
" df['vote_ratio'] = (df['upvote'] / (df['total_votes'] + 1)).astype(np.float32)\n",
|
| 344 |
+
" df['zero_downvote'] = (df['downvote'] == 0).astype(np.int8)\n",
|
| 345 |
+
" df['controversy'] = np.minimum(df['upvote'], df['downvote']).astype(np.float32) * 2\n",
|
| 346 |
+
"\n",
|
| 347 |
+
" emo_cols = ['emoticon_1', 'emoticon_2', 'emoticon_3']\n",
|
| 348 |
+
" df[emo_cols] = df[emo_cols].fillna(0)\n",
|
| 349 |
+
" df['total_emo'] = df[emo_cols].sum(axis=1).astype(np.float32)\n",
|
| 350 |
+
" df['has_emo'] = (df['total_emo'] > 0).astype(np.int8)\n",
|
| 351 |
+
"\n",
|
| 352 |
+
" parsed_dt = pd.to_datetime(df['created_date'], errors='coerce')\n",
|
| 353 |
+
" hour = parsed_dt.dt.hour.fillna(12).astype(int)\n",
|
| 354 |
+
" day_of_week = parsed_dt.dt.dayofweek.fillna(3).astype(int)\n",
|
| 355 |
+
"\n",
|
| 356 |
+
" df['hour_sin']= np.sin(2 * np.pi * hour / 24).astype(np.float32)\n",
|
| 357 |
+
" df['hour_cos'] = np.cos(2 * np.pi * hour / 24).astype(np.float32)\n",
|
| 358 |
+
" df['dow_sin'] = np.sin(2 * np.pi * day_of_week / 7).astype(np.float32)\n",
|
| 359 |
+
" df['is_weekend'] = (day_of_week >= 5).astype(np.int8)\n",
|
| 360 |
+
"\n",
|
| 361 |
+
" race_col = df['race'].fillna('_').str.lower()\n",
|
| 362 |
+
" religion_col = df['religion'].fillna('_').str.lower()\n",
|
| 363 |
+
" gender_col = df['gender'].fillna('_').str.lower()\n",
|
| 364 |
+
"\n",
|
| 365 |
+
" has_race = (race_col != '_') & (race_col != 'none')\n",
|
| 366 |
+
" has_religion = (religion_col != '_') & (religion_col != 'none')\n",
|
| 367 |
+
" has_gender = (gender_col != '_') & (gender_col != 'none')\n",
|
| 368 |
+
"\n",
|
| 369 |
+
" df['has_identity'] = (has_race | has_religion | has_gender).astype(np.int8)\n",
|
| 370 |
+
" df['identity_count'] = (\n",
|
| 371 |
+
" has_race.astype(int) + has_religion.astype(int) + has_gender.astype(int)\n",
|
| 372 |
+
" ).astype(np.int8)\n",
|
| 373 |
+
" df['disability_flag'] = (\n",
|
| 374 |
+
" df['disability'].map({True: 1, False: 0, 'True': 1, 'False': 0}).fillna(0)\n",
|
| 375 |
+
" ).astype(np.int8)\n",
|
| 376 |
+
"\n",
|
| 377 |
+
" df['if_prod'] = (if1 * if2).astype(np.float32)\n",
|
| 378 |
+
" df['if_ratio'] = (if1 / (if2 + 1)).astype(np.float32)\n",
|
| 379 |
+
" df['if_sum'] = (if1 + if2).astype(np.float32)\n",
|
| 380 |
+
"\n",
|
| 381 |
+
" df['zone_safe'] = (if2 <= 7).astype(np.int8)\n",
|
| 382 |
+
" df['zone_c1_trigger'] = ((if2 >= 8) & (if1.isin([4, 6, 10]))).astype(np.int8)\n",
|
| 383 |
+
" df['zone_c23'] = ((if1 == 0) & (if2 >= 8)).astype(np.int8)\n",
|
| 384 |
+
" df['if1_low'] = (if1 <= 1).astype(np.int8)\n",
|
| 385 |
+
" df['if1_nonzero'] = (if1 > 0).astype(np.int8)\n",
|
| 386 |
+
"\n",
|
| 387 |
+
" df['golden_c1'] = ((if2 >= 8) & df['has_identity'].astype(bool)).astype(np.int8)\n",
|
| 388 |
+
" df['golden_c2'] = ((if2 >= 8) & ~df['has_identity'].astype(bool)).astype(np.int8)\n",
|
| 389 |
+
"\n",
|
| 390 |
+
" df['is_short'] = (word_count <= 15).astype(np.int8)\n",
|
| 391 |
+
" df['short_violent'] = (df['is_short'] * df['has_violence']).astype(np.int8)\n",
|
| 392 |
+
"\n",
|
| 393 |
+
" df['danger_zone'] = ((df['zone_c23'] == 1) & (df['has_identity'] == 0)).astype(np.int8)\n",
|
| 394 |
+
" df['violence_in_dz'] = (df['violence_count'] * df['danger_zone']).astype(np.float32)\n",
|
| 395 |
+
" df['c3_signal'] = (df['is_short'] * df['zero_downvote'] * (df['has_identity'] == 0) * df['zone_c23']).astype(np.int8)\n",
|
| 396 |
+
"\n",
|
| 397 |
+
" numeric_dtype_cols = df.select_dtypes(include=[np.number]).columns\n",
|
| 398 |
+
" df[numeric_dtype_cols] = df[numeric_dtype_cols].fillna(0)\n",
|
| 399 |
+
"\n",
|
| 400 |
+
" return df\n",
|
| 401 |
+
"\n",
|
| 402 |
+
"print('FeatureEngineer ready.')\n"
|
| 403 |
+
]
|
| 404 |
+
},
|
| 405 |
+
{
|
| 406 |
+
"cell_type": "markdown",
|
| 407 |
+
"metadata": {},
|
| 408 |
+
"source": [
|
| 409 |
+
"## 6. Vectorization & Feature Matrix Assembly\n",
|
| 410 |
+
"---"
|
| 411 |
+
]
|
| 412 |
+
},
|
| 413 |
+
{
|
| 414 |
+
"cell_type": "code",
|
| 415 |
+
"execution_count": null,
|
| 416 |
+
"metadata": {},
|
| 417 |
+
"outputs": [],
|
| 418 |
+
"source": [
|
| 419 |
+
"print('Running clean_text_column and build_features...')\n",
|
| 420 |
+
"train_engineered = build_features(clean_text_column(train_features))\n",
|
| 421 |
+
"test_engineered = build_features(clean_text_column(test_raw))\n",
|
| 422 |
+
"\n",
|
| 423 |
+
"train_text = train_engineered['comment_clean'].values\n",
|
| 424 |
+
"test_text = test_engineered['comment_clean'].values\n",
|
| 425 |
+
"\n",
|
| 426 |
+
"print('Building TF-IDF matrices...')\n",
|
| 427 |
+
"tfidf_word = TfidfVectorizer(\n",
|
| 428 |
+
" max_features=35000,\n",
|
| 429 |
+
" ngram_range=(1, 2),\n",
|
| 430 |
+
" min_df=2,\n",
|
| 431 |
+
" max_df=0.92,\n",
|
| 432 |
+
" sublinear_tf=True,\n",
|
| 433 |
+
" strip_accents='unicode',\n",
|
| 434 |
+
" dtype=np.float32\n",
|
| 435 |
+
")\n",
|
| 436 |
+
"\n",
|
| 437 |
+
"tfidf_char = TfidfVectorizer(\n",
|
| 438 |
+
" max_features=10000,\n",
|
| 439 |
+
" analyzer='char_wb',\n",
|
| 440 |
+
" ngram_range=(3, 5),\n",
|
| 441 |
+
" min_df=3,\n",
|
| 442 |
+
" dtype=np.float32\n",
|
| 443 |
+
")\n",
|
| 444 |
+
"\n",
|
| 445 |
+
"tfidf_phrase = TfidfVectorizer(\n",
|
| 446 |
+
" max_features=10000,\n",
|
| 447 |
+
" ngram_range=(2, 3),\n",
|
| 448 |
+
" min_df=3,\n",
|
| 449 |
+
" max_df=0.92,\n",
|
| 450 |
+
" sublinear_tf=True,\n",
|
| 451 |
+
" dtype=np.float32\n",
|
| 452 |
+
")\n",
|
| 453 |
+
"\n",
|
| 454 |
+
"train_tfidf = hstack([\n",
|
| 455 |
+
" tfidf_word.fit_transform(train_text),\n",
|
| 456 |
+
" tfidf_char.fit_transform(train_text),\n",
|
| 457 |
+
" tfidf_phrase.fit_transform(train_text)\n",
|
| 458 |
+
"])\n",
|
| 459 |
+
"\n",
|
| 460 |
+
"test_tfidf = hstack([\n",
|
| 461 |
+
" tfidf_word.transform(test_text),\n",
|
| 462 |
+
" tfidf_char.transform(test_text),\n",
|
| 463 |
+
" tfidf_phrase.transform(test_text)\n",
|
| 464 |
+
"])\n",
|
| 465 |
+
"\n",
|
| 466 |
+
"EXCLUDE_COLS = {\n",
|
| 467 |
+
" 'comment', 'comment_clean', 'created_date',\n",
|
| 468 |
+
" 'post_id', 'race', 'religion', 'gender', 'disability'\n",
|
| 469 |
+
"}\n",
|
| 470 |
+
"numeric_col_names = [\n",
|
| 471 |
+
" col for col in train_engineered.columns\n",
|
| 472 |
+
" if col not in EXCLUDE_COLS\n",
|
| 473 |
+
" and train_engineered[col].dtype in [\n",
|
| 474 |
+
" np.float64, np.int64, np.float32, np.int32, np.int8\n",
|
| 475 |
+
" ]\n",
|
| 476 |
+
"]\n",
|
| 477 |
+
"\n",
|
| 478 |
+
"train_num_scaled = train_engineered[numeric_col_names].values.astype(np.float32)\n",
|
| 479 |
+
"test_num_scaled = test_engineered[numeric_col_names].values.astype(np.float32)\n",
|
| 480 |
+
"\n",
|
| 481 |
+
"cat_col_names = ['race', 'religion', 'gender']\n",
|
| 482 |
+
"ordinal_enc = OrdinalEncoder(\n",
|
| 483 |
+
" handle_unknown='use_encoded_value',\n",
|
| 484 |
+
" unknown_value=-1\n",
|
| 485 |
+
")\n",
|
| 486 |
+
"\n",
|
| 487 |
+
"train_cats = ordinal_enc.fit_transform(\n",
|
| 488 |
+
" train_engineered[cat_col_names].fillna('missing').astype(str)).astype(np.int32)\n",
|
| 489 |
+
"test_cats = ordinal_enc.transform(\n",
|
| 490 |
+
" test_engineered[cat_col_names].fillna('missing').astype(str)).astype(np.int32)\n",
|
| 491 |
+
"\n",
|
| 492 |
+
"X_train_full = hstack([\n",
|
| 493 |
+
" train_tfidf,\n",
|
| 494 |
+
" csr_matrix(train_num_scaled),\n",
|
| 495 |
+
" csr_matrix(train_cats)\n",
|
| 496 |
+
"]).tocsr()\n",
|
| 497 |
+
"\n",
|
| 498 |
+
"X_test_full = hstack([\n",
|
| 499 |
+
" test_tfidf,\n",
|
| 500 |
+
" csr_matrix(test_num_scaled),\n",
|
| 501 |
+
" csr_matrix(test_cats)\n",
|
| 502 |
+
"]).tocsr()\n",
|
| 503 |
+
"\n",
|
| 504 |
+
"del train_tfidf, test_tfidf, train_num_scaled, test_num_scaled\n",
|
| 505 |
+
"del train_engineered, test_engineered\n",
|
| 506 |
+
"gc.collect()\n",
|
| 507 |
+
"\n",
|
| 508 |
+
"print(f'X_train_full shape: {X_train_full.shape}')\n",
|
| 509 |
+
"print(f'X_test_full shape: {X_test_full.shape}')\n"
|
| 510 |
+
]
|
| 511 |
+
},
|
| 512 |
+
{
|
| 513 |
+
"cell_type": "markdown",
|
| 514 |
+
"metadata": {},
|
| 515 |
+
"source": [
|
| 516 |
+
"## 7. Stratified K-Fold Stacking CV (7 Base Models) \u2014 models kept for deployment\n",
|
| 517 |
+
"---\n",
|
| 518 |
+
"This is the only training pass. Each fold's fitted model is appended to a list instead of being\n",
|
| 519 |
+
"discarded, so after CV finishes we already have a deployable bagged ensemble (3 fitted copies per\n",
|
| 520 |
+
"base learner) with zero extra training cost. This is exactly what the original notebook did to\n",
|
| 521 |
+
"build its `tst_*` test predictions \u2014 the only change here is that we keep the fitted objects\n",
|
| 522 |
+
"instead of throwing them away after computing OOF/test probabilities."
|
| 523 |
+
]
|
| 524 |
+
},
|
| 525 |
+
{
|
| 526 |
+
"cell_type": "code",
|
| 527 |
+
"execution_count": null,
|
| 528 |
+
"metadata": {},
|
| 529 |
+
"outputs": [],
|
| 530 |
+
"source": [
|
| 531 |
+
"print(f'{N_FOLDS}-FOLD STRATIFIED CV : 7 BASE MODELS (models retained for deployment)')\n",
|
| 532 |
+
"print('=' * 60)\n",
|
| 533 |
+
"\n",
|
| 534 |
+
"kfold = StratifiedKFold(n_splits=N_FOLDS, shuffle=True, random_state=SEED)\n",
|
| 535 |
+
"n_train = X_train_full.shape[0]\n",
|
| 536 |
+
"n_test = X_test_full.shape[0]\n",
|
| 537 |
+
"\n",
|
| 538 |
+
"oof_lgb = np.zeros((n_train, 4), dtype=np.float32)\n",
|
| 539 |
+
"oof_lr_w = np.zeros((n_train, 4), dtype=np.float32)\n",
|
| 540 |
+
"oof_lr_c = np.zeros((n_train, 4), dtype=np.float32)\n",
|
| 541 |
+
"oof_nbsvm = np.zeros((n_train, 4), dtype=np.float32)\n",
|
| 542 |
+
"oof_lgb_bin = np.zeros((n_train, 2), dtype=np.float32)\n",
|
| 543 |
+
"oof_c23 = np.zeros((n_train, 2), dtype=np.float32)\n",
|
| 544 |
+
"oof_svc = np.zeros((n_train, 4), dtype=np.float32)\n",
|
| 545 |
+
"\n",
|
| 546 |
+
"tst_lgb = np.zeros((n_test, 4), dtype=np.float32)\n",
|
| 547 |
+
"tst_lr_w = np.zeros((n_test, 4), dtype=np.float32)\n",
|
| 548 |
+
"tst_lr_c = np.zeros((n_test, 4), dtype=np.float32)\n",
|
| 549 |
+
"tst_nbsvm = np.zeros((n_test, 4), dtype=np.float32)\n",
|
| 550 |
+
"tst_lgb_bin = np.zeros((n_test, 2), dtype=np.float32)\n",
|
| 551 |
+
"tst_c23 = np.zeros((n_test, 2), dtype=np.float32)\n",
|
| 552 |
+
"tst_svc = np.zeros((n_test, 4), dtype=np.float32)\n",
|
| 553 |
+
"\n",
|
| 554 |
+
"# Fold-model registries -- these ARE the deployment artifact, no separate refit needed.\n",
|
| 555 |
+
"fold_lgb_models = []\n",
|
| 556 |
+
"fold_lr_word_models = []\n",
|
| 557 |
+
"fold_lr_char_models = []\n",
|
| 558 |
+
"fold_nbsvm_models = []\n",
|
| 559 |
+
"fold_lgb_bin_models = []\n",
|
| 560 |
+
"fold_c23_models = []\n",
|
| 561 |
+
"fold_svc_models = []\n",
|
| 562 |
+
"\n",
|
| 563 |
+
"LGB_PARAMS = dict(\n",
|
| 564 |
+
" objective='multiclass',\n",
|
| 565 |
+
" num_class=4,\n",
|
| 566 |
+
" n_estimators=1000,\n",
|
| 567 |
+
" learning_rate=0.03,\n",
|
| 568 |
+
" num_leaves=127,\n",
|
| 569 |
+
" max_depth=-1,\n",
|
| 570 |
+
" max_bin=127,\n",
|
| 571 |
+
" colsample_bytree=0.5,\n",
|
| 572 |
+
" subsample=0.9,\n",
|
| 573 |
+
" subsample_freq=1,\n",
|
| 574 |
+
" min_child_samples=10,\n",
|
| 575 |
+
" class_weight=lgb_class_weights,\n",
|
| 576 |
+
" reg_alpha=0.0,\n",
|
| 577 |
+
" reg_lambda=0.0,\n",
|
| 578 |
+
" random_state=SEED,\n",
|
| 579 |
+
" n_jobs=-1,\n",
|
| 580 |
+
" verbose=-1\n",
|
| 581 |
+
")\n",
|
| 582 |
+
"\n",
|
| 583 |
+
"for fold_num, (train_idx, val_idx) in enumerate(kfold.split(X_train_full, train_labels), 1):\n",
|
| 584 |
+
" print(f'\\n FOLD {fold_num}/{N_FOLDS}')\n",
|
| 585 |
+
"\n",
|
| 586 |
+
" y_train = train_labels[train_idx]\n",
|
| 587 |
+
" y_val = train_labels[val_idx]\n",
|
| 588 |
+
"\n",
|
| 589 |
+
" # [1/7] LightGBM Multiclass\n",
|
| 590 |
+
" print(' [1/7] LightGBM \u2014 full feature matrix')\n",
|
| 591 |
+
" X_tr_lgb = X_train_full[train_idx]\n",
|
| 592 |
+
" X_va_lgb = X_train_full[val_idx]\n",
|
| 593 |
+
" cat_feature_indices = [\n",
|
| 594 |
+
" X_train_full.shape[1] - 3,\n",
|
| 595 |
+
" X_train_full.shape[1] - 2,\n",
|
| 596 |
+
" X_train_full.shape[1] - 1\n",
|
| 597 |
+
" ]\n",
|
| 598 |
+
" lgb_model = lgb.LGBMClassifier(**LGB_PARAMS)\n",
|
| 599 |
+
" lgb_model.fit(\n",
|
| 600 |
+
" X_tr_lgb, y_train,\n",
|
| 601 |
+
" eval_set=[(X_va_lgb, y_val)],\n",
|
| 602 |
+
" callbacks=[\n",
|
| 603 |
+
" lgb.early_stopping(30, verbose=False),\n",
|
| 604 |
+
" lgb.log_evaluation(0)\n",
|
| 605 |
+
" ],\n",
|
| 606 |
+
" categorical_feature=cat_feature_indices\n",
|
| 607 |
+
" )\n",
|
| 608 |
+
" oof_lgb[val_idx] = lgb_model.predict_proba(X_va_lgb)\n",
|
| 609 |
+
" tst_lgb += lgb_model.predict_proba(X_test_full) / N_FOLDS\n",
|
| 610 |
+
" fold_lgb_models.append(lgb_model)\n",
|
| 611 |
+
" del X_tr_lgb, X_va_lgb\n",
|
| 612 |
+
" gc.collect()\n",
|
| 613 |
+
"\n",
|
| 614 |
+
" # [2/7] LR-Word\n",
|
| 615 |
+
" print(' [2/7] LR-Word \u2014 60k word n-grams')\n",
|
| 616 |
+
" lr_word = Pipeline([\n",
|
| 617 |
+
" ('tfidf', TfidfVectorizer(\n",
|
| 618 |
+
" max_features=60000,\n",
|
| 619 |
+
" ngram_range=(1, 3),\n",
|
| 620 |
+
" sublinear_tf=True,\n",
|
| 621 |
+
" min_df=2,\n",
|
| 622 |
+
" max_df=0.95,\n",
|
| 623 |
+
" strip_accents='unicode',\n",
|
| 624 |
+
" token_pattern=r'(?u)\\b\\w+\\b',\n",
|
| 625 |
+
" dtype=np.float32\n",
|
| 626 |
+
" )),\n",
|
| 627 |
+
" ('lr', _lr(\n",
|
| 628 |
+
" C=LR_WORD_C,\n",
|
| 629 |
+
" class_weight='balanced',\n",
|
| 630 |
+
" solver='liblinear',\n",
|
| 631 |
+
" max_iter=1000,\n",
|
| 632 |
+
" dual=False,\n",
|
| 633 |
+
" tol=1e-3,\n",
|
| 634 |
+
" random_state=SEED\n",
|
| 635 |
+
" ))\n",
|
| 636 |
+
" ])\n",
|
| 637 |
+
" lr_word.fit(train_text[train_idx], y_train)\n",
|
| 638 |
+
" oof_lr_w[val_idx] = lr_word.predict_proba(train_text[val_idx])\n",
|
| 639 |
+
" tst_lr_w += lr_word.predict_proba(test_text) / N_FOLDS\n",
|
| 640 |
+
" fold_lr_word_models.append(lr_word)\n",
|
| 641 |
+
" gc.collect()\n",
|
| 642 |
+
"\n",
|
| 643 |
+
" # [3/7] LR-Char\n",
|
| 644 |
+
" print(' [3/7] LR-Char \u2014 30k character n-grams')\n",
|
| 645 |
+
" lr_char = Pipeline([\n",
|
| 646 |
+
" ('tfidf', TfidfVectorizer(\n",
|
| 647 |
+
" max_features=30000,\n",
|
| 648 |
+
" analyzer='char',\n",
|
| 649 |
+
" ngram_range=(3, 6),\n",
|
| 650 |
+
" sublinear_tf=True,\n",
|
| 651 |
+
" min_df=5,\n",
|
| 652 |
+
" dtype=np.float32\n",
|
| 653 |
+
" )),\n",
|
| 654 |
+
" ('lr', _lr(\n",
|
| 655 |
+
" C=LR_CHAR_C,\n",
|
| 656 |
+
" class_weight='balanced',\n",
|
| 657 |
+
" solver='lbfgs',\n",
|
| 658 |
+
" max_iter=1000,\n",
|
| 659 |
+
" random_state=SEED\n",
|
| 660 |
+
" ))\n",
|
| 661 |
+
" ])\n",
|
| 662 |
+
" lr_char.fit(train_text[train_idx], y_train)\n",
|
| 663 |
+
" oof_lr_c[val_idx] = lr_char.predict_proba(train_text[val_idx])\n",
|
| 664 |
+
" tst_lr_c += lr_char.predict_proba(test_text) / N_FOLDS\n",
|
| 665 |
+
" fold_lr_char_models.append(lr_char)\n",
|
| 666 |
+
" gc.collect()\n",
|
| 667 |
+
"\n",
|
| 668 |
+
" # [4/7] NB-SVM\n",
|
| 669 |
+
" print(' [4/7] NB-SVM \u2014 NB feature weighting + LR')\n",
|
| 670 |
+
" nbsvm = Pipeline([\n",
|
| 671 |
+
" ('tfidf', TfidfVectorizer(\n",
|
| 672 |
+
" max_features=50000,\n",
|
| 673 |
+
" ngram_range=(1, 2),\n",
|
| 674 |
+
" sublinear_tf=True,\n",
|
| 675 |
+
" min_df=2,\n",
|
| 676 |
+
" max_df=0.95,\n",
|
| 677 |
+
" strip_accents='unicode',\n",
|
| 678 |
+
" dtype=np.float32\n",
|
| 679 |
+
" )),\n",
|
| 680 |
+
" ('nb', NBTransformer(alpha=1.0)),\n",
|
| 681 |
+
" ('lr', _lr(\n",
|
| 682 |
+
" C=NBSVM_C,\n",
|
| 683 |
+
" class_weight='balanced',\n",
|
| 684 |
+
" solver='lbfgs',\n",
|
| 685 |
+
" max_iter=1000,\n",
|
| 686 |
+
" random_state=SEED\n",
|
| 687 |
+
" ))\n",
|
| 688 |
+
" ])\n",
|
| 689 |
+
" nbsvm.fit(train_text[train_idx], y_train)\n",
|
| 690 |
+
" oof_nbsvm[val_idx] = nbsvm.predict_proba(train_text[val_idx])\n",
|
| 691 |
+
" tst_nbsvm += nbsvm.predict_proba(test_text) / N_FOLDS\n",
|
| 692 |
+
" fold_nbsvm_models.append(nbsvm)\n",
|
| 693 |
+
" gc.collect()\n",
|
| 694 |
+
"\n",
|
| 695 |
+
" # [5/7] LGB-Binary\n",
|
| 696 |
+
" print(' [5/7] LGB-Binary \u2014 Class 3 vs rest')\n",
|
| 697 |
+
" y_train_lgb_bin = (y_train == 3).astype(int)\n",
|
| 698 |
+
" y_val_lgb_bin = (y_val == 3).astype(int)\n",
|
| 699 |
+
" lgb_bin_model = lgb.LGBMClassifier(\n",
|
| 700 |
+
" objective='binary',\n",
|
| 701 |
+
" n_estimators=500,\n",
|
| 702 |
+
" learning_rate=0.03,\n",
|
| 703 |
+
" num_leaves=63,\n",
|
| 704 |
+
" max_bin=127,\n",
|
| 705 |
+
" colsample_bytree=0.4,\n",
|
| 706 |
+
" subsample=0.8,\n",
|
| 707 |
+
" subsample_freq=1,\n",
|
| 708 |
+
" min_child_samples=20,\n",
|
| 709 |
+
" class_weight={0: 1, 1: 20},\n",
|
| 710 |
+
" random_state=SEED,\n",
|
| 711 |
+
" n_jobs=-1,\n",
|
| 712 |
+
" verbose=-1\n",
|
| 713 |
+
" )\n",
|
| 714 |
+
" lgb_bin_model.fit(\n",
|
| 715 |
+
" X_train_full[train_idx], y_train_lgb_bin,\n",
|
| 716 |
+
" eval_set=[(X_train_full[val_idx], y_val_lgb_bin)],\n",
|
| 717 |
+
" callbacks=[lgb.early_stopping(30, verbose=False)]\n",
|
| 718 |
+
" )\n",
|
| 719 |
+
" oof_lgb_bin[val_idx] = lgb_bin_model.predict_proba(X_train_full[val_idx])\n",
|
| 720 |
+
" tst_lgb_bin += lgb_bin_model.predict_proba(X_test_full) / N_FOLDS\n",
|
| 721 |
+
" fold_lgb_bin_models.append(lgb_bin_model)\n",
|
| 722 |
+
" gc.collect()\n",
|
| 723 |
+
"\n",
|
| 724 |
+
" # [6/7] LGB C3 vs C2 Specialist\n",
|
| 725 |
+
" print(' [6/7] LGB C3vC2 \u2014 Class 3 vs Class 2 specialist')\n",
|
| 726 |
+
" c23_train_mask = (y_train == 2) | (y_train == 3)\n",
|
| 727 |
+
" c23_val_mask = (y_val == 2) | (y_val == 3)\n",
|
| 728 |
+
" y_train_c23 = (y_train[c23_train_mask] == 3).astype(int)\n",
|
| 729 |
+
" y_val_c23 = (y_val[c23_val_mask] == 3).astype(int)\n",
|
| 730 |
+
" lgb_c23_model = lgb.LGBMClassifier(\n",
|
| 731 |
+
" objective='binary',\n",
|
| 732 |
+
" n_estimators=500,\n",
|
| 733 |
+
" learning_rate=0.03,\n",
|
| 734 |
+
" num_leaves=63,\n",
|
| 735 |
+
" max_bin=127,\n",
|
| 736 |
+
" colsample_bytree=0.4,\n",
|
| 737 |
+
" subsample=0.8,\n",
|
| 738 |
+
" subsample_freq=1,\n",
|
| 739 |
+
" min_child_samples=20,\n",
|
| 740 |
+
" class_weight={0: 1, 1: 12},\n",
|
| 741 |
+
" random_state=SEED,\n",
|
| 742 |
+
" n_jobs=-1,\n",
|
| 743 |
+
" verbose=-1\n",
|
| 744 |
+
" )\n",
|
| 745 |
+
" lgb_c23_model.fit(\n",
|
| 746 |
+
" X_train_full[train_idx][c23_train_mask], y_train_c23,\n",
|
| 747 |
+
" eval_set=[(X_train_full[val_idx][c23_val_mask], y_val_c23)],\n",
|
| 748 |
+
" callbacks=[lgb.early_stopping(30, verbose=False)]\n",
|
| 749 |
+
" )\n",
|
| 750 |
+
" oof_c23[val_idx] = lgb_c23_model.predict_proba(X_train_full[val_idx])\n",
|
| 751 |
+
" tst_c23 += lgb_c23_model.predict_proba(X_test_full) / N_FOLDS\n",
|
| 752 |
+
" fold_c23_models.append(lgb_c23_model)\n",
|
| 753 |
+
" gc.collect()\n",
|
| 754 |
+
"\n",
|
| 755 |
+
" # [7/7] LinearSVC (Calibrated)\n",
|
| 756 |
+
" print(' [7/7] LinearSVC \u2014 calibrated probability output')\n",
|
| 757 |
+
" svc_base = LinearSVC(C=0.184, class_weight='balanced', max_iter=1000, random_state=SEED)\n",
|
| 758 |
+
" p_svc = Pipeline([\n",
|
| 759 |
+
" ('tfidf', TfidfVectorizer(\n",
|
| 760 |
+
" max_features=50000,\n",
|
| 761 |
+
" ngram_range=(1, 2),\n",
|
| 762 |
+
" sublinear_tf=True,\n",
|
| 763 |
+
" min_df=2,\n",
|
| 764 |
+
" max_df=0.95,\n",
|
| 765 |
+
" strip_accents='unicode',\n",
|
| 766 |
+
" dtype=np.float32\n",
|
| 767 |
+
" )),\n",
|
| 768 |
+
" ('svc', CalibratedClassifierCV(svc_base, method='sigmoid', cv=2))\n",
|
| 769 |
+
" ])\n",
|
| 770 |
+
" p_svc.fit(train_text[train_idx], y_train)\n",
|
| 771 |
+
" oof_svc[val_idx] = p_svc.predict_proba(train_text[val_idx])\n",
|
| 772 |
+
" tst_svc += p_svc.predict_proba(test_text) / N_FOLDS\n",
|
| 773 |
+
" fold_svc_models.append(p_svc)\n",
|
| 774 |
+
" gc.collect()\n",
|
| 775 |
+
"\n",
|
| 776 |
+
"print(\"\\nOOF predictions completed for all 7 base models.\")\n",
|
| 777 |
+
"print(f\"Retained {N_FOLDS} fitted copies per base learner for the deployment artifact.\")\n"
|
| 778 |
+
]
|
| 779 |
+
},
|
| 780 |
+
{
|
| 781 |
+
"cell_type": "markdown",
|
| 782 |
+
"metadata": {},
|
| 783 |
+
"source": [
|
| 784 |
+
"## 8. Meta-Learner & Threshold Multipliers\n",
|
| 785 |
+
"---\n",
|
| 786 |
+
"No separate full-data base-model refit stage. The meta-learner is small (24 stacked probability\n",
|
| 787 |
+
"columns \u2192 4 classes) so retraining it on 100% of the OOF matrix is cheap and matches the original\n",
|
| 788 |
+
"notebook's approach."
|
| 789 |
+
]
|
| 790 |
+
},
|
| 791 |
+
{
|
| 792 |
+
"cell_type": "code",
|
| 793 |
+
"execution_count": null,
|
| 794 |
+
"metadata": {},
|
| 795 |
+
"outputs": [],
|
| 796 |
+
"source": [
|
| 797 |
+
"print('META-LEARNER + THRESHOLD APPLICATION')\n",
|
| 798 |
+
"print('=' * 60)\n",
|
| 799 |
+
"\n",
|
| 800 |
+
"stacked_train = np.hstack([oof_lgb, oof_lr_w, oof_lr_c, oof_nbsvm,\n",
|
| 801 |
+
" oof_lgb_bin, oof_svc, oof_c23]).astype(np.float32)\n",
|
| 802 |
+
"stacked_test = np.hstack([tst_lgb, tst_lr_w, tst_lr_c, tst_nbsvm,\n",
|
| 803 |
+
" tst_lgb_bin, tst_svc, tst_c23]).astype(np.float32)\n",
|
| 804 |
+
"\n",
|
| 805 |
+
"print(f'Stacked train shape: {stacked_train.shape}')\n",
|
| 806 |
+
"print(f'Stacked test shape: {stacked_test.shape}')\n",
|
| 807 |
+
"\n",
|
| 808 |
+
"lgb_meta_params = dict(\n",
|
| 809 |
+
" objective='multiclass',\n",
|
| 810 |
+
" num_class=4,\n",
|
| 811 |
+
" num_leaves=16,\n",
|
| 812 |
+
" n_estimators=100,\n",
|
| 813 |
+
" learning_rate=0.05,\n",
|
| 814 |
+
" min_child_samples=200,\n",
|
| 815 |
+
" random_state=SEED,\n",
|
| 816 |
+
" n_jobs=-1,\n",
|
| 817 |
+
" verbose=-1\n",
|
| 818 |
+
")\n",
|
| 819 |
+
"\n",
|
| 820 |
+
"# OOF sanity check of the meta-learner before committing to the final fit\n",
|
| 821 |
+
"meta_kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED + 99)\n",
|
| 822 |
+
"meta_oof_preds = np.zeros((n_train, 4), dtype=np.float32)\n",
|
| 823 |
+
"for tr_m, va_m in meta_kfold.split(stacked_train, train_labels):\n",
|
| 824 |
+
" lgb_meta = lgb.LGBMClassifier(**lgb_meta_params)\n",
|
| 825 |
+
" lgb_meta.fit(stacked_train[tr_m], train_labels[tr_m])\n",
|
| 826 |
+
" meta_oof_preds[va_m] = lgb_meta.predict_proba(stacked_train[va_m])\n",
|
| 827 |
+
"\n",
|
| 828 |
+
"meta_oof_f1 = f1_score(train_labels, meta_oof_preds.argmax(1), average='macro')\n",
|
| 829 |
+
"print(f'\\nMeta OOF F1 (base, before threshold tuning): {meta_oof_f1:.4f}')\n",
|
| 830 |
+
"print(classification_report(train_labels, meta_oof_preds.argmax(1), digits=4))\n",
|
| 831 |
+
"\n",
|
| 832 |
+
"final_meta = lgb.LGBMClassifier(**lgb_meta_params)\n",
|
| 833 |
+
"final_meta.fit(stacked_train, train_labels)\n",
|
| 834 |
+
"\n",
|
| 835 |
+
"BEST_MULTS = [1.032, 0.951, 0.85, 1.25]\n",
|
| 836 |
+
"\n",
|
| 837 |
+
"meta_oof_adj = meta_oof_preds.copy()\n",
|
| 838 |
+
"for i in range(4):\n",
|
| 839 |
+
" meta_oof_adj[:, i] *= BEST_MULTS[i]\n",
|
| 840 |
+
"meta_oof_adj_f1 = f1_score(train_labels, meta_oof_adj.argmax(1), average='macro')\n",
|
| 841 |
+
"print(f'Meta OOF F1 (with threshold multipliers): {meta_oof_adj_f1:.4f}')\n",
|
| 842 |
+
"\n",
|
| 843 |
+
"test_meta_proba = final_meta.predict_proba(stacked_test)\n",
|
| 844 |
+
"for i in range(4):\n",
|
| 845 |
+
" test_meta_proba[:, i] *= BEST_MULTS[i]\n",
|
| 846 |
+
"\n",
|
| 847 |
+
"final_preds = test_meta_proba.argmax(1)\n",
|
| 848 |
+
"print(f\"\\nPrediction complete. First 10 test predictions: {final_preds[:10]}\")\n"
|
| 849 |
+
]
|
| 850 |
+
},
|
| 851 |
+
{
|
| 852 |
+
"cell_type": "markdown",
|
| 853 |
+
"metadata": {},
|
| 854 |
+
"source": [
|
| 855 |
+
"## 9. Export Deployment Artifact (`joblib.dump`)\n",
|
| 856 |
+
"---"
|
| 857 |
+
]
|
| 858 |
+
},
|
| 859 |
+
{
|
| 860 |
+
"cell_type": "code",
|
| 861 |
+
"execution_count": null,
|
| 862 |
+
"metadata": {},
|
| 863 |
+
"outputs": [],
|
| 864 |
+
"source": [
|
| 865 |
+
"artifact_path = '/kaggle/working/comment_classifier_pipeline.joblib'\n",
|
| 866 |
+
"if not os.path.exists('/kaggle/working'):\n",
|
| 867 |
+
" artifact_path = 'comment_classifier_pipeline.joblib'\n",
|
| 868 |
+
"\n",
|
| 869 |
+
"artifact = {\n",
|
| 870 |
+
" 'tfidf_word': tfidf_word,\n",
|
| 871 |
+
" 'tfidf_char': tfidf_char,\n",
|
| 872 |
+
" 'tfidf_phrase': tfidf_phrase,\n",
|
| 873 |
+
" 'ordinal_enc': ordinal_enc,\n",
|
| 874 |
+
" 'numeric_col_names': numeric_col_names,\n",
|
| 875 |
+
" 'cat_col_names': cat_col_names,\n",
|
| 876 |
+
"\n",
|
| 877 |
+
" # Bagged fold models (N_FOLDS fitted copies each) \u2014 averaged at inference time.\n",
|
| 878 |
+
" 'lgb_models': fold_lgb_models,\n",
|
| 879 |
+
" 'lr_word_models': fold_lr_word_models,\n",
|
| 880 |
+
" 'lr_char_models': fold_lr_char_models,\n",
|
| 881 |
+
" 'nbsvm_models': fold_nbsvm_models,\n",
|
| 882 |
+
" 'lgb_bin_models': fold_lgb_bin_models,\n",
|
| 883 |
+
" 'lgb_c23_models': fold_c23_models,\n",
|
| 884 |
+
" 'svc_models': fold_svc_models,\n",
|
| 885 |
+
"\n",
|
| 886 |
+
" 'meta_model': final_meta,\n",
|
| 887 |
+
" 'thresholds': BEST_MULTS,\n",
|
| 888 |
+
" 'class_names': CLASS_NAMES,\n",
|
| 889 |
+
" 'n_folds': N_FOLDS,\n",
|
| 890 |
+
"}\n",
|
| 891 |
+
"\n",
|
| 892 |
+
"joblib.dump(artifact, artifact_path, compress=3)\n",
|
| 893 |
+
"print(f\"Saved deployment artifact successfully to '{artifact_path}'. File size: {os.path.getsize(artifact_path) / (1024*1024):.2f} MB\")\n"
|
| 894 |
+
]
|
| 895 |
+
},
|
| 896 |
+
{
|
| 897 |
+
"cell_type": "markdown",
|
| 898 |
+
"metadata": {},
|
| 899 |
+
"source": [
|
| 900 |
+
"## 10. Save Submission CSV\n",
|
| 901 |
+
"---"
|
| 902 |
+
]
|
| 903 |
+
},
|
| 904 |
+
{
|
| 905 |
+
"cell_type": "code",
|
| 906 |
+
"execution_count": null,
|
| 907 |
+
"metadata": {},
|
| 908 |
+
"outputs": [],
|
| 909 |
+
"source": [
|
| 910 |
+
"submission = sample_sub.copy()\n",
|
| 911 |
+
"submission['label'] = final_preds\n",
|
| 912 |
+
"submission.to_csv('submission.csv', index=False)\n",
|
| 913 |
+
"\n",
|
| 914 |
+
"print('Submission saved to submission.csv')\n",
|
| 915 |
+
"print('\\nTest prediction distribution:')\n",
|
| 916 |
+
"pred_counts = pd.Series(final_preds).value_counts().sort_index()\n",
|
| 917 |
+
"for cls_id, count in pred_counts.items():\n",
|
| 918 |
+
" pct = count / len(final_preds) * 100\n",
|
| 919 |
+
" print(f' Class {cls_id} ({CLASS_NAMES[cls_id]:14s}): {count:6,} ({pct:.2f}%)')\n"
|
| 920 |
+
]
|
| 921 |
+
},
|
| 922 |
+
{
|
| 923 |
+
"cell_type": "markdown",
|
| 924 |
+
"metadata": {},
|
| 925 |
+
"source": [
|
| 926 |
+
"## 11. Inference Function for Web App Deployment (Gradio / FastAPI / HF Spaces)\n",
|
| 927 |
+
"---\n",
|
| 928 |
+
"Averages predictions across the `N_FOLDS` fitted copies of each base learner (bagging), exactly\n",
|
| 929 |
+
"mirroring how the training loop produced `tst_*` \u2014 then feeds the stacked probabilities to the\n",
|
| 930 |
+
"meta-learner and applies the threshold multipliers."
|
| 931 |
+
]
|
| 932 |
+
},
|
| 933 |
+
{
|
| 934 |
+
"cell_type": "code",
|
| 935 |
+
"execution_count": null,
|
| 936 |
+
"metadata": {},
|
| 937 |
+
"outputs": [],
|
| 938 |
+
"source": [
|
| 939 |
+
"def predict_comment(df_raw, model_artifact):\n",
|
| 940 |
+
" \"\"\"\n",
|
| 941 |
+
" Single or batch inference function for live web applications (Gradio / FastAPI).\n",
|
| 942 |
+
" df_raw must be a pandas DataFrame containing comment text and tabular columns.\n",
|
| 943 |
+
" \"\"\"\n",
|
| 944 |
+
" df_clean = clean_text_column(df_raw)\n",
|
| 945 |
+
" df_eng = build_features(df_clean)\n",
|
| 946 |
+
" clean_text = df_eng['comment_clean'].values\n",
|
| 947 |
+
"\n",
|
| 948 |
+
" w_vec = model_artifact['tfidf_word'].transform(clean_text)\n",
|
| 949 |
+
" c_vec = model_artifact['tfidf_char'].transform(clean_text)\n",
|
| 950 |
+
" p_vec = model_artifact['tfidf_phrase'].transform(clean_text)\n",
|
| 951 |
+
"\n",
|
| 952 |
+
" num_feats = df_eng[model_artifact['numeric_col_names']].values.astype(np.float32)\n",
|
| 953 |
+
" cat_feats = model_artifact['ordinal_enc'].transform(\n",
|
| 954 |
+
" df_eng[model_artifact['cat_col_names']].fillna('missing').astype(str)\n",
|
| 955 |
+
" ).astype(np.int32)\n",
|
| 956 |
+
"\n",
|
| 957 |
+
" X_full = hstack([w_vec, c_vec, p_vec, csr_matrix(num_feats), csr_matrix(cat_feats)]).tocsr()\n",
|
| 958 |
+
"\n",
|
| 959 |
+
" n_folds = model_artifact['n_folds']\n",
|
| 960 |
+
" n_rows = X_full.shape[0]\n",
|
| 961 |
+
"\n",
|
| 962 |
+
" def bag(models, X):\n",
|
| 963 |
+
" out = None\n",
|
| 964 |
+
" for m in models:\n",
|
| 965 |
+
" p = m.predict_proba(X)\n",
|
| 966 |
+
" out = p if out is None else out + p\n",
|
| 967 |
+
" return out / len(models)\n",
|
| 968 |
+
"\n",
|
| 969 |
+
" p_lgb = bag(model_artifact['lgb_models'], X_full)\n",
|
| 970 |
+
" p_lr_w = bag(model_artifact['lr_word_models'], clean_text)\n",
|
| 971 |
+
" p_lr_c = bag(model_artifact['lr_char_models'], clean_text)\n",
|
| 972 |
+
" p_nbsvm = bag(model_artifact['nbsvm_models'], clean_text)\n",
|
| 973 |
+
" p_lgb_bin = bag(model_artifact['lgb_bin_models'], X_full)\n",
|
| 974 |
+
" p_svc = bag(model_artifact['svc_models'], clean_text)\n",
|
| 975 |
+
" p_c23 = bag(model_artifact['lgb_c23_models'], X_full)\n",
|
| 976 |
+
"\n",
|
| 977 |
+
" stacked = np.hstack([p_lgb, p_lr_w, p_lr_c, p_nbsvm, p_lgb_bin, p_svc, p_c23]).astype(np.float32)\n",
|
| 978 |
+
"\n",
|
| 979 |
+
" meta_probs = model_artifact['meta_model'].predict_proba(stacked)\n",
|
| 980 |
+
" mults = model_artifact['thresholds']\n",
|
| 981 |
+
" for idx in range(4):\n",
|
| 982 |
+
" meta_probs[:, idx] *= mults[idx]\n",
|
| 983 |
+
"\n",
|
| 984 |
+
" preds = meta_probs.argmax(axis=1)\n",
|
| 985 |
+
" return preds, meta_probs\n",
|
| 986 |
+
"\n",
|
| 987 |
+
"print(\"Inference function 'predict_comment' initialized.\")\n"
|
| 988 |
+
]
|
| 989 |
+
}
|
| 990 |
+
],
|
| 991 |
+
"metadata": {
|
| 992 |
+
"kernelspec": {
|
| 993 |
+
"display_name": "Python 3",
|
| 994 |
+
"language": "python",
|
| 995 |
+
"name": "python3"
|
| 996 |
+
},
|
| 997 |
+
"language_info": {
|
| 998 |
+
"name": "python",
|
| 999 |
+
"version": "3.11"
|
| 1000 |
+
}
|
| 1001 |
+
},
|
| 1002 |
+
"nbformat": 4,
|
| 1003 |
+
"nbformat_minor": 5
|
| 1004 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==6.20.0
|
| 2 |
+
joblib==1.5.3
|
| 3 |
+
scikit-learn>=1.4.0
|
| 4 |
+
lightgbm>=4.0.0
|
| 5 |
+
pandas>=2.0.0
|
| 6 |
+
numpy>=1.24.0
|
| 7 |
+
scipy>=1.10.0
|
| 8 |
+
packaging>=23.0
|