Sentiment analysis
Sentiment Analysis is one of the most classic and widely applied tasks in the field of Natural Language Processing (NLP). It uses computational techniques to automatically identify, extract, and analyze subjective information in text, determining whether the author's attitude toward a specific topic, product, or service is positive, negative, or neutral.
Basic Types of Sentiment Analysis
Classification by Analysis Granularity
- Document-Level Sentiment Analysis: Judge the sentiment tendency of the entire document as a whole
- Sentence-Level Sentiment Analysis: Analyze the sentiment polarity of a single sentence
- Aspect-Level Sentiment Analysis: Make sentiment judgments about specific aspects mentioned in the text
Classification by Sentiment Dimension
- Binary Classification: Positive / Negative
- Three-Class Classification: Positive / Neutral / Negative
- Multi-Class Classification: Finer-grained sentiment classification (e.g., anger, happiness, sadness, etc.)
- Sentiment Intensity Analysis: Quantify the intensity of sentiment
Lexicon-Based Sentiment Analysis Methods
Lexicon-based methods are the most traditional sentiment analysis techniques, mainly relying on pre-built sentiment lexicons.
Core Components
-
Sentiment Dictionary: A collection of words with sentiment polarity and intensity
-
Intensity Regulator: Handles the influence of degree adverbs and negation words
Basic workflow
Example
Pseudocode example: dictionary-based sentiment analysis
def
lexicon_based_sentiment
(
text
)
:
sentiment_score
=
0
words
=
tokenize
(
text
)
Tokenization
for
word
in
words:
if
word
in
positive_lexicon:
sentiment_score +
=
positive_lexicon
[
word
]
elif
word
in
negative_lexicon:
sentiment_score -
=
negative_lexicon
[
word
]
Handle negation and degree modification
sentiment_score
=
apply_negation
(
words
,
sentiment_score
)
sentiment_score
=
apply_intensifier
(
words
,
sentiment_score
)
return
normalize
(
sentiment_score
)
Analysis of Pros and Cons
Advantages:
- No training data required
- High computational efficiency
- Strong interpretability
Disadvantages:
- Difficult to handle complex language phenomena (e.g., sarcasm, irony)
- Depends on the coverage and quality of the dictionary
- Cannot capture contextual semantics
Machine learning-based sentiment analysis methods
Machine learning methods perform sentiment analysis by learning patterns from labeled data.
Typical Feature Engineering
- Bag-of-Words model (BOW): Text represented as a vector of word occurrence frequencies
- TF-IDF: Considers the importance of words in a document
- N-gram Features: Captures local word sequence patterns
- Sentiment Dictionary Features: Combines the advantages of dictionary-based methods
Common algorithms

Code example: implementing sentiment classification with Scikit-learn
Example
from
sklearn.
feature_extraction
.
text
import
TfidfVectorizer
from
sklearn.
svm
import
LinearSVC
from
sklearn.
pipeline
import
Pipeline
Build a classification pipeline
sentiment_clf
=
Pipeline
(
[
(
'tfidf'
,
TfidfVectorizer
(
ngram_range
=
(
1
,
2
)
)
)
,
(
'clf'
,
LinearSVC
(
)
)
]
)
Train the model
sentiment_clf.
fit
(
train_texts
,
train_labels
)
Predict on new text
prediction
=
sentiment_clf.
predict
(
[
"This product is very easy to use, highly recommended!"
]
)
(
prediction
)
Output: 'positive'
Fine-grained Sentiment Analysis
Fine-grained sentiment analysis (Aspect-Based Sentiment Analysis, ABSA) is a more advanced sentiment analysis task that aims to identify specific aspects mentioned in text and their corresponding sentiments.
Core Subtasks of ABSA
-
Aspect Extraction: Identify entities or attributes discussed in the text
-
Sentiment Classification: Make sentiment judgments for each identified aspect
Comparison of Implementation Methods
| Method type | Representative models | Applicable scenarios | Advantages | Disadvantages |
|---|---|---|---|---|
| Pipeline Method | First extract aspects with CRF, then classify sentiment with a classifier | Resource-limited scenarios | Clear modules, easy to debug | Error propagation |
| End-to-end Method | BERT-ABSA, AOA-LSTM | High-precision requirements | Joint optimization, better performance | Requires more data |
| Multi-task learning | MT-DNN, Multi-Task BERT | Related task assistance | Knowledge sharing | Difficult task balancing |
Code example: BERT-based aspect-level sentiment analysis
Example
from
transformers
import
BertTokenizer
,
BertForSequenceClassification
import
torch
Load a pre-trained model
model
=
BertForSequenceClassification.
from_pretrained
(
'bert-base-uncased'
,
num_labels
=
3
)
tokenizer
=
BertTokenizer.
from_pretrained
(
'bert-base-uncased'
)
Prepare the input
text
=
"The restaurant's environment is great, but the service is too slow."
aspect
=
"service"
inputs
=
tokenizer
(
f
"[CLS] {aspect} [SEP] {text} [SEP]"
,
return_tensors
=
"pt"
)
Predict sentiment
outputs
=
model
(
**inputs
)
predictions
=
torch.
argmax
(
outputs.
logits
,
dim
=
1
)
(
predictions
)
Possible output: 1 (negative)
Challenges and Future Directions of Sentiment Analysis
Current Major Challenges
- Context Dependency: The same word may carry different sentiments in different contexts
- Domain Adaptation: Models trained in one domain degrade in performance in other domains
- Multilingual Processing: Sentiment expression varies greatly across languages
- Sarcasm and Irony Detection: Cases where surface text contradicts actual sentiment
Frontier Development Directions
- Multimodal Sentiment Analysis: Combines multiple information sources such as text, images, and speech
- Cross-lingual Sentiment Analysis: Leverages commonalities between languages to improve low-resource language performance
- Sentiment Cause Extraction: Not only judges sentiment but also analyzes its causes
- Personalized Sentiment Analysis: Considers the user's personal characteristics and historical behavior
Practical Exercise
Exercise 1: Build a Basic Sentiment Analyzer
- Implement a simple sentiment analyzer using NLTK's VADER dictionary
- Test its accuracy on a movie review dataset
Exercise 2: Compare Different Machine Learning Methods
- Train sentiment classifiers using Naive Bayes, SVM, and Logistic Regression respectively
- Use cross-validation to compare their performance differences
Exercise 3: Aspect-Level Sentiment Analysis Practice
- Fine-tune a pre-trained BERT model on the SemEval 2014 restaurant review dataset
- Implement an end-to-end system that can simultaneously extract aspects and judge sentiment
Through this article, you should have mastered the basic concepts, main methods, and implementation techniques of sentiment analysis. As a fundamental NLP task, sentiment analysis technology keeps evolving and has broad value in practical applications, from product review analysis to social media monitoring, where it plays an important role.