Update README.md
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908# R-ViHSD — ViSoBERT + TF-IDF/LinearSVM StackingA Vietnamese hate-speech and text-noise classification pipeline combining:- **ViSoBERT** for semantic representation.- **TF-IDF character + word n-grams** for robust lexical features.- **LinearSVC** models for hate-speech and noise classification.- **Logistic Regression stacking** for the final hate-speech prediction.The pipeline is trained using **Out-of-Fold (OOF) stacking** to reduce data leakage. After OOF training, the final base models are retrained on the full labeled dataset for inference on new data.---## 1. Task DefinitionFor each Vietnamese text sample, the system predicts two outputs.### Hate-Speech Label```textCLEANOFFENSIVEHATE```### Noise Type```textORIGINALNO_DIACRITICSTEENCODECHAR_REPEATPUNCT_NOISEOBFUSCATIONMIXED```The minimum inference input format is:```csvid,text0001,"sample text"0002,"another sample"```The `id` column is preserved in the output but is not used as a model feature.---## 2. Overall Architecture```text┌─────────────────────────┐│ TEXT │└────────────┬────────────┘│┌──────────────────────┼──────────────────────┐│ │ │▼ ▼ ▼┌────────────────┐ ┌──────────────────┐ ┌─────────────────┐│ ViSoBERT │ │ TF-IDF char+word│ │ Surface Features│└───────┬────────┘ └────────┬─────────┘ └────────┬────────┘│ │ │3 class probabilities ┌─────┴─────┐ ││ │ │▼ ▼ │Hate LinearSVC Noise LinearSVC ││ │ │3 decision 7 decision │scores scores ││ │ ││ softmax ││ │ │└─────┬─────┘ ││ │┌──────────────────────┴──────────────────────┘│▼┌──────────────────────┐│ 18 Stacking Features │└──────────┬───────────┘│▼┌──────────────────────┐│ Logistic Regression ││ Meta-Model │└──────────┬───────────┘│▼CLEAN / OFFENSIVE / HATE```The final `noise_type` prediction does not pass through the meta-model. It is obtained directly from:```textTF-IDF → Noise LinearSVC → argmax```---## 3. Saved Model StructureAfter training, the main working directory is expected to contain:```textrvihsd_stacking_work/│├── visobert_full/│ ├── config.json│ ├── model.safetensors / pytorch_model.bin│ ├── tokenizer_config.json│ ├── tokenizer.json│ └── ...│├── full_vectorizer.joblib├── full_hate_svm.joblib├── full_noise_svm.joblib├── meta_model.joblib│├── visobert_oof.npy├── svm_oof.npy├── noise_oof_scores.npy├── visobert_fold*_pred.npy│└── submissions/```### Required Files for InferenceOnly the following files are required for inference:```textvisobert_full/full_vectorizer.joblibfull_hate_svm.joblibfull_noise_svm.joblibmeta_model.joblib```OOF files are used during training and evaluation but are not required for deployment.---## 4. ViSoBERT ModelBackbone:```textuitnlp/visobert```ViSoBERT is fine-tuned for three-class hate-speech classification:```text0 → CLEAN1 → OFFENSIVE2 → HATE```Main training configuration:| Parameter | Value ||---|---:|| Backbone | `uitnlp/visobert` || Max sequence length | `128` || Epochs | `3` || Learning rate | `2e-5` || Weight decay | `0.01` || Warmup ratio | `0.08` || Label smoothing | `0.05` || Train batch size | `128` || Evaluation batch size | `64` || Gradient accumulation | `2` || Seed | `42` |During training, ViSoBERT uses weighted cross-entropy with sqrt-balanced class weights to reduce the effect of class imbalance.The model produces three probabilities:```textP(CLEAN)P(OFFENSIVE)P(HATE)```These three values are passed to the stacking meta-model.---## 5. TF-IDF FeaturesThe pipeline combines two TF-IDF vectorizers.### Character TF-IDF```pythonanalyzer="char"ngram_range=(3, 5)max_features=150_000min_df=2sublinear_tf=True```### Word TF-IDF```pythonanalyzer="word"ngram_range=(1, 2)max_features=80_000min_df=2sublinear_tf=True```The two sparse matrices are concatenated:```textCharacter TF-IDF + Word TF-IDF│▼Sparse Feature Matrix```Character n-grams are particularly useful for noisy social-media text, including:- teencode,- misspellings,- missing Vietnamese diacritics,- repeated characters,- obfuscation,- punctuation noise.---## 6. LinearSVC ModelsTwo independent LinearSVC models are used.### Hate-Speech SVMClasses:```textCLEANOFFENSIVEHATE```Configuration:```pythonLinearSVC(C=2.0,class_weight="balanced",random_state=42)```The stacking model uses the three `decision_function` scores, not calibrated probabilities.### Noise SVMClasses:```textORIGINALNO_DIACRITICSTEENCODECHAR_REPEATPUNCT_NOISEOBFUSCATIONMIXED```Configuration:```pythonLinearSVC(C=2.0,class_weight="balanced",random_state=42)```For stacking, the seven decision scores are transformed using:```pythonsoftmax(noise_score, axis=1)```These values are only used as stacking features and should not be interpreted as calibrated probabilities.---## 7. Surface FeaturesThe pipeline also extracts five handcrafted features:```text1. log(1 + text length)2. punctuation ratio3. Vietnamese-diacritic ratio4. repeated-character score5. obfuscation score```The final meta-model input consists of:```textViSoBERT probabilities 3Hate SVM decision scores 3Noise SVM softmax scores 7Surface features 5-------------------------------Total 18```The feature order must remain exactly the same during inference.---## 8. Meta-ModelThe final hate-speech meta-model is:```textStandardScaler↓LogisticRegression```Configuration:```pythonPipeline([("scale", StandardScaler()),("lr", LogisticRegression(C=1.0,max_iter=3000,class_weight="balanced",random_state=42))])```Input:```text18 features```Output:```textCLEAN / OFFENSIVE / HATE```The model is saved as:```textmeta_model.joblib```---## 9. Out-of-Fold StackingThe meta-model should not be trained on predictions produced by base models that have already seen the same samples.The training pipeline therefore uses:```pythonStratifiedGroupKFold(n_splits=5,shuffle=True,random_state=42)```Workflow:```textFold 1 → train base models on other folds → predict Fold 1Fold 2 → train base models on other folds → predict Fold 2...Fold 5 → train base models on other folds → predict Fold 5```These predictions form the Out-of-Fold feature matrix.The meta-model is then trained on:```textViSoBERT OOF predictions+Hate SVM OOF scores+Noise SVM OOF scores+Surface features↓Logistic Regression Meta-Model```Grouping based on normalized text can also be used to reduce duplicate or augmentation leakage across folds.---## 10. Final TrainingAfter OOF features are generated and the meta-model is trained:1. The TF-IDF vectorizer is fitted again on all labeled data.2. The hate-speech LinearSVC is trained on all labeled data.3. The noise LinearSVC is trained on all labeled data.4. ViSoBERT is fine-tuned on all labeled data.5. All final models are saved for inference.If:```pythonUSE_VALIDATION_FOR_FINAL_TRAIN = True```the final models use:```texttraining_set + validation_set```---## 11. Environment RequirementsRecommended installation:```bashpip install -U \"transformers>=4.46" \"accelerate>=1.0" \"scikit-learn>=1.4" \sentencepiece \joblib \scipy \pandas \numpy \torch```Main dependencies:```textPythonPyTorchTransformersscikit-learnSciPyNumPyPandasJoblibSentencePiece```CUDA GPU support is recommended for ViSoBERT inference but is not required.---## 12. Loading the ModelsExample:```pythonfrom pathlib import Pathimport joblibfrom transformers import (AutoTokenizer,AutoModelForSequenceClassification,)WORK_DIR = Path("/content/drive/MyDrive/rvihsd_stacking_work")tokenizer = AutoTokenizer.from_pretrained(WORK_DIR / "visobert_full")visobert = AutoModelForSequenceClassification.from_pretrained(WORK_DIR / "visobert_full")vectorizer = joblib.load(WORK_DIR / "full_vectorizer.joblib")hate_svm = joblib.load(WORK_DIR / "full_hate_svm.joblib")noise_svm = joblib.load(WORK_DIR / "full_noise_svm.joblib")meta_model = joblib.load(WORK_DIR / "meta_model.joblib")```> `full_vectorizer.joblib` contains a custom `DualTfidf` class. The inference environment must define a compatible `DualTfidf` class before loading the file with `joblib`.---## 13. Inference FlowFor each new text sample:```texttext│├── ViSoBERT│ └── 3 class probabilities│├── TF-IDF│ ├── Hate LinearSVC│ │ └── 3 decision scores│ ││ └── Noise LinearSVC│ ├── 7 decision scores│ └── softmax → 7 stacking features│└── Surface features└── 5 features```The final stacking input is:```pythonmeta_X = np.hstack([visobert_prob, # 3hate_svm_score, # 3noise_soft, # 7surface_features, # 5])```The feature dimension must satisfy:```pythonassert meta_X.shape[1] == 18```Final hate-speech prediction:```pythonhate_pred = meta_model.predict(meta_X)```Final noise prediction:```pythonnoise_pred = noise_score.argmax(axis=1)```---## 14. Input FormatA new CSV file should contain at least:```csvid,text1,"first sentence"2,"second sentence"3,"third sentence"```Additional columns may exist, but inference should only depend on:```textidtext```This prevents accidental use of labels or unrelated metadata.---## 15. Output FormatRecommended output:```csvid,pred_label,pred_noise_type1,CLEAN,ORIGINAL2,OFFENSIVE,TEENCODE3,HATE,NO_DIACRITICS```Columns:| Column | Description ||---|---|| `id` | Original sample ID || `pred_label` | `CLEAN`, `OFFENSIVE`, or `HATE` || `pred_noise_type` | One of the seven supported noise classes |---## 16. Label Mapping### Hate-Speech Labels```pythonLABELS = ["CLEAN","OFFENSIVE","HATE",]```Mapping:```text0 → CLEAN1 → OFFENSIVE2 → HATE```### Noise Labels```pythonNOISE_LABELS = ["ORIGINAL","NO_DIACRITICS","TEENCODE","CHAR_REPEAT","PUNCT_NOISE","OBFUSCATION","MIXED",]```Mapping:```text0 → ORIGINAL1 → NO_DIACRITICS2 → TEENCODE3 → CHAR_REPEAT4 → PUNCT_NOISE5 → OBFUSCATION6 → MIXED```Do not change the class order when using the already-trained models.---## 17. Recommended Inference ChecksUseful safety checks:```pythonassert len(output) == len(test_df)assert output["id"].is_uniqueassert set(output["pred_label"]).issubset(LABELS)assert set(output["pred_noise_type"]).issubset(NOISE_LABELS)assert meta_X.shape[1] == 18```If the stacking matrix does not contain exactly 18 features, the inference feature construction no longer matches training.---## 18. Components That Must Stay ConsistentWhen using the existing trained models, keep the following unchanged:- hate-speech label order,- noise label order,- `MAX_LENGTH = 128`,- tokenizer saved in `visobert_full`,- `meta_surface_features` implementation,- `DualTfidf` implementation,- 18-feature stacking order,- noise-score softmax transformation before the meta-model.The stacking order must remain:```text[ViSoBERT: 3]+[Hate SVM: 3]+[Noise SVM: 7]+[Surface Features: 5]```---## 19. Do New Test Sets Require Retraining?**No.**If the following trained artifacts are available:```textvisobert_full/full_vectorizer.joblibfull_hate_svm.joblibfull_noise_svm.joblibmeta_model.joblib```a new dataset only requires:```textLOAD MODELS↓LOAD NEW CSV↓TF-IDF + SVM INFERENCE↓ViSoBERT INFERENCE↓SURFACE FEATURE EXTRACTION↓STACKING↓SAVE PREDICTIONS```There is no need to rerun:```text5-fold OOF trainingTF-IDF fittingSVM trainingViSoBERT fine-tuningMeta-model training```---## 20. Training CacheThe notebook may use:```pythonREUSE_CACHE = True```Typical cache files include:```textsvm_oof.npynoise_oof_scores.npyvisobert_oof.npyvisobert_fold*_pred.npy```These files are useful for resuming training or reusing OOF predictions.They are not required for deployment.---## 21. Main Training Hyperparameters```pythonN_FOLDS = 5SEED = 42MODEL_NAME = "uitnlp/visobert"MAX_LENGTH = 128EPOCHS = 3TRAIN_BATCH_SIZE = 128EVAL_BATCH_SIZE = 64GRAD_ACCUM_STEPS = 2LEARNING_RATE = 2e-5WEIGHT_DECAY = 0.01WARMUP_RATIO = 0.08LABEL_SMOOTHING = 0.05CHAR_NGRAM = (3, 5)WORD_NGRAM = (1, 2)CHAR_MAX_FEATURES = 150_000WORD_MAX_FEATURES = 80_000MIN_DF = 2SVM_C_HATE = 2.0SVM_C_NOISE = 2.0META_C = 1.0```---## 22. Evaluation MetricBoth tasks are evaluated using Macro-F1.Hate-speech classification:```pythonf1_score(y_hate,hate_pred,average="macro")```Noise classification:```pythonf1_score(y_noise,noise_pred,average="macro")```The notebook may also compute a combined score:```text0.85 × Hate Macro-F1+0.15 × Noise Macro-F1```This README intentionally does not report a fixed F1 score because the actual metric depends on the specific training run and cached predictions.---## 23. Minimal Deployment PackageFor deployment on another machine, the project can be organized as:```textmodel/├── visobert_full/├── full_vectorizer.joblib├── full_hate_svm.joblib├── full_noise_svm.joblib├── meta_model.joblib├── inference.py└── README.md```A command-line inference interface may look like:```bashpython inference.py \--input new_test.csv \--output predictions.csv \--model-dir model```---## 24. Notes- The meta-model predicts only the hate-speech label.- The noise label is produced directly by the noise LinearSVC.- `LinearSVC.decision_function()` values are not probabilities.- The softmax applied to noise scores is used as a stacking transformation rather than probability calibration.- Model compatibility depends on preserving the preprocessing and feature-ordering logic used during training.- When transferring `joblib` artifacts between environments, compatible versions of Python and scikit-learn are recommended.---## 25. SummaryThe final inference system is:```textViSoBERT+TF-IDF Character/Word Features+Hate LinearSVC+Noise LinearSVC+Surface Features↓Logistic Regression Stacking↓Final Hate-Speech PredictionNoise LinearSVC↓Final Noise-Type Prediction```This architecture combines transformer-based semantic information with sparse lexical features that are robust to noisy Vietnamese social-media text.
README.md+908