{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Comment Category Prediction: Fast Deployment Training & Export\n", "---\n", "**Core Methodology:** Stacked ensemble 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", "\n", "**Why this notebook is fast (fits in Kaggle's 9h CPU limit):**\n", "- `N_FOLDS = 3` (the `deployment_training_template.ipynb` used 4, adding a full extra fold pass over 7 models).\n", "- 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", "- 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", "- No EDA / visualization / hyperparameter-search cells \u2014 those never touched the trained artifact anyway.\n", "\n", "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." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Imports and Setup\n", "---" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "import gc\n", "import warnings\n", "import re\n", "import os\n", "import joblib\n", "from datetime import datetime\n", "\n", "from scipy.sparse import hstack, csr_matrix\n", "from sklearn.base import BaseEstimator, TransformerMixin\n", "from sklearn.preprocessing import OrdinalEncoder\n", "from sklearn.model_selection import StratifiedKFold\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "from sklearn.pipeline import Pipeline\n", "from sklearn.metrics import f1_score, classification_report\n", "from sklearn.linear_model import LogisticRegression\n", "from sklearn.svm import LinearSVC\n", "from sklearn.calibration import CalibratedClassifierCV\n", "import lightgbm as lgb\n", "from packaging.version import Version\n", "import sklearn\n", "\n", "def _lr(**kwargs):\n", " if Version(sklearn.__version__) < Version(\"1.6\"):\n", " kwargs['multi_class'] = 'multinomial'\n", " return LogisticRegression(**kwargs)\n", "\n", "warnings.filterwarnings('ignore')\n", "print('All imports successful.')\n", "print(f'sklearn version : {sklearn.__version__}')\n", "print(f'lightgbm version: {lgb.__version__}')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Paths & Configuration\n", "---" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "train_set_path = '/kaggle/input/comment-category-prediction-challenge/train.csv'\n", "test_set_path = '/kaggle/input/comment-category-prediction-challenge/test.csv'\n", "sample_path = '/kaggle/input/comment-category-prediction-challenge/Sample.csv'\n", "\n", "if not os.path.exists(train_set_path):\n", " train_set_path = '/kaggle/input/competitions/comment-category-prediction-challenge/train.csv'\n", " test_set_path = '/kaggle/input/competitions/comment-category-prediction-challenge/test.csv'\n", " sample_path = '/kaggle/input/competitions/comment-category-prediction-challenge/Sample.csv'\n", "\n", "SEED = 42\n", "N_FOLDS = 3 # matches the original 8h run (update-main.ipynb / Notebook-main.ipynb), NOT the 4 used in the 12h template\n", "np.random.seed(SEED)\n", "\n", "CLASS_NAMES = {0: 'Normal', 1: 'Offensive', 2: 'Hate Speech', 3: 'Severe/Violent'}\n", "CLASS_LABELS = ['C-0 Normal', 'C-1 Offensive', 'C-2 Hate Speech', 'C-3 Severe/Violent']\n", "\n", "LR_WORD_C = 5.395\n", "LR_CHAR_C = 4.464\n", "NBSVM_C = 2.0\n", "lgb_class_weights = {0: 1.0, 1: 3.5, 2: 1.5, 3: 15.0}\n", "\n", "print(\"Paths and configuration initialized.\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Data Loading\n", "---" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Loading datasets...\")\n", "train_raw = pd.read_csv(train_set_path)\n", "test_raw = pd.read_csv(test_set_path)\n", "sample_sub = pd.read_csv(sample_path)\n", "\n", "train_raw = train_raw.drop_duplicates(subset=['comment'], keep='first').reset_index(drop=True)\n", "train_labels = train_raw['label'].values.astype(int)\n", "train_features = train_raw.drop(columns=['label'])\n", "\n", "print(f\"Train samples: {len(train_features):,}\")\n", "print(f\"Test samples: {len(test_raw):,}\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Text Preprocessing & Custom Transformers\n", "---" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "LEET_MAP = str.maketrans({\n", " '0': 'o', '1': 'i', '3': 'e', '4': 'a',\n", " '5': 's', '7': 't', '@': 'a', '$': 's', '!': 'i'\n", "})\n", "\n", "ABBREV_MAP = {\n", " 'u' : 'you',\n", " 'r' : 'are',\n", " 'ur' : 'your',\n", " 'gonna': 'going to',\n", " 'wanna': 'want to',\n", " 'kys' : 'kill yourself',\n", " 'kms' : 'kill myself',\n", " 'wtf' : 'what the fuck',\n", " 'stfu' : 'shut the fuck up',\n", " 'idk' : 'i do not know',\n", " 'ngl' : 'not gonna lie',\n", "}\n", "\n", "def expand_abbrevs(sentence):\n", " words = sentence.split()\n", " result = []\n", " for w in words:\n", " if w in ABBREV_MAP:\n", " result.append(ABBREV_MAP[w])\n", " else:\n", " result.append(w)\n", " return ' '.join(result)\n", "\n", "def clean_text_column(df):\n", " df = df.copy()\n", " text = df['comment'].fillna('').astype(str)\n", "\n", " text = text.str.lower()\n", "\n", " text = text.str.replace(r'http\\S+|www\\.\\S+', ' ', regex=True)\n", " text = text.str.replace(r'\\w+\\.(com|org|net|co|us)', ' ', regex=True)\n", " text = text.str.replace(r'<[^>]+>', ' ', regex=True)\n", "\n", " text = text.apply(lambda s: s.translate(LEET_MAP))\n", " text = text.apply(expand_abbrevs)\n", "\n", " text = text.str.replace(r'[^a-z\\s]', ' ', regex=True)\n", " text = text.str.replace(r'\\s+', ' ', regex=True).str.strip()\n", "\n", " text = text.replace('', 'empty_comment').fillna('missing_comment')\n", "\n", " df['comment_clean'] = text\n", " return df\n", "\n", "class NBTransformer(BaseEstimator, TransformerMixin):\n", " def __init__(self, alpha=1.0):\n", " self.alpha = alpha\n", "\n", " def fit(self, X, y=None):\n", " if y is None:\n", " self.r_ = np.ones(X.shape[1], dtype=np.float32)\n", " return self\n", "\n", " labels = np.unique(y)\n", " num_cols = X.shape[1]\n", " ratios = np.zeros((len(labels), num_cols), dtype=np.float64)\n", "\n", " for i, lbl in enumerate(labels):\n", " mask = (y == lbl)\n", " p_counts = np.asarray(X[mask].sum(axis=0)).flatten() + self.alpha\n", " n_counts = np.asarray(X[~mask].sum(axis=0)).flatten() + self.alpha\n", "\n", " p_freq = p_counts / p_counts.sum()\n", " n_freq = n_counts / n_counts.sum()\n", " ratios[i] = np.log(p_freq) - np.log(n_freq)\n", "\n", " self.r_ = np.abs(ratios).max(axis=0).astype(np.float32)\n", " return self\n", "\n", " def transform(self, X):\n", " return X.multiply(self.r_)\n", "\n", "print('TextCleaner and NBTransformer ready.')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Feature Engineering\n", "---" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "POSITIVE_WORDS = frozenset({\n", " 'good','great','excellent','amazing','wonderful','best','love','perfect',\n", " 'nice','fantastic','awesome','beautiful','brilliant','outstanding','happy',\n", " 'glad','pleased','thankful','thanks','appreciate','agree','helpful','useful',\n", " 'interesting','impressive','well','better','fine','cool','fun','enjoy',\n", " 'liked','support','positive','fair','kind','respect','right','correct'\n", "})\n", "\n", "NEGATIVE_WORDS = frozenset({\n", " 'bad','terrible','awful','hate','worst','horrible','disgusting','poor',\n", " 'pathetic','stupid','ugly','wrong','annoying','boring','dumb','useless',\n", " 'trash','garbage','waste','sucks','lame','crap','fail','failed','worse',\n", " 'angry','mad','upset','disappointed','sad','broken','ruined','ridiculous',\n", " 'offensive','toxic','evil','idiot','fool','shut','die','kill'\n", "})\n", "\n", "VIOLENCE_WORDS = frozenset({\n", " 'kill','killed','killing','shoot','shooting','shot','death','dead','die',\n", " 'dying','murder','murdered','murders','attack','attacking','attacked',\n", " 'burn','burning','burned','fire','firing','guns','gun','weapon','weapons',\n", " 'bomb','bombing','destroy','destroying','violence','violent','rape','hang',\n", " 'hanging','decapitate','decapitated','torture','tortured','stab','stabbing',\n", " 'threat','threaten'\n", "})\n", "\n", "def count_unique(text):\n", " return len(set(str(text).split()))\n", "\n", "def count_pos(text):\n", " words = str(text).split()\n", " count = 0\n", " for w in words:\n", " if w in POSITIVE_WORDS:\n", " count += 1\n", " return count\n", "\n", "def count_neg(text):\n", " words = str(text).split()\n", " count = 0\n", " for w in words:\n", " if w in NEGATIVE_WORDS:\n", " count += 1\n", " return count\n", "\n", "def count_caps(text):\n", " words = str(text).split()\n", " count = 0\n", " for w in words:\n", " if w.isupper() and len(w) > 1:\n", " count += 1\n", " return count\n", "\n", "def count_violence(text):\n", " words = str(text).split()\n", " count = 0\n", " for w in words:\n", " if w in VIOLENCE_WORDS:\n", " count += 1\n", " return count\n", "\n", "def build_features(df):\n", " df = df.copy()\n", " raw = df['comment'].astype(str)\n", " cln = df.get('comment_clean', raw.str.lower())\n", "\n", " word_count = cln.str.split().str.len().fillna(0).astype(int)\n", "\n", " if1 = df['if_1'].fillna(0)\n", " if2 = df['if_2'].fillna(0)\n", "\n", " df['char_count'] = cln.str.len().astype(np.float32)\n", " df['word_count'] = word_count.astype(np.float32)\n", " df['unique_words'] = cln.apply(count_unique).astype(np.float32)\n", " df['lexical_div'] = (df['unique_words'] / (word_count + 1)).astype(np.float32)\n", " df['avg_word_len'] = (df['char_count'] / (word_count + 1)).astype(np.float32)\n", "\n", " df['caps_count'] = raw.str.count(r'[A-Z]').astype(np.float32)\n", " df['caps_ratio'] = (df['caps_count'] / (df['char_count'] + 1)).astype(np.float32)\n", " df['exclaim'] = raw.str.count('!').astype(np.float32)\n", " df['question'] = raw.str.count(r'\\?').astype(np.float32)\n", " df['punct_count'] = raw.str.count(r'[^\\w\\s]').astype(np.float32)\n", " df['sent_count'] = raw.str.count(r'[.!?]+').clip(lower=1).astype(np.float32)\n", " df['avg_sent_len'] = (word_count / (df['sent_count'] + 1)).astype(np.float32)\n", " df['all_caps_words'] = raw.apply(count_caps).astype(np.float32)\n", "\n", " df['pos_count'] = cln.apply(count_pos).astype(np.float32)\n", " df['neg_count'] = cln.apply(count_neg).astype(np.float32)\n", " df['sent_balance'] = (df['pos_count'] - df['neg_count']).astype(np.float32)\n", "\n", " df['violence_count'] = cln.apply(count_violence).astype(np.float32)\n", " df['has_violence'] = (df['violence_count'] > 0).astype(np.int8)\n", " df['violence_ratio'] = (df['violence_count'] / (word_count + 1)).astype(np.float32)\n", " df['violence_score'] = (\n", " df['violence_count'] * 2.0 + df['violence_ratio'] * 10.0\n", " ).astype(np.float32)\n", " df['if1_x_violence'] = (if1 * df['violence_count']).astype(np.float32)\n", "\n", " df['upvote'] = df['upvote'].fillna(0)\n", " df['downvote'] = df['downvote'].fillna(0)\n", "\n", " df['total_votes'] = (df['upvote'] + df['downvote']).astype(np.float32)\n", " df['vote_ratio'] = (df['upvote'] / (df['total_votes'] + 1)).astype(np.float32)\n", " df['zero_downvote'] = (df['downvote'] == 0).astype(np.int8)\n", " df['controversy'] = np.minimum(df['upvote'], df['downvote']).astype(np.float32) * 2\n", "\n", " emo_cols = ['emoticon_1', 'emoticon_2', 'emoticon_3']\n", " df[emo_cols] = df[emo_cols].fillna(0)\n", " df['total_emo'] = df[emo_cols].sum(axis=1).astype(np.float32)\n", " df['has_emo'] = (df['total_emo'] > 0).astype(np.int8)\n", "\n", " parsed_dt = pd.to_datetime(df['created_date'], errors='coerce')\n", " hour = parsed_dt.dt.hour.fillna(12).astype(int)\n", " day_of_week = parsed_dt.dt.dayofweek.fillna(3).astype(int)\n", "\n", " df['hour_sin']= np.sin(2 * np.pi * hour / 24).astype(np.float32)\n", " df['hour_cos'] = np.cos(2 * np.pi * hour / 24).astype(np.float32)\n", " df['dow_sin'] = np.sin(2 * np.pi * day_of_week / 7).astype(np.float32)\n", " df['is_weekend'] = (day_of_week >= 5).astype(np.int8)\n", "\n", " race_col = df['race'].fillna('_').str.lower()\n", " religion_col = df['religion'].fillna('_').str.lower()\n", " gender_col = df['gender'].fillna('_').str.lower()\n", "\n", " has_race = (race_col != '_') & (race_col != 'none')\n", " has_religion = (religion_col != '_') & (religion_col != 'none')\n", " has_gender = (gender_col != '_') & (gender_col != 'none')\n", "\n", " df['has_identity'] = (has_race | has_religion | has_gender).astype(np.int8)\n", " df['identity_count'] = (\n", " has_race.astype(int) + has_religion.astype(int) + has_gender.astype(int)\n", " ).astype(np.int8)\n", " df['disability_flag'] = (\n", " df['disability'].map({True: 1, False: 0, 'True': 1, 'False': 0}).fillna(0)\n", " ).astype(np.int8)\n", "\n", " df['if_prod'] = (if1 * if2).astype(np.float32)\n", " df['if_ratio'] = (if1 / (if2 + 1)).astype(np.float32)\n", " df['if_sum'] = (if1 + if2).astype(np.float32)\n", "\n", " df['zone_safe'] = (if2 <= 7).astype(np.int8)\n", " df['zone_c1_trigger'] = ((if2 >= 8) & (if1.isin([4, 6, 10]))).astype(np.int8)\n", " df['zone_c23'] = ((if1 == 0) & (if2 >= 8)).astype(np.int8)\n", " df['if1_low'] = (if1 <= 1).astype(np.int8)\n", " df['if1_nonzero'] = (if1 > 0).astype(np.int8)\n", "\n", " df['golden_c1'] = ((if2 >= 8) & df['has_identity'].astype(bool)).astype(np.int8)\n", " df['golden_c2'] = ((if2 >= 8) & ~df['has_identity'].astype(bool)).astype(np.int8)\n", "\n", " df['is_short'] = (word_count <= 15).astype(np.int8)\n", " df['short_violent'] = (df['is_short'] * df['has_violence']).astype(np.int8)\n", "\n", " df['danger_zone'] = ((df['zone_c23'] == 1) & (df['has_identity'] == 0)).astype(np.int8)\n", " df['violence_in_dz'] = (df['violence_count'] * df['danger_zone']).astype(np.float32)\n", " df['c3_signal'] = (df['is_short'] * df['zero_downvote'] * (df['has_identity'] == 0) * df['zone_c23']).astype(np.int8)\n", "\n", " numeric_dtype_cols = df.select_dtypes(include=[np.number]).columns\n", " df[numeric_dtype_cols] = df[numeric_dtype_cols].fillna(0)\n", "\n", " return df\n", "\n", "print('FeatureEngineer ready.')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Vectorization & Feature Matrix Assembly\n", "---" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('Running clean_text_column and build_features...')\n", "train_engineered = build_features(clean_text_column(train_features))\n", "test_engineered = build_features(clean_text_column(test_raw))\n", "\n", "train_text = train_engineered['comment_clean'].values\n", "test_text = test_engineered['comment_clean'].values\n", "\n", "print('Building TF-IDF matrices...')\n", "tfidf_word = TfidfVectorizer(\n", " max_features=35000,\n", " ngram_range=(1, 2),\n", " min_df=2,\n", " max_df=0.92,\n", " sublinear_tf=True,\n", " strip_accents='unicode',\n", " dtype=np.float32\n", ")\n", "\n", "tfidf_char = TfidfVectorizer(\n", " max_features=10000,\n", " analyzer='char_wb',\n", " ngram_range=(3, 5),\n", " min_df=3,\n", " dtype=np.float32\n", ")\n", "\n", "tfidf_phrase = TfidfVectorizer(\n", " max_features=10000,\n", " ngram_range=(2, 3),\n", " min_df=3,\n", " max_df=0.92,\n", " sublinear_tf=True,\n", " dtype=np.float32\n", ")\n", "\n", "train_tfidf = hstack([\n", " tfidf_word.fit_transform(train_text),\n", " tfidf_char.fit_transform(train_text),\n", " tfidf_phrase.fit_transform(train_text)\n", "])\n", "\n", "test_tfidf = hstack([\n", " tfidf_word.transform(test_text),\n", " tfidf_char.transform(test_text),\n", " tfidf_phrase.transform(test_text)\n", "])\n", "\n", "EXCLUDE_COLS = {\n", " 'comment', 'comment_clean', 'created_date',\n", " 'post_id', 'race', 'religion', 'gender', 'disability'\n", "}\n", "numeric_col_names = [\n", " col for col in train_engineered.columns\n", " if col not in EXCLUDE_COLS\n", " and train_engineered[col].dtype in [\n", " np.float64, np.int64, np.float32, np.int32, np.int8\n", " ]\n", "]\n", "\n", "train_num_scaled = train_engineered[numeric_col_names].values.astype(np.float32)\n", "test_num_scaled = test_engineered[numeric_col_names].values.astype(np.float32)\n", "\n", "cat_col_names = ['race', 'religion', 'gender']\n", "ordinal_enc = OrdinalEncoder(\n", " handle_unknown='use_encoded_value',\n", " unknown_value=-1\n", ")\n", "\n", "train_cats = ordinal_enc.fit_transform(\n", " train_engineered[cat_col_names].fillna('missing').astype(str)).astype(np.int32)\n", "test_cats = ordinal_enc.transform(\n", " test_engineered[cat_col_names].fillna('missing').astype(str)).astype(np.int32)\n", "\n", "X_train_full = hstack([\n", " train_tfidf,\n", " csr_matrix(train_num_scaled),\n", " csr_matrix(train_cats)\n", "]).tocsr()\n", "\n", "X_test_full = hstack([\n", " test_tfidf,\n", " csr_matrix(test_num_scaled),\n", " csr_matrix(test_cats)\n", "]).tocsr()\n", "\n", "del train_tfidf, test_tfidf, train_num_scaled, test_num_scaled\n", "del train_engineered, test_engineered\n", "gc.collect()\n", "\n", "print(f'X_train_full shape: {X_train_full.shape}')\n", "print(f'X_test_full shape: {X_test_full.shape}')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Stratified K-Fold Stacking CV (7 Base Models) \u2014 models kept for deployment\n", "---\n", "This is the only training pass. Each fold's fitted model is appended to a list instead of being\n", "discarded, so after CV finishes we already have a deployable bagged ensemble (3 fitted copies per\n", "base learner) with zero extra training cost. This is exactly what the original notebook did to\n", "build its `tst_*` test predictions \u2014 the only change here is that we keep the fitted objects\n", "instead of throwing them away after computing OOF/test probabilities." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f'{N_FOLDS}-FOLD STRATIFIED CV : 7 BASE MODELS (models retained for deployment)')\n", "print('=' * 60)\n", "\n", "kfold = StratifiedKFold(n_splits=N_FOLDS, shuffle=True, random_state=SEED)\n", "n_train = X_train_full.shape[0]\n", "n_test = X_test_full.shape[0]\n", "\n", "oof_lgb = np.zeros((n_train, 4), dtype=np.float32)\n", "oof_lr_w = np.zeros((n_train, 4), dtype=np.float32)\n", "oof_lr_c = np.zeros((n_train, 4), dtype=np.float32)\n", "oof_nbsvm = np.zeros((n_train, 4), dtype=np.float32)\n", "oof_lgb_bin = np.zeros((n_train, 2), dtype=np.float32)\n", "oof_c23 = np.zeros((n_train, 2), dtype=np.float32)\n", "oof_svc = np.zeros((n_train, 4), dtype=np.float32)\n", "\n", "tst_lgb = np.zeros((n_test, 4), dtype=np.float32)\n", "tst_lr_w = np.zeros((n_test, 4), dtype=np.float32)\n", "tst_lr_c = np.zeros((n_test, 4), dtype=np.float32)\n", "tst_nbsvm = np.zeros((n_test, 4), dtype=np.float32)\n", "tst_lgb_bin = np.zeros((n_test, 2), dtype=np.float32)\n", "tst_c23 = np.zeros((n_test, 2), dtype=np.float32)\n", "tst_svc = np.zeros((n_test, 4), dtype=np.float32)\n", "\n", "# Fold-model registries -- these ARE the deployment artifact, no separate refit needed.\n", "fold_lgb_models = []\n", "fold_lr_word_models = []\n", "fold_lr_char_models = []\n", "fold_nbsvm_models = []\n", "fold_lgb_bin_models = []\n", "fold_c23_models = []\n", "fold_svc_models = []\n", "\n", "LGB_PARAMS = dict(\n", " objective='multiclass',\n", " num_class=4,\n", " n_estimators=1000,\n", " learning_rate=0.03,\n", " num_leaves=127,\n", " max_depth=-1,\n", " max_bin=127,\n", " colsample_bytree=0.5,\n", " subsample=0.9,\n", " subsample_freq=1,\n", " min_child_samples=10,\n", " class_weight=lgb_class_weights,\n", " reg_alpha=0.0,\n", " reg_lambda=0.0,\n", " random_state=SEED,\n", " n_jobs=-1,\n", " verbose=-1\n", ")\n", "\n", "for fold_num, (train_idx, val_idx) in enumerate(kfold.split(X_train_full, train_labels), 1):\n", " print(f'\\n FOLD {fold_num}/{N_FOLDS}')\n", "\n", " y_train = train_labels[train_idx]\n", " y_val = train_labels[val_idx]\n", "\n", " # [1/7] LightGBM Multiclass\n", " print(' [1/7] LightGBM \u2014 full feature matrix')\n", " X_tr_lgb = X_train_full[train_idx]\n", " X_va_lgb = X_train_full[val_idx]\n", " cat_feature_indices = [\n", " X_train_full.shape[1] - 3,\n", " X_train_full.shape[1] - 2,\n", " X_train_full.shape[1] - 1\n", " ]\n", " lgb_model = lgb.LGBMClassifier(**LGB_PARAMS)\n", " lgb_model.fit(\n", " X_tr_lgb, y_train,\n", " eval_set=[(X_va_lgb, y_val)],\n", " callbacks=[\n", " lgb.early_stopping(30, verbose=False),\n", " lgb.log_evaluation(0)\n", " ],\n", " categorical_feature=cat_feature_indices\n", " )\n", " oof_lgb[val_idx] = lgb_model.predict_proba(X_va_lgb)\n", " tst_lgb += lgb_model.predict_proba(X_test_full) / N_FOLDS\n", " fold_lgb_models.append(lgb_model)\n", " del X_tr_lgb, X_va_lgb\n", " gc.collect()\n", "\n", " # [2/7] LR-Word\n", " print(' [2/7] LR-Word \u2014 60k word n-grams')\n", " lr_word = Pipeline([\n", " ('tfidf', TfidfVectorizer(\n", " max_features=60000,\n", " ngram_range=(1, 3),\n", " sublinear_tf=True,\n", " min_df=2,\n", " max_df=0.95,\n", " strip_accents='unicode',\n", " token_pattern=r'(?u)\\b\\w+\\b',\n", " dtype=np.float32\n", " )),\n", " ('lr', _lr(\n", " C=LR_WORD_C,\n", " class_weight='balanced',\n", " solver='liblinear',\n", " max_iter=1000,\n", " dual=False,\n", " tol=1e-3,\n", " random_state=SEED\n", " ))\n", " ])\n", " lr_word.fit(train_text[train_idx], y_train)\n", " oof_lr_w[val_idx] = lr_word.predict_proba(train_text[val_idx])\n", " tst_lr_w += lr_word.predict_proba(test_text) / N_FOLDS\n", " fold_lr_word_models.append(lr_word)\n", " gc.collect()\n", "\n", " # [3/7] LR-Char\n", " print(' [3/7] LR-Char \u2014 30k character n-grams')\n", " lr_char = Pipeline([\n", " ('tfidf', TfidfVectorizer(\n", " max_features=30000,\n", " analyzer='char',\n", " ngram_range=(3, 6),\n", " sublinear_tf=True,\n", " min_df=5,\n", " dtype=np.float32\n", " )),\n", " ('lr', _lr(\n", " C=LR_CHAR_C,\n", " class_weight='balanced',\n", " solver='lbfgs',\n", " max_iter=1000,\n", " random_state=SEED\n", " ))\n", " ])\n", " lr_char.fit(train_text[train_idx], y_train)\n", " oof_lr_c[val_idx] = lr_char.predict_proba(train_text[val_idx])\n", " tst_lr_c += lr_char.predict_proba(test_text) / N_FOLDS\n", " fold_lr_char_models.append(lr_char)\n", " gc.collect()\n", "\n", " # [4/7] NB-SVM\n", " print(' [4/7] NB-SVM \u2014 NB feature weighting + LR')\n", " nbsvm = Pipeline([\n", " ('tfidf', TfidfVectorizer(\n", " max_features=50000,\n", " ngram_range=(1, 2),\n", " sublinear_tf=True,\n", " min_df=2,\n", " max_df=0.95,\n", " strip_accents='unicode',\n", " dtype=np.float32\n", " )),\n", " ('nb', NBTransformer(alpha=1.0)),\n", " ('lr', _lr(\n", " C=NBSVM_C,\n", " class_weight='balanced',\n", " solver='lbfgs',\n", " max_iter=1000,\n", " random_state=SEED\n", " ))\n", " ])\n", " nbsvm.fit(train_text[train_idx], y_train)\n", " oof_nbsvm[val_idx] = nbsvm.predict_proba(train_text[val_idx])\n", " tst_nbsvm += nbsvm.predict_proba(test_text) / N_FOLDS\n", " fold_nbsvm_models.append(nbsvm)\n", " gc.collect()\n", "\n", " # [5/7] LGB-Binary\n", " print(' [5/7] LGB-Binary \u2014 Class 3 vs rest')\n", " y_train_lgb_bin = (y_train == 3).astype(int)\n", " y_val_lgb_bin = (y_val == 3).astype(int)\n", " lgb_bin_model = lgb.LGBMClassifier(\n", " objective='binary',\n", " n_estimators=500,\n", " learning_rate=0.03,\n", " num_leaves=63,\n", " max_bin=127,\n", " colsample_bytree=0.4,\n", " subsample=0.8,\n", " subsample_freq=1,\n", " min_child_samples=20,\n", " class_weight={0: 1, 1: 20},\n", " random_state=SEED,\n", " n_jobs=-1,\n", " verbose=-1\n", " )\n", " lgb_bin_model.fit(\n", " X_train_full[train_idx], y_train_lgb_bin,\n", " eval_set=[(X_train_full[val_idx], y_val_lgb_bin)],\n", " callbacks=[lgb.early_stopping(30, verbose=False)]\n", " )\n", " oof_lgb_bin[val_idx] = lgb_bin_model.predict_proba(X_train_full[val_idx])\n", " tst_lgb_bin += lgb_bin_model.predict_proba(X_test_full) / N_FOLDS\n", " fold_lgb_bin_models.append(lgb_bin_model)\n", " gc.collect()\n", "\n", " # [6/7] LGB C3 vs C2 Specialist\n", " print(' [6/7] LGB C3vC2 \u2014 Class 3 vs Class 2 specialist')\n", " c23_train_mask = (y_train == 2) | (y_train == 3)\n", " c23_val_mask = (y_val == 2) | (y_val == 3)\n", " y_train_c23 = (y_train[c23_train_mask] == 3).astype(int)\n", " y_val_c23 = (y_val[c23_val_mask] == 3).astype(int)\n", " lgb_c23_model = lgb.LGBMClassifier(\n", " objective='binary',\n", " n_estimators=500,\n", " learning_rate=0.03,\n", " num_leaves=63,\n", " max_bin=127,\n", " colsample_bytree=0.4,\n", " subsample=0.8,\n", " subsample_freq=1,\n", " min_child_samples=20,\n", " class_weight={0: 1, 1: 12},\n", " random_state=SEED,\n", " n_jobs=-1,\n", " verbose=-1\n", " )\n", " lgb_c23_model.fit(\n", " X_train_full[train_idx][c23_train_mask], y_train_c23,\n", " eval_set=[(X_train_full[val_idx][c23_val_mask], y_val_c23)],\n", " callbacks=[lgb.early_stopping(30, verbose=False)]\n", " )\n", " oof_c23[val_idx] = lgb_c23_model.predict_proba(X_train_full[val_idx])\n", " tst_c23 += lgb_c23_model.predict_proba(X_test_full) / N_FOLDS\n", " fold_c23_models.append(lgb_c23_model)\n", " gc.collect()\n", "\n", " # [7/7] LinearSVC (Calibrated)\n", " print(' [7/7] LinearSVC \u2014 calibrated probability output')\n", " svc_base = LinearSVC(C=0.184, class_weight='balanced', max_iter=1000, random_state=SEED)\n", " p_svc = Pipeline([\n", " ('tfidf', TfidfVectorizer(\n", " max_features=50000,\n", " ngram_range=(1, 2),\n", " sublinear_tf=True,\n", " min_df=2,\n", " max_df=0.95,\n", " strip_accents='unicode',\n", " dtype=np.float32\n", " )),\n", " ('svc', CalibratedClassifierCV(svc_base, method='sigmoid', cv=2))\n", " ])\n", " p_svc.fit(train_text[train_idx], y_train)\n", " oof_svc[val_idx] = p_svc.predict_proba(train_text[val_idx])\n", " tst_svc += p_svc.predict_proba(test_text) / N_FOLDS\n", " fold_svc_models.append(p_svc)\n", " gc.collect()\n", "\n", "print(\"\\nOOF predictions completed for all 7 base models.\")\n", "print(f\"Retained {N_FOLDS} fitted copies per base learner for the deployment artifact.\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8. Meta-Learner & Threshold Multipliers\n", "---\n", "No separate full-data base-model refit stage. The meta-learner is small (24 stacked probability\n", "columns \u2192 4 classes) so retraining it on 100% of the OOF matrix is cheap and matches the original\n", "notebook's approach." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('META-LEARNER + THRESHOLD APPLICATION')\n", "print('=' * 60)\n", "\n", "stacked_train = np.hstack([oof_lgb, oof_lr_w, oof_lr_c, oof_nbsvm,\n", " oof_lgb_bin, oof_svc, oof_c23]).astype(np.float32)\n", "stacked_test = np.hstack([tst_lgb, tst_lr_w, tst_lr_c, tst_nbsvm,\n", " tst_lgb_bin, tst_svc, tst_c23]).astype(np.float32)\n", "\n", "print(f'Stacked train shape: {stacked_train.shape}')\n", "print(f'Stacked test shape: {stacked_test.shape}')\n", "\n", "lgb_meta_params = dict(\n", " objective='multiclass',\n", " num_class=4,\n", " num_leaves=16,\n", " n_estimators=100,\n", " learning_rate=0.05,\n", " min_child_samples=200,\n", " random_state=SEED,\n", " n_jobs=-1,\n", " verbose=-1\n", ")\n", "\n", "# OOF sanity check of the meta-learner before committing to the final fit\n", "meta_kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED + 99)\n", "meta_oof_preds = np.zeros((n_train, 4), dtype=np.float32)\n", "for tr_m, va_m in meta_kfold.split(stacked_train, train_labels):\n", " lgb_meta = lgb.LGBMClassifier(**lgb_meta_params)\n", " lgb_meta.fit(stacked_train[tr_m], train_labels[tr_m])\n", " meta_oof_preds[va_m] = lgb_meta.predict_proba(stacked_train[va_m])\n", "\n", "meta_oof_f1 = f1_score(train_labels, meta_oof_preds.argmax(1), average='macro')\n", "print(f'\\nMeta OOF F1 (base, before threshold tuning): {meta_oof_f1:.4f}')\n", "print(classification_report(train_labels, meta_oof_preds.argmax(1), digits=4))\n", "\n", "final_meta = lgb.LGBMClassifier(**lgb_meta_params)\n", "final_meta.fit(stacked_train, train_labels)\n", "\n", "BEST_MULTS = [1.032, 0.951, 0.85, 1.25]\n", "\n", "meta_oof_adj = meta_oof_preds.copy()\n", "for i in range(4):\n", " meta_oof_adj[:, i] *= BEST_MULTS[i]\n", "meta_oof_adj_f1 = f1_score(train_labels, meta_oof_adj.argmax(1), average='macro')\n", "print(f'Meta OOF F1 (with threshold multipliers): {meta_oof_adj_f1:.4f}')\n", "\n", "test_meta_proba = final_meta.predict_proba(stacked_test)\n", "for i in range(4):\n", " test_meta_proba[:, i] *= BEST_MULTS[i]\n", "\n", "final_preds = test_meta_proba.argmax(1)\n", "print(f\"\\nPrediction complete. First 10 test predictions: {final_preds[:10]}\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9. Export Deployment Artifact (`joblib.dump`)\n", "---" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "artifact_path = '/kaggle/working/comment_classifier_pipeline.joblib'\n", "if not os.path.exists('/kaggle/working'):\n", " artifact_path = 'comment_classifier_pipeline.joblib'\n", "\n", "artifact = {\n", " 'tfidf_word': tfidf_word,\n", " 'tfidf_char': tfidf_char,\n", " 'tfidf_phrase': tfidf_phrase,\n", " 'ordinal_enc': ordinal_enc,\n", " 'numeric_col_names': numeric_col_names,\n", " 'cat_col_names': cat_col_names,\n", "\n", " # Bagged fold models (N_FOLDS fitted copies each) \u2014 averaged at inference time.\n", " 'lgb_models': fold_lgb_models,\n", " 'lr_word_models': fold_lr_word_models,\n", " 'lr_char_models': fold_lr_char_models,\n", " 'nbsvm_models': fold_nbsvm_models,\n", " 'lgb_bin_models': fold_lgb_bin_models,\n", " 'lgb_c23_models': fold_c23_models,\n", " 'svc_models': fold_svc_models,\n", "\n", " 'meta_model': final_meta,\n", " 'thresholds': BEST_MULTS,\n", " 'class_names': CLASS_NAMES,\n", " 'n_folds': N_FOLDS,\n", "}\n", "\n", "joblib.dump(artifact, artifact_path, compress=3)\n", "print(f\"Saved deployment artifact successfully to '{artifact_path}'. File size: {os.path.getsize(artifact_path) / (1024*1024):.2f} MB\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 10. Save Submission CSV\n", "---" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "submission = sample_sub.copy()\n", "submission['label'] = final_preds\n", "submission.to_csv('submission.csv', index=False)\n", "\n", "print('Submission saved to submission.csv')\n", "print('\\nTest prediction distribution:')\n", "pred_counts = pd.Series(final_preds).value_counts().sort_index()\n", "for cls_id, count in pred_counts.items():\n", " pct = count / len(final_preds) * 100\n", " print(f' Class {cls_id} ({CLASS_NAMES[cls_id]:14s}): {count:6,} ({pct:.2f}%)')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 11. Inference Function for Web App Deployment (Gradio / FastAPI / HF Spaces)\n", "---\n", "Averages predictions across the `N_FOLDS` fitted copies of each base learner (bagging), exactly\n", "mirroring how the training loop produced `tst_*` \u2014 then feeds the stacked probabilities to the\n", "meta-learner and applies the threshold multipliers." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def predict_comment(df_raw, model_artifact):\n", " \"\"\"\n", " Single or batch inference function for live web applications (Gradio / FastAPI).\n", " df_raw must be a pandas DataFrame containing comment text and tabular columns.\n", " \"\"\"\n", " df_clean = clean_text_column(df_raw)\n", " df_eng = build_features(df_clean)\n", " clean_text = df_eng['comment_clean'].values\n", "\n", " w_vec = model_artifact['tfidf_word'].transform(clean_text)\n", " c_vec = model_artifact['tfidf_char'].transform(clean_text)\n", " p_vec = model_artifact['tfidf_phrase'].transform(clean_text)\n", "\n", " num_feats = df_eng[model_artifact['numeric_col_names']].values.astype(np.float32)\n", " cat_feats = model_artifact['ordinal_enc'].transform(\n", " df_eng[model_artifact['cat_col_names']].fillna('missing').astype(str)\n", " ).astype(np.int32)\n", "\n", " X_full = hstack([w_vec, c_vec, p_vec, csr_matrix(num_feats), csr_matrix(cat_feats)]).tocsr()\n", "\n", " n_folds = model_artifact['n_folds']\n", " n_rows = X_full.shape[0]\n", "\n", " def bag(models, X):\n", " out = None\n", " for m in models:\n", " p = m.predict_proba(X)\n", " out = p if out is None else out + p\n", " return out / len(models)\n", "\n", " p_lgb = bag(model_artifact['lgb_models'], X_full)\n", " p_lr_w = bag(model_artifact['lr_word_models'], clean_text)\n", " p_lr_c = bag(model_artifact['lr_char_models'], clean_text)\n", " p_nbsvm = bag(model_artifact['nbsvm_models'], clean_text)\n", " p_lgb_bin = bag(model_artifact['lgb_bin_models'], X_full)\n", " p_svc = bag(model_artifact['svc_models'], clean_text)\n", " p_c23 = bag(model_artifact['lgb_c23_models'], X_full)\n", "\n", " stacked = np.hstack([p_lgb, p_lr_w, p_lr_c, p_nbsvm, p_lgb_bin, p_svc, p_c23]).astype(np.float32)\n", "\n", " meta_probs = model_artifact['meta_model'].predict_proba(stacked)\n", " mults = model_artifact['thresholds']\n", " for idx in range(4):\n", " meta_probs[:, idx] *= mults[idx]\n", "\n", " preds = meta_probs.argmax(axis=1)\n", " return preds, meta_probs\n", "\n", "print(\"Inference function 'predict_comment' initialized.\")\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.11" } }, "nbformat": 4, "nbformat_minor": 5 }