Views
No views yet
Input Text → SentenceTransformer → Embeddings (768D) →
Feature Engineering (Length + Sentiment + POS) → XGBoost → Prediction1import pickle
2import numpy as np
3from sentence_transformers import SentenceTransformer
4from textblob import TextBlob
5import nltk
6from huggingface_hub import hf_hub_download
7
8# Download NLTK data
9nltk.download('punkt', quiet=True)
10nltk.download('averaged_perceptron_tagger', quiet=True)
11
12# Load models
13xgb_path = hf_hub_download(repo_id="USERNAME/sentimental_analysis_updated", filename="xgboost_model.pkl")
14sentence_path = hf_hub_download(repo_id="USERNAME/sentimental_analysis_updated", filename="sentence_transformer")
15
16# Load XGBoost model
17with open(xgb_path, 'rb') as f:
18 pipeline_data = pickle.load(f)
19 xgb_model = pipeline_data['xgboost_model']
20 label_names = pipeline_data['label_names']
21
22# Load SentenceTransformer
23sentence_model = SentenceTransformer(sentence_path)
24
25def predict_sentiment(text):
26 # Extract features
27 embedding = sentence_model.encode([text])
28 comment_length = np.array([len(text.split())]).reshape(-1, 1)
29 sentiment_polarity = np.array([TextBlob(text).sentiment.polarity]).reshape(-1, 1)
30
31 # POS counts
32 try:
33 tags = nltk.pos_tag(nltk.word_tokenize(text))
34 pos_counts = np.array([[
35 sum(1 for _, tag in tags if tag.startswith('J')), # Adjectives
36 sum(1 for _, tag in tags if tag.startswith('N')), # Nouns
37 sum(1 for _, tag in tags if tag.startswith('V')) # Verbs
38 ]])
39 except:
40 pos_counts = np.array([[0, 0, 0]])
41
42 # Combine features
43 features = np.hstack([embedding, comment_length, sentiment_polarity, pos_counts])
44
45 # Predict
46 prediction = xgb_model.predict(features)[0]
47 confidence = xgb_model.predict_proba(features)[0].max()
48
49 return {
50 'label': label_names[prediction],
51 'confidence': confidence,
52 'prediction_id': int(prediction)
53 }
54
55# Example usage
56result = predict_sentiment("I love this new phone! It's amazing!")
57print(f"Sentiment: {result['label']} (confidence: {result['confidence']:.3f})")paraphrase-mpnet-base-v21@misc{reddit-sentiment-hybrid,
2 title={Reddit Sentiment Analysis - Hybrid Model},
3 year={2025},
4 publisher={Hugging Face},
5 url={https://huggingface.co/USERNAME/sentimental_analysis_updated}
6}