Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Sentiment analysis

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

  1. Document-Level Sentiment Analysis: Judge the sentiment tendency of the entire document as a whole
  2. Sentence-Level Sentiment Analysis: Analyze the sentiment polarity of a single sentence
  3. Aspect-Level Sentiment Analysis: Make sentiment judgments about specific aspects mentioned in the text

Classification by Sentiment Dimension

  1. Binary Classification: Positive / Negative
  2. Three-Class Classification: Positive / Neutral / Negative
  3. Multi-Class Classification: Finer-grained sentiment classification (e.g., anger, happiness, sadness, etc.)
  4. 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

  1. Sentiment Dictionary: A collection of words with sentiment polarity and intensity

  2. Common English dictionaries: SentiWordNet, AFINN, VADER
  3. Common Chinese dictionaries: Hownet sentiment dictionary, Dalian University of Technology Sentiment Vocabulary Ontology
  4. - Common English dictionaries: SentiWordNet, AFINN, VADER - Common Chinese dictionaries: Hownet sentiment dictionary, Dalian University of Technology Sentiment Vocabulary Ontology
    1. Intensity Regulator: Handles the influence of degree adverbs and negation words

    2. Degree adverbs: very(1.5), quite(1.3), a bit(0.8), etc.
    3. Negation words: not, no, by no means, etc.
    4. - Degree adverbs: very(1.5), quite(1.3), a bit(0.8), etc. - Negation words: not, no, by no means, etc.

      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:

      Disadvantages:


      Machine learning-based sentiment analysis methods

      Machine learning methods perform sentiment analysis by learning patterns from labeled data.

      Typical Feature Engineering

      1. Bag-of-Words model (BOW): Text represented as a vector of word occurrence frequencies
      2. TF-IDF: Considers the importance of words in a document
      3. N-gram Features: Captures local word sequence patterns
      4. 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!"

      ]

      )

      print

      (

      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

      1. Aspect Extraction: Identify entities or attributes discussed in the text

      2. Explicit aspect: "The phone's battery life is great" → "battery"
      3. Implicit aspect: "The photos come out very clear" → "camera"
      4. - Explicit aspect: "The phone's battery life is great" → "battery" - Implicit aspect: "The photos come out very clear" → "camera"
        1. 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

        )

        print

        (

        predictions

        )

         

        Possible output: 1 (negative)


        Challenges and Future Directions of Sentiment Analysis

        Current Major Challenges

        1. Context Dependency: The same word may carry different sentiments in different contexts
        2. Domain Adaptation: Models trained in one domain degrade in performance in other domains
        3. Multilingual Processing: Sentiment expression varies greatly across languages
        4. Sarcasm and Irony Detection: Cases where surface text contradicts actual sentiment

        Frontier Development Directions

        1. Multimodal Sentiment Analysis: Combines multiple information sources such as text, images, and speech
        2. Cross-lingual Sentiment Analysis: Leverages commonalities between languages to improve low-resource language performance
        3. Sentiment Cause Extraction: Not only judges sentiment but also analyzes its causes
        4. Personalized Sentiment Analysis: Considers the user's personal characteristics and historical behavior

        Practical Exercise

        Exercise 1: Build a Basic Sentiment Analyzer

        1. Implement a simple sentiment analyzer using NLTK's VADER dictionary
        2. Test its accuracy on a movie review dataset

        Exercise 2: Compare Different Machine Learning Methods

        1. Train sentiment classifiers using Naive Bayes, SVM, and Logistic Regression respectively
        2. Use cross-validation to compare their performance differences

        Exercise 3: Aspect-Level Sentiment Analysis Practice

        1. Fine-tune a pre-trained BERT model on the SemEval 2014 restaurant review dataset
        2. 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.