The Wayback Machine - https://web.archive.org/web/20241121212915/https://www.geeksforgeeks.org/sentiment-analysis-using-fuzzy-logic/
Open In App

Sentiment Analysis using Fuzzy Logic

Last Updated : 02 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Sentiment analysis, also known as opinion mining, is a crucial area of natural language processing (NLP) that involves determining the sentiment expressed in a piece of text. This sentiment can be positive, negative, or neutral. Traditional sentiment analysis methods often rely on machine learning techniques, which require large datasets and extensive training. However, an alternative approach using fuzzy logic can offer a more intuitive and flexible way to handle the inherent uncertainty and vagueness in human language.

In the article, we are going to explore why and how we can use fuzzy logic for sentiment analysis.

What is Fuzzy Logic?

Fuzzy logic, introduced by Lotfi Zadeh in 1965, extends classical logic to handle the concept of partial truth — truth values between "completely true" and "completely false." This is particularly useful in dealing with real-world scenarios where binary true/false values are insufficient to represent the complexity of human reasoning.

In the context of sentiment analysis, fuzzy logic allows us to assign degrees of positivity or negativity to words and phrases, reflecting the subtleties of human emotions and opinions more effectively than traditional binary classifications.

Why Use Fuzzy Logic for Sentiment Analysis?

  1. Handling Ambiguity: Fuzzy logic can manage the ambiguity and imprecision inherent in natural language, where words can have different connotations depending on the context.
  2. Linguistic Variables: It uses linguistic variables (e.g., "good," "bad," "average") instead of numerical values, making the system more interpretable.
  3. Rule-Based Approach: Fuzzy logic employs a rule-based approach, allowing for the incorporation of expert knowledge and heuristic rules into the sentiment analysis process.

Components of a Fuzzy Logic System

A fuzzy logic system for sentiment analysis typically consists of the following components:

  1. Fuzzification: Converting input data (text) into fuzzy sets. Words and phrases are mapped to degrees of sentiment (e.g., "happy" might be 0.8 positive, 0.1 negative).
  2. Fuzzy Rules: A set of if-then rules that define how different inputs relate to the sentiment output. For example, "IF the word is 'happy' THEN the sentiment is positive."
  3. Inference Engine: Applies the fuzzy rules to the fuzzified inputs to generate fuzzy outputs.
  4. Defuzzification: Converts the fuzzy output back into a crisp value, such as a sentiment score.

Implementing Fuzzy Logic for Sentiment Analysis

Step 1: Import Necessary Libraries

We start by importing the necessary libraries for handling data, preprocessing text, performing sentiment analysis, and working with fuzzy logic.

import pandas as pd
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from textblob import TextBlob
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, classification_report

# Download necessary NLTK data files
nltk.download('stopwords')
nltk.download('punkt')

Step 2: Define Preprocessing Function

This step involves defining a function to preprocess the text data. The function converts text to lowercase, tokenizes it, and removes stopwords.

# Preprocessing function
def preprocess(text):
text = text.lower()
words = word_tokenize(text)
words = [word for word in words if word not in stopwords.words('english')]
return ' '.join(words)

Step 3: Load and Preprocess Dataset

Load the dataset from a CSV file, then preprocess the text data using the defined function.

# Load dataset
df = pd.read_csv('/content/sentiment_analysis.csv')

# Preprocess texts
df['processed_text'] = df['text'].apply(preprocess)

Step 4: Obtain Sentiment Polarity Scores with TextBlob

Use TextBlob to compute initial sentiment polarity scores for the preprocessed text.

# Use TextBlob to obtain initial sentiment polarity scores
df['textblob_polarity'] = df['processed_text'].apply(lambda text: TextBlob(text).sentiment.polarity)

Step 5: Define Fuzzy Variables

Define fuzzy variables for polarity and sentiment with their respective ranges and membership functions.

# Define fuzzy variables
polarity = ctrl.Antecedent(np.arange(-1, 1.1, 0.1), 'polarity')
sentiment = ctrl.Consequent(np.arange(0, 1.1, 0.1), 'sentiment')

# Membership functions for polarity
polarity['negative'] = fuzz.trimf(polarity.universe, [-1, -1, 0])
polarity['neutral'] = fuzz.trimf(polarity.universe, [-0.5, 0, 0.5])
polarity['positive'] = fuzz.trimf(polarity.universe, [0, 1, 1])

# Membership functions for sentiment
sentiment['negative'] = fuzz.trimf(sentiment.universe, [0, 0, 0.3])
sentiment['neutral'] = fuzz.trimf(sentiment.universe, [0.2, 0.5, 0.7])
sentiment['positive'] = fuzz.trimf(sentiment.universe, [0.5, 1, 1])

Step 6: Define Fuzzy Rules

Define the fuzzy logic rules to map the polarity to the corresponding sentiment.

# Fuzzy rules
rule1 = ctrl.Rule(polarity['positive'], sentiment['positive'])
rule2 = ctrl.Rule(polarity['negative'], sentiment['negative'])
rule3 = ctrl.Rule(polarity['neutral'], sentiment['neutral'])

Step 7: Create and Simulate Fuzzy Control System

Create a fuzzy control system and simulate it to evaluate the sentiment based on the polarity scores.

# Control system
sentiment_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
sentiment_sim = ctrl.ControlSystemSimulation(sentiment_ctrl)

# Evaluate sentiment using fuzzy logic
fuzzy_sentiments = []
for polarity_score in df['textblob_polarity']:
sentiment_sim.input['polarity'] = polarity_score
try:
sentiment_sim.compute()
fuzzy_sentiments.append(sentiment_sim.output['sentiment'])
except:
fuzzy_sentiments.append(np.nan) # Assign NaN if computation fails

df['fuzzy_sentiment_score'] = fuzzy_sentiments

Step 8: Handle Missing Values and Map Sentiment Scores

Handle cases where sentiment computation fails by assigning a neutral score. Then map the fuzzy sentiment score to sentiment labels.

# Handle cases where sentiment could not be computed
df['fuzzy_sentiment_score'].fillna(0.5, inplace=True) # Assign a neutral score if NaN

# Map the fuzzy sentiment score to sentiment labels
def map_sentiment(score):
if score <= 0.4:
return 'negative'
elif score >= 0.6:
return 'positive'
else:
return 'neutral'

df['fuzzy_sentiment'] = df['fuzzy_sentiment_score'].apply(map_sentiment)

Step 9: Evaluate and Visualize the Results

Evaluate the performance of the fuzzy sentiment classification using a classification report and visualize the membership functions.

# Evaluate the model
report = classification_report(df['sentiment'], df['fuzzy_sentiment'], target_names=['negative', 'neutral', 'positive'])
print(report)

# Visualize the membership functions
polarity.view()
sentiment.view()

By following these steps, you can implement a fuzzy logic-based sentiment analysis system that processes text data, evaluates sentiment polarity using TextBlob, and refines the sentiment classification using a fuzzy control system.

Complete Code

Python
import pandas as pd
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from textblob import TextBlob
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, classification_report


nltk.download('stopwords')
nltk.download('punkt')


def preprocess(text):
    text = text.lower()
    words = word_tokenize(text)
    words = [word for word in words if word not in stopwords.words('english')]
    return ' '.join(words)


df = pd.read_csv('/content/sentiment_analysis.csv')


df['processed_text'] = df['text'].apply(preprocess)


df['textblob_polarity'] = df['processed_text'].apply(lambda text: TextBlob(text).sentiment.polarity)


polarity = ctrl.Antecedent(np.arange(-1, 1.1, 0.1), 'polarity')
sentiment = ctrl.Consequent(np.arange(0, 1.1, 0.1), 'sentiment')


polarity['negative'] = fuzz.trimf(polarity.universe, [-1, -1, 0])
polarity['neutral'] = fuzz.trimf(polarity.universe, [-0.5, 0, 0.5])
polarity['positive'] = fuzz.trimf(polarity.universe, [0, 1, 1])

sentiment['negative'] = fuzz.trimf(sentiment.universe, [0, 0, 0.3])
sentiment['neutral'] = fuzz.trimf(sentiment.universe, [0.2, 0.5, 0.7])
sentiment['positive'] = fuzz.trimf(sentiment.universe, [0.5, 1, 1])

rule1 = ctrl.Rule(polarity['positive'], sentiment['positive'])
rule2 = ctrl.Rule(polarity['negative'], sentiment['negative'])
rule3 = ctrl.Rule(polarity['neutral'], sentiment['neutral'])

sentiment_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
sentiment_sim = ctrl.ControlSystemSimulation(sentiment_ctrl)

fuzzy_sentiments = []
for polarity_score in df['textblob_polarity']:
    sentiment_sim.input['polarity'] = polarity_score
    try:
        sentiment_sim.compute()
        fuzzy_sentiments.append(sentiment_sim.output['sentiment'])
    except:
        fuzzy_sentiments.append(np.nan)  

df['fuzzy_sentiment_score'] = fuzzy_sentiments


df['fuzzy_sentiment_score'].fillna(0.5, inplace=True)

def map_sentiment(score):
    if score <= 0.4:
        return 'negative'
    elif score >= 0.6:
        return 'positive'
    else:
        return 'neutral'

df['fuzzy_sentiment'] = df['fuzzy_sentiment_score'].apply(map_sentiment)

report = classification_report(df['sentiment'], df['fuzzy_sentiment'], target_names=['negative', 'neutral', 'positive'])
print(report)
polarity.view()
sentiment.view()

Output:

               precision    recall  f1-score   support

negative 0.77 0.33 0.46 134
neutral 0.55 0.84 0.66 200
positive 0.75 0.62 0.68 165

accuracy 0.63 499
macro avg 0.69 0.60 0.60 499
weighted avg 0.68 0.63 0.61 499
polarity
Triangular Membership function of variable Polarity


sentiment
Triangular Membership function of variable Sentiment


As we can see the dip in recall of negative sentiments is due to imbalanced dataset. The 63% accuracy can be regarded as good in sentiment analysis because texts can be of different sentiments.

Advantages and Challenges

Advantages

  • Interpretability: The use of linguistic variables and rules makes the system more understandable to humans.
  • Flexibility: Easily incorporates new rules and adjusts existing ones based on expert knowledge or new data.
  • Robustness: Handles uncertainty and partial truths effectively, providing more nuanced sentiment analysis.

Challenges

  • Rule Definition: Creating a comprehensive set of rules can be time-consuming and requires domain expertise.
  • Scalability: Fuzzy logic systems may become complex and harder to manage as the number of rules increases.
  • Subjectivity: Assigning sentiment scores and defining rules can be subjective and vary among different individuals.

Conclusion

Fuzzy logic offers a powerful and flexible approach to sentiment analysis, addressing some of the limitations of traditional machine learning methods. By leveraging the ability to handle uncertainty and vagueness, fuzzy logic can provide more nuanced and interpretable sentiment analysis, making it a valuable tool for understanding human emotions and opinions expressed in text. As AI and NLP technologies continue to evolve, integrating fuzzy logic into sentiment analysis systems could enhance their effectiveness and broaden their application in various fields.


Previous Article
Next Article

Similar Reads

Difference between Neural Network And Fuzzy Logic
Neural Network: Neural network is an information processing system that is inspired by the way biological nervous systems such as brain process information. A neural network is composed of a large number of interconnected processing elements known as neurons which are used to solve problems. A neural network is an attempt to make a computer model o
2 min read
Fuzzy Logic Control System
Introduction: Fuzzy logic control (FLC) is the most active research area in the application of fuzzy set theory, fuzzy reasoning, and fuzzy logic. The application of FLC extends from industrial process control to biomedical instrumentation and securities. Compared to conventional control techniques, FLC has been best utilized in complex ill-defined
7 min read
Fuzzy Logic and Probability : The Confusing Terms
Often through reading many articles and blogs on Data Science there are a few terms that we all come across and don’t actually get a clear understanding of the same. Moreover, by looking at the basic overview of the terms it often happens that in a few couples of days we come across the same terms again. So, it is necessary that we understand its d
4 min read
Fuzzy Logic applications in AI
Fuzzy logic, a concept introduced by Lotfi Zadeh in the 1960s, extends classical logic to handle the concept of partial truth, where truth values range between completely true and completely false. This approach is especially useful in dealing with uncertainty and vagueness in complex systems. Fuzzy logic has found numerous applications in artifici
8 min read
Fuzzy Logic for Uncertainty Management in Machine Learning
Uncertainty in machine learning refers to the inherent unpredictability in model predictions due to factors like data variability and model limitations. Fuzzy logic is a mathematical framework used to handle imprecise and uncertain information by allowing partial truth values between completely true and completely false. Managing uncertainty in mac
7 min read
Facebook Sentiment Analysis using python
This article is a Facebook sentiment analysis using Vader, nowadays many government institutions and companies need to know their customers' feedback and comment on social media such as Facebook. What is sentiment analysis? Sentiment analysis is one of the best modern branches of machine learning, which is mainly used to analyze the data in order t
6 min read
Twitter Sentiment Analysis on Russia-Ukraine War Using Python
In this article, we are going to see how we can perform the Twitter sentiment analysis on the Russia-Ukraine War using Python. Twitter Sentiment Analysis on Russia-Ukraine WarThe role of social media in public opinion has been profound and evident since it started gaining attention. Social media allows us to share information in a great capacity an
9 min read
Sentiment Analysis using CatBoost
Sentiment analysis is crucial for understanding the emotional tone behind text data, making it invaluable for applications such as customer feedback analysis, social media monitoring, and market research. In this article, we will explore how to perform sentiment analysis using CatBoost. Table of Content Key Features of CatBoost Why use to CatBoost
4 min read
Sentiment Analysis in Ancient Texts Using NLP Techniques.
Natural language processing (NLP) has undergone significant advancements in recent years, with applications ranging from chatbots to language translation. One intriguing application is sentiment analysis, where the goal is to determine the emotional tone behind a body of text. While this is relatively straightforward with contemporary texts, applyi
5 min read
Sentiment Analysis using HuggingFace's RoBERTa Model
Sentiment analysis determines the sentiment or emotion behind a piece of text. It's widely used to analyze customer reviews, social media posts, and other forms of textual data to understand public opinion and trends. In this article, we are going to implement sentiment analysis using RoBERTa model. Overview of HuggingFace and TransformersHuggingFa
4 min read
Amazon Product Review Sentiment Analysis using RNN
In this article, we will learn how to use Recurrent Neural Networks for Sentiment Analysis. We will use the Product Reviews dataset which has around 25000 customer reviews. Our end goal will be to give a rating according to the review given. Sentiment Analysis using RNNSentiment Analysis is the process of extracting information from the texts. It i
9 min read
Sentiment Analysis Using 'quanteda' in R
Sentiment analysis is the technique used to determine the sentiment expressed in the piece of text, classifying it as positive, negative, or neutral. In R, the quanteda package is the robust tool for text processing. While sentimentr can be used for sentiment analysis. This article will guide you through the steps to perform the sentiment analysis
5 min read
Flipkart Reviews Sentiment Analysis using Python
This article is based on the analysis of the reviews and ratings user gives on Flipkart to make others aware of their experience and moreover about the quality of the product and brand. So, by analyzing that data we can tell the users a lot about the products and also the ways to enhance the quality of the product.  Today we will be using Machine L
5 min read
Aspect Modelling in Sentiment Analysis
Prerequisite: Sentiment Analysis Before getting into the specifics of Aspect Modelling, let us first briefly understand what Sentiment Analysis is with a real-life example. Sentiment Analysis (SA): It is a technique to distinguish a person's feeling towards something or someone based on a piece of text they have written about it. It could be positi
3 min read
Sentiment Analysis of Hindi Text - Python
Sentiment Analysis for Indic Language: This article exhibits how to use the library VADER for doing the sentiment analysis of the Indic Language'Hindi'. Sentiment analysis is a metric that conveys how positive or negative or neutral the text or data is. It is performed on textual data to help businesses monitor brand and product sentiment in custom
3 min read
Sentiment Analysis of YouTube Comments
YouTube has become a significant platform for communication and expression, where people from all over the world can share their thoughts and opinions on various videos. These comments can provide a deep insight into what the viewer perceives and their feedback on the content. This allows content creators to understand the responses of viewers and
13 min read
What is Sentiment Analysis?
Sentiment analysis is a popular task in natural language processing. The goal of sentiment analysis is to classify the text based on the mood or mentality expressed in the text, which can be positive negative, or neutral. What is Sentiment Analysis?Sentiment analysis is the process of classifying whether a block of text is positive, negative, or ne
11 min read
How to use PyTorch for sentiment analysis on textual data?
Sentiment Analysis is a natural language processing (NLP) task that involves identifying the emotion present in a given text. The amount of textual data on social media, consumer reviews, and other platforms is increasing, making sentiment analysis more and more crucial. In this article, we present a step-by-step guide to performing sentiment analy
8 min read
Dataset for Sentiment Analysis
Sentiment analysis, which helps understand how people feel and what they think, is very important in studying public opinions, customer thoughts, and social media buzz. But to make sentiment analysis work well, we need good datasets to train and test our systems. In this article, we will look at some of the popular datasets used for sentiment analy
8 min read
Fine-tuning BERT model for Sentiment Analysis
Google created a transformer-based machine learning approach for natural language processing pre-training called Bidirectional Encoder Representations from Transformers. It has a huge number of parameters, hence training it on a small dataset would lead to overfitting. This is why we use a pre-trained BERT model that has been trained on a huge data
6 min read
Sentiment Analysis for Customer Reviews in R
In today's digital age, businesses thrive or perish based on their ability to understand and respond to customer sentiment. Customer reviews on platforms such as Amazon, Yelp, or TripAdvisor provide a treasure trove of data, offering insights into consumer opinions, preferences, and satisfaction levels. Sentiment analysis, a branch of natural langu
13 min read
Amazon Product Reviews Sentiment Analysis in Python
Amazon gives a platform to small businesses and companies with modest resources to grow larger. And Because of its popularity, people actually spend time and write detailed reviews, about the brand and the product. So, by analyzing that data we can tell companies a lot about their products and also the ways to enhance the quality of the product. Bu
4 min read
Sentiment Analysis of Restaurant Reviews - Machine Learning Project
Online reviews are essential in our decision-making process for choosing where to eat, what to buy, and which services to use. But how do businesses interpret the significance of these reviews for their service quality? That's where sentiment analysis comes in. This article provides an overview of sentiment analysis, common terms, and how Natural L
6 min read
NLP Sentiment Analysis for US Election
Natural Language Processing is a subfield of Artificial Intelligence that enables computers to understand, analyze, and manipulate human language. This article discusses the prediction of U.S. election results based on Sentiment Analysis using tweets. What is Sentiment Analysis?Sentiment analysis is a technique through which we can examine a text t
15+ min read
How to Use the Hugging Face Transformer Library for Sentiment Analysis
The Hugging Face Transformer library is now a popular choice for developers working on Natural Language Processing (NLP) projects. It simplifies access to a range of pretrained models like BERT, GPT, and RoBERTa, making it easier for developers to utilize advanced models without extensive knowledge in deep learning. The Transformer library enables
5 min read
Image Segmentation Using Fuzzy C-Means Clustering
This article delves into the process of image segmentation using Fuzzy C-Means (FCM) clustering, a powerful technique for partitioning images into meaningful regions. We'll explore the fundamentals of FCM, its advantages over traditional methods, and provide a step-by-step guide to implementing FCM for image segmentation using Python. By the end of
7 min read
ML | Fuzzy Clustering
Prerequisite: Clustering in Machine Learning Clustering is an unsupervised machine learning technique that divides the given data into different clusters based on their distances (similarity) from each other. The unsupervised k-means clustering algorithm gives the values of any point lying in some particular cluster to be either as 0 or 1 i.e., eit
6 min read
Fuzzy Clustering in R
Clustering is an unsupervised machine-learning technique that is used to identify similarities and patterns within data points by grouping similar points based on their features. These points can belong to different clusters simultaneously. This method is widely used in various fields such as Customer Segmentation, Recommendation Systems, Document
15+ min read
Fuzzy Optimization Techniques: An Overview
Fuzzy optimization techniques have been useful in the field of optimization, where decision-making processes are often complicated and tainted by uncertainty. These methods tackle vagueness and ambiguity by utilizing fuzzy logic concepts, which makes them applicable to a variety of fields like economics, engineering, healthcare, and environmental m
4 min read
Sentiment Classification Using BERT
BERT stands for Bidirectional Representation for Transformers and was proposed by researchers at Google AI language in 2018. Although the main aim of that was to improve the understanding of the meaning of queries related to Google Search, BERT becomes one of the most important and complete architectures for various natural language tasks having ge
13 min read
three90RightbarBannerImg