Text Classification
Transformers
Safetensors
PyTorch
English
roberta
sentiment-analysis
fastapi
multilingual
docker
kafka
nlp
Eval Results (legacy)
Instructions to use SkyNet-DL/sentiment-roberta with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use SkyNet-DL/sentiment-roberta with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="SkyNet-DL/sentiment-roberta")# Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("SkyNet-DL/sentiment-roberta") model = AutoModelForSequenceClassification.from_pretrained("SkyNet-DL/sentiment-roberta") - Notebooks
- Google Colab
- Kaggle
File size: 40,863 Bytes
2e4d08f 1de9d90 6e1eb54 aab2898 1de9d90 6e1eb54 1de9d90 6e1eb54 1de9d90 6e1eb54 1de9d90 6e1eb54 1de9d90 aab2898 6e1eb54 fc6d0bd f11ed1c 6e1eb54 f11ed1c 6e1eb54 f11ed1c 1374065 f11ed1c 1374065 f11ed1c b8d3d37 fc6d0bd b8d3d37 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 | ---
language:
- en
license: mit
tags:
- sentiment-analysis
- roberta
- transformers
- pytorch
- fastapi
- multilingual
- docker
- kafka
- nlp
pipeline_tag: text-classification
library_name: transformers
datasets:
- Reddit
metrics:
- accuracy
- f1
model-index:
- name: sentiment-roberta
results:
- task:
type: text-classification
name: Sentiment Analysis
dataset:
name: Reddit Sentiment Dataset
type: custom
metrics:
- type: accuracy
value: 0.8709
name: Accuracy
- type: f1
value: 0.8715
name: Weighted F1 Score
---
## π Project Philosophy
This project intentionally preserves a controlled amount of real-world noise inside the final training dataset instead of aggressively sanitizing every sample.
The objective was to train the sentiment classifier under realistic social-media conditions, where user-generated content naturally includes:
- repetitive text
- malformed sentences
- slang and informal grammar
- emotionally chaotic writing
- duplicated phrases
- inconsistent punctuation
- low-quality Reddit comments
- partially incoherent text
- noisy conversational patterns
Examples of preserved noise include:
- repeated phrases such as: "Avoid being judgmental."
- incomplete or poorly structured sentences
- emotionally disorganized long-form Reddit posts
- imperfect GPT-generated synthetic samples
- informal internet writing styles
Rather than building a perfectly clean academic benchmark, the pipeline focuses on creating a model capable of handling imperfect real-world inputs commonly found on social media platforms.
The preprocessing pipeline still performs:
- invalid text filtering
- semantic validation
- augmentation quality control
- synthetic sample filtering
but intentionally avoids over-cleaning the dataset in order to preserve natural language variability.
This strategy improves:
- robustness to noisy inputs
- real-world generalization
- inference stability
- tolerance to imperfect user text
- production-oriented behavior
The final model was designed to operate under realistic NLP conditions rather than idealized datasets.
β οΈ Note:
Even though the model achieved strong performance under noisy conditions, cleaner datasets and more aggressive manual curation could likely produce even higher evaluation metrics and better class separation.
For optimal training performance, GPU acceleration is strongly recommended. A GPU with at least **8 GB of VRAM** is suggested for fine-tuning RoBERTa efficiently, especially when using:
- mixed precision training
- gradient accumulation
- SWA optimization
- larger batch sizes
- transformer-based augmentation pipelines
## π Project Overview
The pipeline consists of the following stages:
1. **Reddit Data Extraction**
2. **Real-Time Streaming with Apache Kafka**
3. **Data Storage with PostgreSQL / MySQL**
4. **Text Cleaning, Data Augmentation & Dataset Balancing**
5. **Fine-Tuning the RoBERTa Sentiment Classifier**
6. **Model Evaluation, Testing & Inference**
7. **Inference API & Web Interface**
8. **Full Docker Support**
9. **Installation & Environment Setup**
## π₯ 1. Reddit Data Extraction
- Data is collected from the Reddit API using multiple subreddits grouped into **five categories**.
- The number of posts retrieved is customizable through the `TOTAL_LIMIT` variable.
- The project supports environment-based Reddit authentication using:
```env
REDDIT_CLIENT_ID
REDDIT_CLIENT_SECRET
REDDIT_USER_AGENT
REDDIT_USERNAME
REDDIT_PASSWORD
## β‘ 2. Real-Time Streaming with Apache Kafka
The pipeline leverages Apache Kafka to enable real-time data ingestion and processing.
This stage is composed of two main components:
π€ Kafka Producer
- Fetches Reddit posts dynamically using the Reddit API
- Streams each post as a message into a Kafka topic (reddit_posts)
- Controls the ingestion rate to avoid overwhelming the system
- Ensures scalability by decoupling data ingestion from downstream processing
Key responsibilities:
- Data ingestion from Reddit
- Message serialization (JSON)
- Publishing messages to Kafka topics
π₯ Kafka Consumer
- Subscribes to the reddit_posts topic
- Consumes messages in batches for efficiency
- Stores raw data into the database (reddit_posts table)
- Applies preprocessing and data augmentation
- Publishes cleaned data into a new Kafka topic (cleaned_data)
Key responsibilities:
- Batch processing of streaming data
- Data persistence (raw + processed)
- Data cleaning and transformation
- Forwarding processed data for downstream tasks
π Streaming Flow
Reddit API β Kafka Producer β Kafka Topic (reddit_posts)
β Kafka Consumer β Database (raw data)
β Data Cleaning & Augmentation
β Kafka Topic (cleaned_data)
βοΈ Kafka Configuration
The pipeline supports both local execution and Docker-based environments.
Kafka broker address
- Use "localhost:9092" for local execution
- Use "kafka:9092" when running with Docker
KAFKA_BROKER=localhost:9092 or kafka:9092
Input topic (raw Reddit data)
KAFKA_TOPIC=reddit_posts
Consumer group identifier (for scalability and fault tolerance)
KAFKA_CONSUMER_GROUP=reddit_consumer_group
Output topic (processed/cleaned data)
TOPIC_OUTPUT=cleaned_data
Consumer group ID (used internally by Kafka)
GROUP_ID=reddit_consumer_group
π§ Design Considerations
- Decoupled Architecture: Producers and consumers operate independently
- Scalability: Multiple consumers can be added using the same GROUP_ID
- Fault Tolerance: Kafka ensures message durability and replayability
- Batch Processing: Improves performance and reduces database overhead
- Streaming + Processing Hybrid: Combines real-time ingestion with batch transformations
π Why Kafka?
Using Apache Kafka allows this pipeline to:
Handle large-scale data ingestion
Enable real-time sentiment analysis pipelines
Support future extensions (e.g., monitoring, alerting, dashboards)
Integrate easily with distributed systems (Spark, Flink, etc.)
## ποΈ 3. Data Storage with PostgreSQL / MySQL
The pipeline includes a flexible and scalable storage layer built on top of relational databases such as PostgreSQL and MySQL.
Database interactions are managed using SQLAlchemy, enabling seamless switching between database engines without modifying the core logic.
βοΈ Database Configuration
The system is fully configurable via environment variables:
# Supported values: "postgres" or "mysql"
DB_TYPE=
DB_HOST=
DB_PORT=
DB_NAME=
DB_USER=
DB_PASSWORD=
π Connection Management
A centralized connection handler dynamically builds the database URL
Uses SQLAlchemy engine for efficient connection pooling
Ensures a single reusable connection instance across the pipeline
Supports both local and Docker-based environments
π§± Data Model Overview
The pipeline stores data across multiple structured tables:
π₯ reddit_posts (Raw Data)
Stores original Reddit data ingested from Kafka.
Fields:
- id (Primary Key)
- title
- text
- score
- num_comments
- created_utc
- url
- label (auto-generated)
π Labeling Strategy:
Rule-based labeling using subreddit categories
Fallback to sentiment analysis using VADER
Hybrid approach improves labeling robustness
π§Ή cleaned_data (Processed Data)
Stores cleaned and normalized text ready for training.
Fields:
- id
- text
- label
π relabeled_data (Hybrid Relabeling)
Stores dataset after applying model-based relabeling
Used to reduce noise and improve data quality before training
Hybrid relabeling uses a pretrained external model
(cardiffnlp/twitter-roberta-base-sentiment)
before the final fine-tuning stage.
βοΈ balanced_* (Balanced Datasets)
Stores class-balanced datasets
Created using undersampling or other balancing strategies
π§ͺ synthetic_* (Augmented Data)
Stores synthetically generated samples
Used to improve minority class representation
π validation_data
Stores validation split (20% of dataset)
Includes text and numeric labels used for evaluation
π validation_results
Stores model predictions for validation data
Automatically resets before inserting new results
π§ Data Processing Logic
- Raw messages from Kafka are stored immediately in reddit_posts
- Data validation filters:
- Missing fields (id, text)
- Non-informative text
- Hybrid labeling system:
- Subreddit-based labeling
- VADER sentiment fallback
- Cleaned data is stored in cleaned_data
- Additional transformations generate:
- Relabeled datasets
- Balanced datasets
- Synthetic datasets
Kafka (reddit_posts)
β
Database (reddit_posts - raw)
β
Validation + Labeling (Hybrid)
β
Database (cleaned_data)
β
(Others)
β relabeled_data:
β balanced_data: Balance dataset distribution through oversampling, downsampling or both
β combined: Combine relabeled (raw data) and cleaned data
β synthetic_data: Data generated by GPT-2 for oversampling
The dataset used to train the model consists of a mix of balanced and combined data.
Which is called balanced combined
## π§Ή 4. Text Cleaning, Data Augmentation & Dataset Balancing
A critical stage of the pipeline focuses on improving data quality, dataset diversity, and class balance before model training.
This step combines:
- Text normalization and preprocessing
- Invalid / noisy text filtering
- Traditional NLP-based data augmentation
- Hybrid dataset balancing using downsampling + oversampling
- Synthetic text generation using GPT-2-based controlled generation
This significantly improves training stability and model generalization.
π§½ Text Cleaning
The clean_text() function standardizes the input text before training.
- Applied preprocessing steps:
- Convert text to lowercase
- Remove special characters
- Remove extra spaces
- Remove emojis and Unicode symbols
- Remove English stopwords using NLTK
- Normalize sentence structure
This helps reduce noise and improves semantic consistency across samples.
π« Invalid Text Detection
The is_valid_text() function filters low-quality or meaningless content such as:
- [deleted]
- [removed]
- placeholder text
- extremely short texts
- non-informative content
- malformed generated samples
This prevents noisy samples from contaminating the training dataset.
π Traditional Data Augmentation
To increase dataset diversity, the pipeline applies lightweight augmentation techniques:
πΉ Synonym Replacement
Uses WordNet through NLTK to replace words with semantically similar synonyms.
Example:
Original: I feel very happy today
Augmented: I feel very glad today
πΉ Word Dropout
Randomly removes non-critical words while preserving semantic meaning.
Special care is taken to preserve:
negations (not, never, no)
short but important words
Example:
Original: I do not like this product at all
Augmented: I not like product
π§ Semantic Validation
Not every augmentation is useful.
The pipeline uses Sentence Transformers (all-MiniLM-L6-v2) to validate semantic similarity between:
- original text
- augmented text
using cosine similarity.
This prevents augmentation from changing the original sentiment meaning.
βοΈ Dataset Balancing Strategy
The original Reddit dataset was highly imbalanced across sentiment classes:
- Positive
- Neutral
- Negative
To prevent model bias toward majority classes, a hybrid balancing strategy was implemented.
π½ Downsampling (Majority Class)
If severe imbalance is detected:
the majority class is partially reduced
the reduction ratio is automatically adjusted based on imbalance severity
This avoids over-representation without losing too much valuable information.
- Adaptive strategy:
- High imbalance β stronger downsampling
- Moderate imbalance β softer downsampling
This is more robust than fixed-ratio downsampling.
πΌ Oversampling (Minority Classes)
Minority classes are expanded using synthetic text generation with GPT-2.
This improves representation for underrepresented sentiment classes.
The system automatically:
- detects minority classes
- calculates missing samples
- generates only the required amount
This avoids unnecessary synthetic noise.
π§ͺ Synthetic Data Generation with GPT-2
Instead of naive duplication, the project generates new realistic Reddit-style text samples using:
GPT-2 + prompt-based controlled generation
Each sentiment class uses specialized prompts
Example prompts:
Negative β dissatisfaction / frustration
Neutral β factual, emotion-free statements
Positive β appreciation / satisfaction
Example:
Write a short emotionally positive Reddit comment showing appreciation and satisfaction.
Generation uses:
- nucleus sampling (top_p)
- temperature control
- filtering and validation
- post-cleaning of generated outputs
This produces higher-quality synthetic samples for oversampling.
π§Ό Synthetic Data Filtering
Generated samples are additionally filtered using:
- minimum word count
- punctuation checks
- invalid symbol detection
- spam/noise detection
- malformed sentence removal
- prompt leakage removal
This ensures only high-quality synthetic samples are retained.
π Preprocessing Metrics
The system tracks preprocessing quality using shared metrics:
- empty_text_count
- invalid_text_count
This helps monitor:
- dataset quality
- cleaning effectiveness
- augmentation quality
and improves debugging across the full pipeline.
π Full Preprocessing Flow
Raw Reddit Data
β
Text Cleaning
β
Invalid Text Filtering
β
Traditional Augmentation
β synonym replacement
β word dropout
β
Dataset Balancing
β downsampling
β oversampling (GPT-2)
β
Synthetic Data Validation
β
Final Training Dataset
π Why This Matters
This stage improves:
- Model generalization
- Class balance
- Training stability
- Minority class performance
- Label quality
- Real-world robustness
Without this step, the model would suffer from:
- overfitting
- class bias
- poor minority recall
- noisy training signals
## π€ 5. Fine-Tuning the RoBERTa Sentiment Classifier
The training stage focuses on fine-tuning RoBERTa for multi-class sentiment classification:
- Negative
- Neutral
- Positive
The model is trained using a production-oriented strategy designed to improve:
- generalization
- minority class performance
- training stability
- robustness against overfitting
This goes far beyond standard fine-tuning.
π§ Model Architecture
The project uses:
roberta-base
via Hugging Face Transformers.
Configuration includes:
- num_labels = 3
- reduced dropout tuning
- attention dropout optimization
- progressive layer unfreezing
- mixed precision training
- SWA optimization
This setup improves performance while maintaining efficient training.
π¦ Flexible Dataset Selection
Training supports multiple dataset sources:
Available sources:
- raw β original Reddit data
- relabeled β hybrid relabeled dataset
- cleaned β cleaned + augmented dataset
- combined β 50% relabeled + 50% cleaned
Available training modes:
- unbalanced
- balanced
- synthetic
This allows controlled experimentation and comparison between data strategies.
Example:
train_model(
data_source="combined",
dataset_type="balanced"
)
βοΈ Loss Function Strategy
Because sentiment classes remain naturally imbalanced, the training pipeline uses advanced loss handling.
π₯ Focal Loss (Primary)
Custom Focal Loss is used to improve minority class learning.
Benefits:
- reduces dominance of easy samples
- focuses on hard examples
- improves minority recall
- reduces majority class bias
Additional improvements:
- dynamic alpha calculation
- class-aware weighting
- special boost for the Neutral class
This significantly improved F1 performance.
πΉ Weighted CrossEntropy (Alternative)
Also implemented as a fallback baseline using:
- class weights
- balanced label distribution
This allows direct comparison against Focal Loss.
π§ Progressive Layer Freezing / Unfreezing
Instead of fine-tuning the full model immediately
Initial strategy:
- first 6 RoBERTa layers are frozen
Progressive unfreezing:
- deeper layers are gradually unfrozen every few epochs
Benefits:
- prevents catastrophic forgetting
- stabilizes early training
- improves transfer learning efficiency
- reduces overfitting risk
This behaves similarly to advanced techniques like Layer-wise Learning Rate Decay (LLRD).
π Learning Rate Optimization
The project uses:
OneCycleLR Scheduler
instead of static learning rates.
This provides:
- warm-up phase
- cosine annealing
- smoother convergence
- better final generalization
Additional learning rate reductions are applied when new layers are unfrozen.
β‘ Mixed Precision + Gradient Accumulation
Training includes:
- Mixed Precision Training
Using:
- autocast + GradScaler
Benefits:
- lower VRAM consumption
- faster training
- improved GPU efficiency
Gradient Accumulation
Configuration:
- batch_size = 24
- accumulation_steps = 3
This simulates larger effective batch sizes without GPU memory issues.
π§ Stochastic Weight Averaging (SWA)
The final training epochs use:
SWA (Stochastic Weight Averaging)
This technique:
- averages model weights
- improves generalization
- produces flatter minima
- reduces validation instability
The final saved model is the SWA-optimized version, not the raw last epoch checkpoint.
π Early Stopping
To avoid overfitting:
Early stopping monitors:
- weighted F1-score
- validation loss
Training stops automatically if no improvement is detected.
This prevents unnecessary training and preserves the best-performing checkpoint.
π Validation Strategy
Dataset split:
- 80% Training
- 20% Validation
using stratified sampling.
Validation data is also stored in the database for:
- reproducibility
- inference testing
- model evaluation consistency
π Evaluation Metrics
Each epoch tracks:
- Validation Accuracy
- Weighted F1 Score
- Training Loss
- Validation Loss
- Full Classification Report
Special focus is placed on:
Weighted F1 Score
because it better reflects performance on imbalanced datasets.
πΎ Model Saving
The final model is saved as:
Roberta_sentiment_model/
including:
- model weights (model.safetensors)
- tokenizer
- config files
- tokenizer metadata
This allows immediate deployment with:
- AutoTokenizer.from_pretrained(...)
- AutoModelForSequenceClassification.from_pretrained(...)
and direct upload to Hugging Face.
π Training Flow
Balanced Dataset
β
Train / Validation Split
β
RoBERTa Tokenization
β
Progressive Fine-Tuning
β Focal Loss
β OneCycleLR
β Mixed Precision
β SWA
β Early Stopping
β
Validation Monitoring
β
Best Model Selection
β
Final SWA Model Saved
This is a production-grade training strategy for robust NLP classification
with:
- advanced optimization
- imbalance handling
- model stability improvements
- reproducible experimentation
- deployable output
## π§ͺ 6. Model Evaluation, Testing & Inference
After training, the fine-tuned RoBERTa model is evaluated using a dedicated validation pipeline designed to measure both global performance and per-class robustness.
This stage ensures the model is reliable before deployment and provides detailed diagnostics for sentiment classification quality.
π¦ Validation Dataset
The validation dataset is automatically created during training using an 80/20 stratified split:
- 80% β Training set
- 20% β Validation set
The validation split is stored in the database inside:
validation_data
Fields:
- id
- text
- label
This guarantees reproducibility and allows evaluation to be performed independently after training.
π€ Inference on Validation Data
The saved model from Roberta_sentiment_model is loaded for evaluation.
Each validation sample is processed using:
- RoBERTaTokenizer
- RoBERTaForSequenceClassification
- Softmax probability scoring
- Argmax class prediction
Predicted labels are then stored in:
validation_results
Fields:
- id
- text
- predicted_label
This separation between ground truth and predictions enables robust post-training analysis.
π Evaluation Metrics
The project uses multiple evaluation metrics to avoid relying only on accuracy.
- Global Metrics
- Accuracy
- Weighted F1-score
- Balanced Accuracy
- Matthews Correlation Coefficient (MCC)
These metrics provide a better understanding of performance, especially under class imbalance.
π Per-Class Detailed Metrics
For each sentiment class:
- Negative
- Neutral
- Positive
the system computes:
- TP (True Positives)
- TN (True Negatives)
- FP (False Positives)
- FN (False Negatives)
- Precision
- Recall
- F1-score
- Balanced Accuracy
- MCC
- Support
This helps identify which classes are harder to predict (typically the Neutral class).
π Confusion Matrix Analysis
Two confusion matrices are generated:
- Standard Confusion Matrix
Shows absolute prediction counts across classes.
<p align="center">
<img src="images/confusion_matrix.jpg" width="700"/>
</p>
- Normalized Confusion Matrix
Shows percentage-based performance for easier interpretation.
<p align="center">
<img src="images/confusion_matrix_normalized.png" width="700"/>
</p>
These visualizations help detect systematic classification errors and class confusion patterns.
π§Ύ Final Evaluation Results
Final model performance achieved:
- Accuracy: 0.8709
- F1-score: 0.8715
| Class | Precision | Recall | F1-Score | Balanced Acc. | MCC |
| -------- | --------: | -----: | -------: | ------------: | ----: |
| Negative | 0.884 | 0.878 | 0.881 | 0.910 | 0.822 |
| Neutral | 0.805 | 0.839 | 0.822 | 0.869 | 0.731 |
| Positive | 0.929 | 0.895 | 0.912 | 0.930 | 0.869 |
Key Observations
- Positive sentiment achieved the strongest performance
- Neutral sentiment remained the most challenging class
- Balanced Accuracy confirms strong generalization across classes
- MCC indicates strong classification reliability beyond simple accuracy
- Class balancing + hybrid relabeling + Focal Loss significantly improved minority class performance
π Manual Prediction Mode
The project also includes an interactive testing mode:
manual_prediction()
This allows users to input custom text and receive real-time sentiment predictions directly from the trained model.
Example:
Input: "I really enjoyed using this app today"
Prediction: Positive
This is useful for:
- quick qualitative testing
- manual verification
- demo purposes
- API validation before deployment
π Evaluation Flow
Training
β
Validation Split Saved
β
validation_data
β
Model Inference
β
validation_results
β
Metrics + Confusion Matrix + MCC + F1
β
Manual Testing
π― Why This Evaluation Strategy?
This evaluation design ensures:
- reliable offline validation
- reproducible testing
- strong interpretability
- production readiness
- detection of weak classes before deployment
Rather than using only accuracy, the project focuses on robust real-world performance validation for sentiment analysis systems.
## π 7. Inference API & Web Interface
To make the trained model easily accessible and testable, the project includes a production-ready REST API built with FastAPI, along with a lightweight web interface developed using HTML, CSS, and JavaScript.
This allows both programmatic access and interactive testing of the sentiment analysis model.
π API Features
- Real-time sentiment prediction
- Automatic language detection
- On-the-fly translation to English
- Probability distribution output
- Clean JSON responses
- Interactive browser-based UI
π Multilingual Support
The API supports multilingual input using:
- langdetect for language detection
- Helsinki-NLP/opus-mt-xx-en translation
π Flow:
User Input (any language)
β Language Detection
β (If not English) Translation to English
β RoBERTa Inference
β Sentiment Output
π Multilingual Support
The API supports multilingual sentiment analysis through automatic language detection and dynamic translation to English before inference.
Currently supported languages:
| Language | Code | Translation Model |
| -------- | ---- | ---------------------------- |
| English | `en` | No translation required |
| Spanish | `es` | `Helsinki-NLP/opus-mt-es-en` |
| French | `fr` | `Helsinki-NLP/opus-mt-fr-en` |
| German | `de` | `Helsinki-NLP/opus-mt-de-en` |
| Italian | `it` | `Helsinki-NLP/opus-mt-it-en` |
The API uses:
langdetect for automatic language identification
MarianMT translation models from Helsinki-NLP
Dynamic model loading with in-memory caching for improved performance
π Multilingual Inference Flow
User Input
β Language Detection
β Dynamic Translation Model Selection
β Translation to English (if required)
β RoBERTa Sentiment Inference
β Sentiment Prediction
This allows the RoBERTa model (trained in English) to perform sentiment analysis on multiple languages without retraining the classifier.
β‘ Dynamic Translation Model Loading
Translation models are loaded dynamically only when required.
Benefits:
- lower initial API startup time
- reduced memory usage
- scalable multilingual support
- cached translation models for faster repeated inference
Once a language model is loaded, it remains cached in memory and is reused for future requests.
π§ Model Inference
The API loads the fine-tuned model from:
Roberta_sentiment_model/
and performs:
- Tokenization with RobertaTokenizer
- Inference with RobertaForSequenceClassification
- Softmax probability calculation
- Argmax classification
π‘ API Endpoints
- POST /predict
Performs sentiment analysis on input text.
Request:
{
"text": "I really like this product!"
}
Response:
{
"input": "I really like this product!",
"prediction": {
"original_text": "I really like this product!",
"processed_text": "I really like this product!",
"label_index": 2,
"label": "Positive",
"probabilities": {
"Negative": 0.01,
"Neutral": 0.05,
"Positive": 0.94
}
}
}
- GET /form
Provides a web-based interface for testing the model.
π₯οΈ Web Interface (Frontend)
A simple UI is included to interact with the API directly from the browser.
Features:
- Text input box
- Submit button
- Real-time prediction display
- Clean and responsive design
Tech Stack:
- HTML
- CSS
- JavaScript (Fetch API)
π Project Structure (API)
fastapi_app/
βββ inference_api.py
templates/
βββ index.html
static/
βββ styles.css
βββ script.js
βΆοΈ Running the API
Locally:
python inference_api.py
or using Uvicorn:
uvicorn inference_api:app --host 0.0.0.0 --port 8000 --reload
π Access Points
Web Interface:
http://localhost:8000/form
Docs (Swagger UI):
http://localhost:8000/docs
π§ͺ Example Use Cases
- Manual sentiment testing
- Demo for stakeholders
- API integration in other services
- Validation before deploying to production
- Multilingual sentiment analysis
π― Why This API Matters
This component transforms the project from:
π just a trained model into a deployable, interactive AI service
It enables:
- real-time usage
- easy testing
- frontend integration
- production deployment readiness
## π³ 8. Full Docker Support
The project includes a fully containerized architecture designed for:
- reproducible environments
- simplified deployment
- scalable orchestration
- isolated services
- production-ready inference
- GPU-compatible model training
The platform provides two independent Docker images:
1. Full ML Pipeline Image
2. Inference API Image
DockerHub Repository:
https://hub.docker.com/repositories/cesarwkr
This separation allows training and inference to scale independently.
π§ Dockerized Architecture
The ecosystem is orchestrated using Docker Compose and includes:
- Apache Kafka
- Zookeeper
- PostgreSQL
- FastAPI Inference API
- Unified ML Pipeline
- Optional pgAdmin (development profile)
π¦ Docker Images
| Image | Purpose |
| -------------------------- | -------------------------- |
| `sentiment_pipeline` | End-to-end ML pipeline |
| `sentiment_inference_api` | Real-time inference API |
π§± Full Pipeline Container
The pipeline container executes the entire workflow through:
main.py
This includes:
- Reddit data extraction
- Kafka streaming
- Data ingestion
- Cleaning & preprocessing
- Hybrid relabeling
- Dataset balancing
- GPT-2 synthetic generation
- RoBERTa fine-tuning
- Validation & evaluation
- Manual testing
π Pipeline Flow
Reddit API
β Kafka Producer
β Kafka Consumer
β PostgreSQL
β Cleaning & Augmentation
β Hybrid Relabeling
β Dataset Balancing
β RoBERTa Training
β Validation & Metrics
β Final Model Export
βοΈ Main Pipeline Orchestration
The pipeline automatically coordinates:
- Kafka consumer threading
- asynchronous ingestion
- database synchronization
- training execution
- evaluation workflows
Key orchestration features:
- automatic waiting for processed data availability
- timeout protection
- validation-data persistence
- automatic model reuse if already trained
- GPU acceleration support
- mixed precision compatibility
π Inference API Container
A separate lightweight container is used for inference and deployment.
The API container includes:
- FastAPI
- multilingual translation support
- HTML/CSS/JS frontend
- Swagger documentation
- real-time sentiment inference
The inference service loads:
Roberta_sentiment_model/
and exposes:
- REST endpoints
- browser testing interface
- multilingual prediction support
π Multi-Stage Docker Builds
Both Dockerfiles use multi-stage builds to optimize:
- image size
- dependency reuse
- build speed
- security
β
Key Optimizations
- layered dependency caching
- reduced final image size
- isolated runtime environment
- removal of unnecessary build tools
- minimized attack surface
π Security Best Practices
The Docker setup follows several container security recommendations.
- Implemented Measures
- non-root execution (appuser)
- isolated runtime containers
- minimized base images
- dependency separation
- reduced privilege escalation risks
- environment-variable based configuration
Example:
RUN useradd --create-home --uid 1000 appuser
USER appuser
This prevents running services as root inside containers.
β‘ GPU Support
The training pipeline supports GPU acceleration using CUDA-enabled PyTorch images.
- Supported Features
- CUDA 12.4
- Mixed Precision Training
- SWA optimization
- Large transformer fine-tuning
Docker Compose GPU reservation:
deploy:
resources:
reservations:
devices:
- capabilities: [gpu]
This enables accelerated RoBERTa training when NVIDIA Docker runtime is available.
π§© Docker Compose Architecture
The full platform is orchestrated through:
docker-compose.yml
Included Services
| Service | Description |
| --------------- | -------------------------- |
| `zookeeper` | Kafka coordination |
| `kafka` | Real-time streaming |
| `postgres` | Persistent storage |
| `pipeline` | Unified ML workflow |
| `inference_api` | Real-time predictions |
| `pgadmin` | Optional DB administration |
π§ͺ Development Profiles
Docker Compose supports optional profiles for flexible execution.
Development Profile
Enables:
pgAdmin
- live development workflows
- local debugging
- GPU Profile
Enables:
- GPU access
- accelerated transformer training
Example:
docker compose --profile gpu up
π Persistent Volumes
Named Docker volumes are used for persistence:
volumes:
postgres_data:
pgadmin_data:
This preserves:
- database data
- pgAdmin configuration
- training metadata
across container restarts.
π Running the Platform
Start Infrastructure + Services:
docker compose up
Start with GPU Support:
docker compose --profile gpu up
Start Development Environment:
docker compose --profile dev up
π§ Inference API Access
Once running Web Interface
http://localhost:8000/form
Swagger Documentation
http://localhost:8000/docs
Run Container:
docker run -p 8000:8000 cesarwkr/sentiment_inference_api:latest
π οΈ Makefile Automation
The project includes a production-oriented Makefile to simplify Docker workflows.
Supported Commands
| Command | Description |
| -------------- | ------------------------- |
| `make build` | Build all images |
| `make up` | Start services |
| `make down` | Stop services |
| `make publish` | Build + tag + push images |
| `make clean` | Remove local images |
π DockerHub Authentication
The Makefile supports secure authentication using environment variables:
DOCKER_USERNAME=
DOCKER_PASSWORD=
π¦ Docker Image Publishing
The project supports automated DockerHub publishing.
Publish Workflow:
make publish
This automatically performs:
- image build
- tagging
- DockerHub push
π€ GitHub Actions CI/CD
A GitHub Actions workflow automates image publishing on every push to:
main
Automated Steps
- repository checkout
- DockerHub login
- Buildx setup
- pipeline image build
- inference API image build
- automatic DockerHub push
Workflow file:
.github/workflows/docker_publish.yml
β‘ Docker Slim Optimization
The inference API image supports additional optimization using:
Docker Slim
Benefits:
- reduced image size
- faster deployment
- lower attack surface
- improved startup speed
Example:
make slim
π― Why This Docker Architecture Matters
This Docker strategy transforms the project into a:
- portable ML platform
- production-ready NLP service
- scalable streaming architecture
- reproducible research environment
- deployable AI inference system
It enables:
- local development
- cloud deployment
- CI/CD integration
- GPU training
- scalable inference
- isolated environments
## 9. βοΈ Installation & Environment Setup
Before running the project locally, install the required Python dependencies.
1οΈβ£ Clone the Repository
2οΈβ£ Create a Virtual Environment (Recommended)
3οΈβ£ Install PyTorch with CUDA Support
This project was developed using:
- Python 3.12.3
- PyTorch 2.6.0
- CUDA 12.4
Install the CUDA-enabled version of PyTorch:
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124
Optional fixed version:
pip install torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124
This enables GPU acceleration for:
- RoBERTa fine-tuning
- mixed precision training
- SWA optimization
- transformer inference
4οΈβ£ Install Project Requirements
pip install -r requirements.txt
For the FastAPI inference service separately:
pip install -r fastapi_app/requirements.txt
5οΈβ£ Configure Environment Variables
Create a .env file in the root directory and configure:
REDDIT_CLIENT_ID=
REDDIT_CLIENT_SECRET=
REDDIT_USER_AGENT=
REDDIT_USERNAME=
REDDIT_PASSWORD=
DB_TYPE=
DB_HOST=
DB_PORT=
DB_NAME=
DB_USER=
DB_PASSWORD=
KAFKA_BROKER=
KAFKA_TOPIC=
β
Environment Ready
After installation, the project is ready for:
- local training
- Kafka streaming
- FastAPI inference
- Docker execution
- GPU acceleration
- model evaluation
π Additional Resources
The repository also includes exported datasets and a standalone training notebook for experimentation and reproducibility.
π Exported Datasets
All datasets used throughout the pipeline are available in the root directory inside:
Datasets/
These datasets were exported from the database into CSV format and can be used for:
- offline experimentation
- reproducible training
- model benchmarking
- data analysis
- visualization
- custom preprocessing workflows
The folder may contain datasets such as:
- reddit posts
- cleaned data
- relabeled data
- balanced combined
- validation data
- validation results
This allows users to explore the project without necessarily running the full Kafka pipeline.
π Standalone Training Notebook
The project also includes a Jupyter Notebook dedicated exclusively to model training.
Location:
just_train_model/train_roberta_sentiment.ipynb
This notebook provides a simplified workflow for:
- loading datasets directly from CSV files
- preprocessing text
- tokenization
- RoBERTa fine-tuning
- evaluation
- experimentation with hyperparameters
It is useful for:
- quick experimentation
- educational purposes
- testing training strategies
- debugging model behavior
- running training independently from the full streaming pipeline
The notebook allows users to train the sentiment classifier without needing to execute:
- Kafka
- Docker Compose
- the complete production pipeline
making experimentation significantly faster and easier.
π Kaggle Resources
The project also provides public Kaggle resources containing:
- the final balanced dataset used for training
- model evaluation workflows
- inference testing
- confusion matrix analysis
- performance metrics
These resources allow users to explore and validate the trained model without running the full pipeline locally.
π Kaggle Notebook (Model Testing & Evaluation)
A public Kaggle notebook is available for loading and testing the trained RoBERTa model
The notebook includes:
- loading the tokenizer
- loading model safetensors
- sentiment inference
- validation testing
- confusion matrix generation
- evaluation metrics
- prediction analysis
β οΈ Note:
The Kaggle notebook is focused on inference and evaluation only.
Model training is not performed inside the notebook.
π Kaggle Dataset
The balanced dataset used to train the final model is also publicly available
This dataset corresponds to the balanced combined dataset used during RoBERTa fine-tuning.
The dataset includes:
- cleaned Reddit text
- multiclass sentiment labels
- balanced class distributions
- training-ready samples
This allows users to:
- reproduce evaluation workflows
- test alternative models
- benchmark NLP architectures
- perform independent experimentation
- validate inference performance without rebuilding the entire pipeline
Dataset in kagle:
https://www.kaggle.com/datasets/cesarwk/balanced-multiclass-sentiment-dataset-from-reddit/settings
Notebook in Kagle:
https://www.kaggle.com/code/cesarwk/roberta-sentiment-model
π€ Hugging Face Model Hub
The trained RoBERTa model is publicly available on Hugging Face
from transformers import RobertaTokenizer, RobertaForSequenceClassification
MODEL_NAME = "SkyNet-DL/sentiment-roberta"
tokenizer = RobertaTokenizer.from_pretrained(MODEL_NAME)
model = RobertaForSequenceClassification.from_pretrained(MODEL_NAME)
Since the uploaded config.json currently contains generic labels (LABEL_0, LABEL_1, LABEL_2), sentiment labels can be manually mapped inside the inference code without needing to retrain or re-upload the model.
Example:
from transformers import RobertaTokenizer, RobertaForSequenceClassification
import torch
import torch.nn.functional as F
MODEL_NAME = "SkyNet-DL/sentiment-roberta"
# Load model from Hugging Face
tokenizer = RobertaTokenizer.from_pretrained(MODEL_NAME)
model = RobertaForSequenceClassification.from_pretrained(MODEL_NAME)
# Manual label mapping
LABELS = {
0: "Negative",
1: "Neutral",
2: "Positive"
}
text = "I really enjoyed this product!"
inputs = tokenizer(text, return_tensors="pt", truncation=True)
with torch.no_grad():
outputs = model(**inputs)
probs = F.softmax(outputs.logits, dim=1)
pred = torch.argmax(probs, dim=1).item()
print("Prediction:", LABELS[pred])
This approach allows the model to remain fully usable directly from Hugging Face even if the original config.json does not yet contain human-readable labels.
This allows:
- direct model download
- lightweight deployments
- easier inference integration
- simplified Docker images
- cloud-based model distribution
The model repository includes:
- model.safetensors
- tokenizer files
- config files
- vocabulary files
making the model fully compatible with Hugging Face Transformers.
Hugging face link: https://huggingface.co/SkyNet-DL/sentiment-roberta
## π₯ YouTube API Demo
A full video demonstration of the Sentiment Analysis API is also available on YouTube.
The video showcases:
- How to launch the FastAPI inference service
- How to use the web interface
- Real-time sentiment prediction testing
- Multilingual text inference
- API response behavior
- End-to-end model interaction
πΊ Watch the demo here:
https://www.youtube.com/watch?v=ExuS0F8i0Wo
This demo provides a quick overview of how the deployed inference system works in practice. |