mahekgheewala commited on
Commit
99561ed
·
verified ·
1 Parent(s): c51522a

Upload Reddit Sentiment Analysis Hybrid Model

Browse files
README.md ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ tags:
4
+ - sentiment-analysis
5
+ - text-classification
6
+ - multiclass-classification
7
+ - sentence-transformers
8
+ - xgboost
9
+ - reddit
10
+ - hybrid-model
11
+ language:
12
+ - en
13
+ metrics:
14
+ - accuracy
15
+ - f1
16
+ pipeline_tag: text-classification
17
+ widget:
18
+ - text: "I love this product! It's amazing and works perfectly."
19
+ example_title: "Positive Example"
20
+ - text: "This is terrible. I hate it so much."
21
+ example_title: "Negative Example"
22
+ - text: "The weather is okay today."
23
+ example_title: "Neutral Example"
24
+ ---
25
+
26
+ # Reddit Sentiment Analysis - Hybrid Model
27
+
28
+ 🎯 **Test Accuracy: 0.9966**
29
+
30
+ ## Model Description
31
+
32
+ This hybrid sentiment analysis model combines **Sentence Transformers** for semantic embeddings with **XGBoost** for classification. Trained on Reddit comments for multiclass sentiment analysis: **Negative**, **Positive**, and **Neutral**.
33
+
34
+ ### Architecture
35
+ ```
36
+ Input Text → SentenceTransformer → Embeddings (768D) →
37
+ Feature Engineering (Length + Sentiment + POS) → XGBoost → Prediction
38
+ ```
39
+
40
+ ## Quick Start
41
+
42
+ ```python
43
+ import pickle
44
+ import numpy as np
45
+ from sentence_transformers import SentenceTransformer
46
+ from textblob import TextBlob
47
+ import nltk
48
+ from huggingface_hub import hf_hub_download
49
+
50
+ # Download NLTK data
51
+ nltk.download('punkt', quiet=True)
52
+ nltk.download('averaged_perceptron_tagger', quiet=True)
53
+
54
+ # Load models
55
+ xgb_path = hf_hub_download(repo_id="USERNAME/sentimental_analysis_updated", filename="xgboost_model.pkl")
56
+ sentence_path = hf_hub_download(repo_id="USERNAME/sentimental_analysis_updated", filename="sentence_transformer")
57
+
58
+ # Load XGBoost model
59
+ with open(xgb_path, 'rb') as f:
60
+ pipeline_data = pickle.load(f)
61
+ xgb_model = pipeline_data['xgboost_model']
62
+ label_names = pipeline_data['label_names']
63
+
64
+ # Load SentenceTransformer
65
+ sentence_model = SentenceTransformer(sentence_path)
66
+
67
+ def predict_sentiment(text):
68
+ # Extract features
69
+ embedding = sentence_model.encode([text])
70
+ comment_length = np.array([len(text.split())]).reshape(-1, 1)
71
+ sentiment_polarity = np.array([TextBlob(text).sentiment.polarity]).reshape(-1, 1)
72
+
73
+ # POS counts
74
+ try:
75
+ tags = nltk.pos_tag(nltk.word_tokenize(text))
76
+ pos_counts = np.array([[
77
+ sum(1 for _, tag in tags if tag.startswith('J')), # Adjectives
78
+ sum(1 for _, tag in tags if tag.startswith('N')), # Nouns
79
+ sum(1 for _, tag in tags if tag.startswith('V')) # Verbs
80
+ ]])
81
+ except:
82
+ pos_counts = np.array([[0, 0, 0]])
83
+
84
+ # Combine features
85
+ features = np.hstack([embedding, comment_length, sentiment_polarity, pos_counts])
86
+
87
+ # Predict
88
+ prediction = xgb_model.predict(features)[0]
89
+ confidence = xgb_model.predict_proba(features)[0].max()
90
+
91
+ return {
92
+ 'label': label_names[prediction],
93
+ 'confidence': confidence,
94
+ 'prediction_id': int(prediction)
95
+ }
96
+
97
+ # Example usage
98
+ result = predict_sentiment("I love this new phone! It's amazing!")
99
+ print(f"Sentiment: {result['label']} (confidence: {result['confidence']:.3f})")
100
+ ```
101
+
102
+ ## Model Details
103
+
104
+ - **Base Model**: `paraphrase-mpnet-base-v2`
105
+ - **Classifier**: XGBoost with GPU acceleration
106
+ - **Features**: 772 dimensions (768 embeddings + 4 engineered)
107
+ - **Classes**: 0=Negative, 1=Positive, 2=Neutral
108
+ - **Training Data**: Reddit comments
109
+ - **Test Accuracy**: 0.9966
110
+
111
+ ## Training Configuration
112
+
113
+ - **XGBoost Parameters**: n_estimators=300, learning_rate=0.05, max_depth=6
114
+ - **Features**: Embeddings + Comment Length + TextBlob Sentiment + POS Counts
115
+ - **Class Balancing**: Sample weights for imbalanced data
116
+ - **Validation**: Stratified train/val/test split
117
+
118
+ ## Citation
119
+
120
+ ```bibtex
121
+ @misc{reddit-sentiment-hybrid,
122
+ title={Reddit Sentiment Analysis - Hybrid Model},
123
+ year={2025},
124
+ publisher={Hugging Face},
125
+ url={https://huggingface.co/USERNAME/sentimental_analysis_updated}
126
+ }
127
+ ```
128
+
129
+ ## License
130
+
131
+ MIT License
config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "hybrid-sentiment-classifier",
3
+ "architecture": "sentence-transformers + xgboost",
4
+ "base_model": "paraphrase-mpnet-base-v2",
5
+ "num_classes": 3,
6
+ "class_names": [
7
+ "Negative",
8
+ "Positive",
9
+ "Neutral"
10
+ ],
11
+ "test_accuracy": 0.9966352624495289
12
+ }
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ sentence-transformers>=2.2.0
2
+ xgboost>=1.6.0
3
+ scikit-learn>=1.0.0
4
+ numpy>=1.21.0
5
+ pandas>=1.3.0
6
+ textblob>=0.17.0
7
+ nltk>=3.7
8
+ torch>=1.9.0
9
+ huggingface-hub>=0.10.0
sentence_transformer/1_Pooling/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 768,
3
+ "pooling_mode_cls_token": false,
4
+ "pooling_mode_mean_tokens": true,
5
+ "pooling_mode_max_tokens": false,
6
+ "pooling_mode_mean_sqrt_len_tokens": false,
7
+ "pooling_mode_weightedmean_tokens": false,
8
+ "pooling_mode_lasttoken": false,
9
+ "include_prompt": true
10
+ }
sentence_transformer/README.md ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: sentence-transformers
4
+ tags:
5
+ - sentence-transformers
6
+ - feature-extraction
7
+ - sentence-similarity
8
+ - transformers
9
+ pipeline_tag: sentence-similarity
10
+ ---
11
+
12
+ # sentence-transformers/paraphrase-mpnet-base-v2
13
+
14
+ This is a [sentence-transformers](https://www.SBERT.net) model: It maps sentences & paragraphs to a 768 dimensional dense vector space and can be used for tasks like clustering or semantic search.
15
+
16
+
17
+
18
+ ## Usage (Sentence-Transformers)
19
+
20
+ Using this model becomes easy when you have [sentence-transformers](https://www.SBERT.net) installed:
21
+
22
+ ```
23
+ pip install -U sentence-transformers
24
+ ```
25
+
26
+ Then you can use the model like this:
27
+
28
+ ```python
29
+ from sentence_transformers import SentenceTransformer
30
+ sentences = ["This is an example sentence", "Each sentence is converted"]
31
+
32
+ model = SentenceTransformer('sentence-transformers/paraphrase-mpnet-base-v2')
33
+ embeddings = model.encode(sentences)
34
+ print(embeddings)
35
+ ```
36
+
37
+
38
+
39
+ ## Usage (HuggingFace Transformers)
40
+ Without [sentence-transformers](https://www.SBERT.net), you can use the model like this: First, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.
41
+
42
+ ```python
43
+ from transformers import AutoTokenizer, AutoModel
44
+ import torch
45
+
46
+
47
+ #Mean Pooling - Take attention mask into account for correct averaging
48
+ def mean_pooling(model_output, attention_mask):
49
+ token_embeddings = model_output[0] #First element of model_output contains all token embeddings
50
+ input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
51
+ return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
52
+
53
+
54
+ # Sentences we want sentence embeddings for
55
+ sentences = ['This is an example sentence', 'Each sentence is converted']
56
+
57
+ # Load model from HuggingFace Hub
58
+ tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/paraphrase-mpnet-base-v2')
59
+ model = AutoModel.from_pretrained('sentence-transformers/paraphrase-mpnet-base-v2')
60
+
61
+ # Tokenize sentences
62
+ encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
63
+
64
+ # Compute token embeddings
65
+ with torch.no_grad():
66
+ model_output = model(**encoded_input)
67
+
68
+ # Perform pooling. In this case, max pooling.
69
+ sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
70
+
71
+ print("Sentence embeddings:")
72
+ print(sentence_embeddings)
73
+ ```
74
+
75
+
76
+
77
+ ## Full Model Architecture
78
+ ```
79
+ SentenceTransformer(
80
+ (0): Transformer({'max_seq_length': 512, 'do_lower_case': False}) with Transformer model: MPNetModel
81
+ (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False})
82
+ )
83
+ ```
84
+
85
+ ## Citing & Authors
86
+
87
+ This model was trained by [sentence-transformers](https://www.sbert.net/).
88
+
89
+ If you find this model helpful, feel free to cite our publication [Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks](https://arxiv.org/abs/1908.10084):
90
+ ```bibtex
91
+ @inproceedings{reimers-2019-sentence-bert,
92
+ title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
93
+ author = "Reimers, Nils and Gurevych, Iryna",
94
+ booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
95
+ month = "11",
96
+ year = "2019",
97
+ publisher = "Association for Computational Linguistics",
98
+ url = "http://arxiv.org/abs/1908.10084",
99
+ }
100
+ ```
sentence_transformer/config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MPNetModel"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "bos_token_id": 0,
7
+ "eos_token_id": 2,
8
+ "hidden_act": "gelu",
9
+ "hidden_dropout_prob": 0.1,
10
+ "hidden_size": 768,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 3072,
13
+ "layer_norm_eps": 1e-05,
14
+ "max_position_embeddings": 514,
15
+ "model_type": "mpnet",
16
+ "num_attention_heads": 12,
17
+ "num_hidden_layers": 12,
18
+ "pad_token_id": 1,
19
+ "relative_attention_num_buckets": 32,
20
+ "torch_dtype": "float32",
21
+ "transformers_version": "4.53.2",
22
+ "vocab_size": 30527
23
+ }
sentence_transformer/config_sentence_transformers.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "sentence_transformers": "5.0.0",
4
+ "transformers": "4.53.2",
5
+ "pytorch": "2.6.0+cu124"
6
+ },
7
+ "model_type": "SentenceTransformer",
8
+ "prompts": {
9
+ "query": "",
10
+ "document": ""
11
+ },
12
+ "default_prompt_name": null,
13
+ "similarity_fn_name": "cosine"
14
+ }
sentence_transformer/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f839cf4fdde8eff477d7f56a42186948f5e236e0c5350b9b8685d7f810b8813
3
+ size 437967672
sentence_transformer/modules.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.models.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.models.Pooling"
13
+ }
14
+ ]
sentence_transformer/sentence_bert_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_seq_length": 512,
3
+ "do_lower_case": false
4
+ }
sentence_transformer/special_tokens_map.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "cls_token": {
10
+ "content": "<s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "eos_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "mask_token": {
24
+ "content": "<mask>",
25
+ "lstrip": true,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "pad_token": {
31
+ "content": "<pad>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "sep_token": {
38
+ "content": "</s>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ },
44
+ "unk_token": {
45
+ "content": "[UNK]",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false
50
+ }
51
+ }
sentence_transformer/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
sentence_transformer/tokenizer_config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<s>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<pad>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "104": {
28
+ "content": "[UNK]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "30526": {
36
+ "content": "<mask>",
37
+ "lstrip": true,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "bos_token": "<s>",
45
+ "clean_up_tokenization_spaces": false,
46
+ "cls_token": "<s>",
47
+ "do_basic_tokenize": true,
48
+ "do_lower_case": true,
49
+ "eos_token": "</s>",
50
+ "extra_special_tokens": {},
51
+ "mask_token": "<mask>",
52
+ "model_max_length": 512,
53
+ "never_split": null,
54
+ "pad_token": "<pad>",
55
+ "sep_token": "</s>",
56
+ "strip_accents": null,
57
+ "tokenize_chinese_chars": true,
58
+ "tokenizer_class": "MPNetTokenizer",
59
+ "unk_token": "[UNK]"
60
+ }
sentence_transformer/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
xgboost_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:233c8a7da7984cb92e09f82c8dd8502324eab077a1fbf30aa3028248639b7ff6
3
+ size 1447268