Comment Category Prediction
An end-to-end machine learning pipeline for classifying 300,000 user comments using custom feature engineering, word and character-level TF-IDF, gradient boosting, and stacked ensemble learning, achieving a validation Macro F1 of 0.8282.
- Scikit-learn
- Pandas
- Seaborn
- XGBoost
- LightGBM
Overview
Comment Category Prediction is an end-to-end machine learning system developed to classify user-generated comments into four predefined categories using a combination of natural language processing, structured metadata, engagement statistics, and ensemble learning.
Developed for the Comment Category Prediction Challenge on Kaggle, the project processes a dataset of 300,000 records and investigates how textual characteristics, user interactions, temporal patterns, and contextual metadata contribute to classification performance.
The system incorporates exploratory data analysis, custom feature engineering transformers, high-dimensional sparse text representations, class imbalance handling, hyperparameter optimization, and stacked ensemble classification.
The project emphasizes systematic experimentation, reusable preprocessing pipelines, and evidence-driven model selection.
Problem Statement
Automatically categorizing user-generated comments presents several machine learning challenges due to variations in language, writing styles, contextual information, and engagement patterns.
Textual information alone may not capture all the signals associated with a comment's assigned category. Additional information, such as voting behavior, reactions, posting patterns, and platform-specific metadata, may provide complementary predictive features.
Furthermore, the dataset exhibits substantial class imbalance, missing categorical information, highly skewed numerical features, and a high-dimensional feature space.
The objective was to develop a multiclass classification system that effectively combines these heterogeneous data sources while maintaining meaningful predictive performance across both majority and minority classes.
The primary objectives were to:
- Classify comments into four predefined categories.
- Extract meaningful features from textual and structured data.
- Handle missing values, skewed distributions, and class imbalance.
- Develop reusable and consistent preprocessing pipelines.
- Compare multiple machine learning architectures.
- Investigate the impact of feature representation and dimensionality reduction.
- Optimize predictive performance using stacked ensemble learning.
My Contribution
I designed and implemented the complete machine learning workflow, covering data analysis, feature engineering, preprocessing, model development, hyperparameter tuning, evaluation, and competition submission generation.
My key contributions include:
- Conducted comprehensive exploratory data analysis on 198,000 labeled training samples and 102,000 test samples.
- Implemented five custom Scikit-learn transformers generating 19 additional features from timestamps, voting behavior, text characteristics, post-level activity, and emoticon interactions.
- Developed a unified preprocessing pipeline using Pipeline and ColumnTransformer to handle heterogeneous data types.
- Implemented complementary word-level and character-level TF-IDF representations.
- Investigated the impact of Truncated Singular Value Decomposition on predictive performance.
- Applied class weighting and sample weighting to address imbalanced class distributions.
- Evaluated eight individual classifier architectures and multiple tuned configurations.
- Conducted hyperparameter search experiments using RandomizedSearchCV.
- Developed a stacking ensemble combining XGBoost, LightGBM, and LinearSVC with Logistic Regression as the meta-classifier.
- Performed class-level error analysis using confusion matrices and classification reports.
- Retrained the selected pipeline on the complete labeled dataset and generated predictions for 102,000 test samples.
System Architecture
The project follows a modular machine learning architecture that separates data ingestion, preprocessing, feature engineering, model experimentation, evaluation, and inference.
| Component | Responsibility |
|---|---|
| Data Pipeline | Dataset loading, statistical analysis, missing-value inspection, and duplicate detection |
| Feature Engineering | Extraction of temporal, textual, engagement, and post-level features |
| Preprocessing | Imputation, logarithmic transformation, scaling, categorical encoding, and text vectorization |
| Model Layer | Linear classifiers, decision trees, gradient boosting, neural networks, and ensemble learning |
| Optimization | Class imbalance handling and hyperparameter search |
| Evaluation | Macro F1, weighted F1, accuracy, precision, recall, and error analysis |
| Inference | Full-dataset training, test prediction, and automated submission generation |
Dataset Composition
The dataset contains 198,000 labeled training records and 102,000 unlabeled test records.
| Attribute | Value |
|---|---|
| Total records | 300,000 |
| Labeled samples | 198,000 |
| Test samples | 102,000 |
| Original input features | 14 |
| Target classes | 4 |
| Training partition | 158,400 |
| Validation partition | 39,600 |
The input data combines comment text with timestamps, post identifiers, voting statistics, emoticon counts, demographic attributes, and additional platform-specific numerical indicators.
An 80:20 stratified train-validation split was used to approximately preserve class distributions across both partitions.
Exploratory Data Analysis
The exploratory analysis investigated statistical properties, missing values, feature distributions, relationships between numerical variables, and class-specific behavioral patterns.
Several important characteristics were identified:
- The target distribution was substantially imbalanced, with class 0 representing the majority of samples.
- Several numerical features exhibited strong positive skewness and extreme outliers.
- Demographic attributes contained a significant proportion of missing values.
- Multiple comments were associated with the same post identifiers.
- Comment lengths, capitalization patterns, punctuation usage, and engagement statistics varied across samples.
- Temporal patterns influenced the volume of comments more clearly than their relative class distribution.
These observations informed the subsequent preprocessing, feature engineering, and model evaluation strategies.
Custom Feature Engineering
Rather than relying exclusively on the original dataset attributes, I developed five reusable custom transformers using Scikit-learn's BaseEstimator and TransformerMixin interfaces.
These transformers generate 19 additional features across five categories.
| Transformer | Engineered Features |
|---|---|
| DateFeatureExtractor | Year, month, day, hour, day of week, weekend indicator, night-time indicator |
| VoteFeatureEngineer | Vote ratio, total votes, difference between upvotes and downvotes |
| TextFeatureEngineer | Comment length, word count, question-mark count, exclamation-mark count, capitalization ratio |
| CommentPerPost | Number of comments associated with a post |
| EmoticonFeatureEngineer | Total emoticons, emoticon presence indicator, emoticon ratio |
Each transformer exposes a consistent fit-transform interface, allowing it to be integrated into larger preprocessing pipelines.
The CommentPerPost transformer learns post-frequency statistics during its fit stage and reuses those statistics during inference, rather than recomputing them from the evaluation dataset.
This modular implementation supports consistent feature generation across training, validation, and test data.
Data Cleaning and Numerical Preprocessing
The preprocessing system applies different transformations depending on the characteristics of each feature.
Missing categorical attributes are represented using an explicit unknown category, avoiding unsupported assumptions about their original values. Missing comment text is replaced with an empty string.
Highly skewed non-negative numerical features are transformed using log1p to reduce the influence of extreme values.
Continuous numerical features are standardized using StandardScaler, while selected categorical attributes are transformed using one-hot encoding.
The categorical encoder is configured to handle previously unseen categories during inference.
These operations are combined using ColumnTransformer, allowing numerical, categorical, and textual data to be processed independently before their representations are merged.
Natural Language Processing Pipeline
The text preprocessing pipeline combines two complementary TF-IDF representations.
Word-Level TF-IDF
The word vectorizer captures lexical patterns through individual words and word combinations.
Its configuration includes:
- Unigram and bigram representations.
- English stop-word removal.
- Maximum vocabulary size of 15,000 features.
- Minimum document frequency of 2.
- Maximum document frequency of 0.9.
Character-Level TF-IDF
The character vectorizer captures subword patterns that may be overlooked by word-level representations.
Its configuration includes:
- Character n-grams within word boundaries.
- N-gram lengths from 3 to 5.
- Maximum vocabulary size of 2,000 features.
- Minimum document frequency of 2.
Character-level representations are particularly useful for capturing spelling variations, informal language, morphological patterns, and misspelled words.
Together, both vectorizers provide up to 17,000 text-derived features, which are combined with structured and engineered numerical features.
Dimensionality Reduction Experiment
The combined feature representation creates a high-dimensional sparse feature space.
To investigate whether dimensionality reduction could improve computational efficiency, I experimented with Truncated Singular Value Decomposition using 300 components.
However, the recorded experiments indicated that reducing the sparse representation negatively affected predictive performance.
| Model | Macro F1 Without SVD | Macro F1 With SVD |
|---|---|---|
| XGBoost | 0.7830 | 0.7144 |
| MLPClassifier | 0.7845 | 0.7351 |
| LinearSVC | 0.7624 | 0.7351 |
Based on these observations, dimensionality reduction was excluded from the final preprocessing pipeline.
While the experiments also involved differences in text-vectorization configurations, they suggested that aggressive feature compression could discard useful predictive information.
Model Development and Experimentation
Multiple supervised learning architectures were implemented and evaluated to identify suitable approaches for the classification task.
The experimental configurations include:
- Logistic Regression
- Stochastic Gradient Descent Classifier
- Linear Support Vector Classifier
- Decision Tree Classifier
- Random Forest Classifier
- XGBoost
- LightGBM
- Multi-Layer Perceptron
- Stacking Ensemble
These models represent different learning approaches, including linear decision boundaries, hierarchical decision trees, gradient-boosted ensembles, and neural networks.
A shared training and evaluation function was implemented to record predictive metrics, training duration, model configurations, and validation predictions.
This enabled comparative analysis across different architectures and feature representations.
Handling Class Imbalance
The dataset contains a substantial difference between the frequencies of majority and minority classes.
To reduce the tendency of classifiers to favor majority-class predictions, class weighting was incorporated into supported models.
For XGBoost experiments, inverse-frequency sample weights were calculated using compute_sample_weight.
The weighting strategy assigns greater importance to samples belonging to underrepresented classes during model optimization.
Macro F1 was selected as the primary model-comparison metric because it assigns equal importance to each class, regardless of its frequency in the dataset.
Hyperparameter Optimization
Hyperparameter search experiments were conducted for XGBoost, LightGBM, and LinearSVC using RandomizedSearchCV.
Due to the size of the dataset and computational requirements, a stratified subset containing 20% of the labeled data was selected for the search experiments.
The resulting configurations were subsequently evaluated within the broader training workflow.
| Model | Parameters Investigated |
|---|---|
| XGBoost | Number of estimators, tree depth, learning rate, subsampling ratio |
| LightGBM | Number of estimators, learning rate, number of leaves, minimum child samples, feature subsampling, regularization |
| LinearSVC | Regularization parameter C |
The experimental results indicated that hyperparameter tuning did not necessarily improve Macro F1 for every model.
This reinforced the importance of aligning the optimization objective with the final evaluation metric and verifying tuned configurations against held-out data.
Stacking Ensemble Architecture
The final selected model uses stacked generalization to combine three complementary classifiers.
The base-level estimators consist of:
- Tuned XGBoost.
- Tuned LightGBM.
- Tuned LinearSVC.
A Logistic Regression classifier acts as the second-level meta-estimator.
The stacking architecture uses three-fold cross-validation to generate base-estimator predictions for training the meta-classifier.
XGBoost and LightGBM contribute probability-based outputs, while LinearSVC contributes decision-function scores.
The meta-classifier learns how to combine these predictions to produce the final category.
This approach combines the nonlinear modeling capabilities of gradient-boosted decision trees with the strengths of linear classification in high-dimensional feature spaces.
The final pipeline integrates preprocessing and ensemble classification into a unified fit-predict interface.
Engineering Challenges
Combining Heterogeneous Data Sources
The dataset contains numerical, categorical, temporal, textual, and engagement-related features.
Applying a single preprocessing approach to every input would overlook their different statistical characteristics.
To address this, I designed independent transformation pipelines for different feature groups and integrated them through ColumnTransformer.
This architecture provides a structured approach to combining sparse NLP representations with dense numerical and categorical features.
Managing High-Dimensional Feature Representations
Word-level and character-level TF-IDF generate thousands of potential features.
This introduces challenges related to memory consumption, model training duration, and computational efficiency.
TruncatedSVD was investigated as a potential optimization, but the recorded experiments demonstrated lower predictive performance after dimensionality reduction.
Consequently, the final pipeline retained the sparse feature representation, prioritizing predictive performance over aggressive compression.
Handling Minority-Class Predictions
A model that predicts majority classes accurately may achieve high overall accuracy while performing poorly on underrepresented categories.
The project addresses this through class weighting, sample weighting, stratified validation, and Macro F1-based evaluation.
Class-level confusion matrices and classification reports were used to identify performance differences that would otherwise be concealed by aggregate accuracy.
Computational Constraints
Training multiple machine learning models on nearly 200,000 labeled records with thousands of features introduces considerable computational requirements.
The stacking ensemble was particularly expensive because its base estimators must be trained repeatedly during cross-validation.
To manage these constraints, the project uses subset-based hyperparameter search, recorded experiment histories, sparse feature representations, and restricted ensemble-level parallelism.
These decisions enabled broader experimentation within the available computational environment.
Consistent Preprocessing During Inference
Feature generation must remain consistent between training and prediction.
Recomputing text vocabularies, scaling statistics, or categorical mappings independently on test data would create incompatible feature representations.
The preprocessing pipeline learns these transformations during training and reuses them when processing validation and test samples.
Integrating preprocessing with the final estimator also reduces the risk of inconsistent feature construction during inference.
Technical Decisions
| Decision | Rationale |
|---|---|
| Custom Scikit-learn transformers | Creates reusable feature engineering components with consistent interfaces |
| ColumnTransformer | Supports independent preprocessing of heterogeneous data types |
| Word-level TF-IDF | Captures lexical patterns and word combinations |
| Character-level TF-IDF | Captures subword patterns, spelling variations, and informal writing |
| Logarithmic transformation | Reduces extreme numerical skewness |
| StandardScaler | Standardizes numerical feature scales |
| One-hot encoding | Represents categorical attributes without introducing artificial ordinal relationships |
| Retaining sparse features | Preserves predictive information that may be lost through aggressive dimensionality reduction |
| Class and sample weighting | Addresses differences in class frequencies |
| Stratified validation | Approximately preserves class distributions across dataset partitions |
| Subset-based hyperparameter search | Reduces computational requirements during experimentation |
| Stacking ensemble | Combines complementary linear and nonlinear classification approaches |
| Logistic Regression meta-classifier | Learns how to combine base-model prediction signals |
| Macro F1 evaluation | Assigns equal importance to all four target classes |
Results & Outcomes
The project resulted in a complete multiclass classification pipeline supporting mixed-data preprocessing, custom feature engineering, model comparison, ensemble learning, and automated competition inference.
Comparative Model Performance
The following table summarizes recorded validation results from the experimental notebook.
| Model | Macro F1 | Accuracy |
|---|---|---|
| Stacking Ensemble | 0.8282 | 91.63% |
| LightGBM | 0.8237 | 91.40% |
| Tuned LightGBM | 0.7987 | 90.35% |
| Weighted XGBoost | 0.7984 | 90.44% |
| Tuned XGBoost | 0.7937 | 91.13% |
| MLPClassifier | 0.7845 | 89.70% |
| LinearSVC | 0.7831 | 89.21% |
| Tuned LinearSVC | 0.7798 | 89.09% |
| Random Forest | 0.7361 | 89.32% |
| Decision Tree | 0.6797 | 84.70% |
| Logistic Regression | 0.6745 | 83.07% |
| SGDClassifier | 0.0372 | 8.04% |
The recorded experiments include different feature representations, weighting strategies, and model configurations. Consequently, these results represent the explored experimental configurations rather than a strictly controlled architecture-only comparison.
Final Ensemble Performance
The stacking ensemble achieved the strongest recorded validation Macro F1 and accuracy.
| Metric | Value |
|---|---|
| Macro F1 | 0.8282 |
| Weighted F1 | 0.9173 |
| Accuracy | 0.9163 |
| Macro Precision | 0.8211 |
| Macro Recall | 0.8359 |
A subsequent training run produced a classification report with approximately 92% accuracy and a Macro F1 score of 0.83.
Class-Level Evaluation
| Class | Precision | Recall | F1 Score | Validation Samples |
|---|---|---|---|---|
| Class 0 | 0.98 | 0.95 | 0.96 | 22,835 |
| Class 1 | 0.76 | 0.82 | 0.79 | 3,183 |
| Class 2 | 0.87 | 0.90 | 0.89 | 12,488 |
| Class 3 | 0.67 | 0.68 | 0.67 | 1,094 |
The class-level evaluation reveals that the model performs most strongly on the majority class, while the least represented class remains comparatively difficult to predict.
Computational Trade-offs
Although the stacking ensemble achieved the highest recorded validation Macro F1, its improvement over standalone LightGBM was relatively small.
LightGBM achieved a Macro F1 of 0.8237 with a recorded training and evaluation duration of approximately 26 minutes.
The stacking ensemble improved this score to 0.8282 but required approximately 4.2 hours for the corresponding recorded experiment.
This comparison highlights an important engineering trade-off between predictive performance and computational efficiency.
For applications where training cost and operational simplicity are significant considerations, standalone LightGBM may represent a more practical alternative.
Implementation Outcomes
- Processed 300,000 comment records.
- Developed five custom feature engineering transformers.
- Generated 19 additional structured features.
- Combined word-level and character-level TF-IDF representations.
- Evaluated eight individual classifier architectures and a stacking ensemble.
- Compared 12 principal experimental configurations.
- Achieved a recorded validation Macro F1 of 0.8282.
- Achieved a recorded validation accuracy of 91.63%.
- Retrained the selected pipeline on all 198,000 labeled records.
- Generated predictions for 102,000 test records.
Lessons Learned
Developing Comment Category Prediction strengthened my understanding of practical machine learning workflows, particularly the relationship between feature quality, model selection, experimental methodology, and computational efficiency.
The project provided practical experience in:
- Conducting exploratory analysis on large heterogeneous datasets.
- Building custom feature engineering components with Scikit-learn.
- Combining natural language features with structured contextual information.
- Working with high-dimensional sparse feature representations.
- Handling missing values and skewed numerical distributions.
- Addressing imbalanced multiclass classification.
- Evaluating the limitations of dimensionality reduction.
- Performing hyperparameter optimization under computational constraints.
- Implementing stacked ensemble learning.
- Interpreting class-level metrics and classification errors.
- Designing consistent training and inference pipelines.
One of the most important findings was that increasing model complexity does not necessarily produce a proportionate improvement in predictive performance.
Feature representation, evaluation methodology, class balance, and computational trade-offs are equally important when developing practical machine learning systems.
Future Improvements
Potential directions for further development include:
Experimental Methodology
- Aligning hyperparameter optimization explicitly with Macro F1.
- Performing hyperparameter search exclusively within training partitions.
- Integrating preprocessing into cross-validation folds.
- Conducting grouped validation based on post identifiers.
- Evaluating temporal generalization using chronological dataset splits.
- Performing controlled feature-group ablation experiments.
- Introducing consistent experiment configuration and artifact management.
Model Performance
- Investigating pretrained language model embeddings.
- Evaluating transformer-based text classification.
- Exploring hybrid neural and structured-data architectures.
- Improving minority-class prediction through alternative weighting strategies.
- Investigating probability calibration and class-specific decision thresholds.
- Exploring more efficient ensemble configurations.
Responsible Machine Learning
- Evaluating demographic feature importance and potential proxy effects.
- Comparing predictive performance with and without sensitive attributes.
- Measuring class-level and subgroup-level fairness.
- Investigating whether engagement features are available at the intended prediction time.
Deployment and Engineering
- Separating notebook-based experimentation into reusable Python modules.
- Persisting trained preprocessing and classification pipelines.
- Developing automated tests for custom transformers.
- Introducing model and dataset versioning.
- Developing a lightweight inference service.
- Monitoring predictive performance and data distribution changes.