def extract_aspects(text):
# Simple keyword-based aspect extraction or use SpaCy for more advanced extraction
aspects = ['battery', 'screen', 'performance'] # Example aspects
return [aspect for aspect in aspects if aspect in text.lower()]
def absa(text):
aspects = extract_aspects(text)
results = {}
for aspect in aspects:
sentiment = sentiment_pipeline(text)[0]
results[aspect] = sentiment
return results
Example usage
review = "The battery life of this phone is amazing, but the screen resolution is poor."
print(absa(review))
Assistant
Certainly! Below is a comprehensive Aspect-Based Sentiment Analysis (ABSA) implementation that leverages both SpaCy for advanced aspect extraction and Hugging Face's Transformers pipeline for sentiment analysis. This enhanced approach dynamically extracts aspects from the text instead of relying on a predefined list and associates sentiments accurately with each aspect.
Overview
Aspect Extraction: Uses SpaCy’s NLP capabilities to identify potential aspects in the text. This involves extracting noun chunks and filtering them based on part-of-speech tags to ensure relevance.
Sentiment Analysis: For each extracted aspect, the surrounding context is analyzed to determine the sentiment. This is achieved by extracting the sentence containing the aspect and applying the sentiment analysis pipeline to that specific sentence.
Aggregation: Compiles the sentiments associated with each aspect into a structured dictionary for easy interpretation.
Prerequisites
Before running the code, ensure that you have the necessary libraries installed. You can install them using pip:
import spacy
from transformers import pipeline
from collections import defaultdict
# Initialize SpaCy's English model
nlp = spacy.load("en_core_web_sm")
# Initialize Hugging Face's sentiment analysis pipeline
sentiment_pipeline = pipeline('sentiment-analysis')
def extract_aspects(text):
"""
Extract potential aspects from the text using SpaCy's NLP features.
Parameters:
text (str): The input text from which to extract aspects.
Returns:
set: A set of extracted aspect strings.
"""
doc = nlp(text)
aspects = set()
# Extract noun chunks as potential aspects
for chunk in doc.noun_chunks:
# Filter out pronouns and ensure the chunk is not too generic
if chunk.root.pos_ in {"NOUN", "PROPN"} and not chunk.text.lower() in {"it", "this", "that"}:
aspects.add(chunk.text.lower())
return aspects
def get_sentences_with_aspect(doc, aspect):
"""
Retrieve all sentences from the doc that contain the given aspect.
Parameters:
doc (spacy.tokens.Doc): The SpaCy parsed document.
aspect (str): The aspect to search for within the sentences.
Returns:
list: A list of sentence strings containing the aspect.
"""
sentences = []
for sent in doc.sents:
if aspect in sent.text.lower():
sentences.append(sent.text)
return sentences
def analyze_sentiment(sentences):
"""
Analyze the sentiment of a list of sentences.
Parameters:
sentences (list): List of sentence strings to analyze.
Returns:
dict: Aggregated sentiment results.
"""
sentiments = defaultdict(float) # Initialize with float for weighted sentiment aggregation
for sentence in sentences:
result = sentiment_pipeline(sentence)[0]
# Assign scores based on sentiment label
if result['label'] == 'POSITIVE':
score = result['score']
sentiments['POSITIVE'] += score
elif result['label'] == 'NEGATIVE':
score = result['score']
sentiments['NEGATIVE'] += score
# Determine the overall sentiment for the aspect
if sentiments['POSITIVE'] > sentiments['NEGATIVE']:
overall_sentiment = ('POSITIVE', sentiments['POSITIVE'])
elif sentiments['NEGATIVE'] > sentiments['POSITIVE']:
overall_sentiment = ('NEGATIVE', sentiments['NEGATIVE'])
else:
overall_sentiment = ('NEUTRAL', 0.0)
return overall_sentiment
def absa(text):
"""
Perform Aspect-Based Sentiment Analysis on the input text.
Parameters:
text (str): The input review or text to analyze.
Returns:
dict: A dictionary mapping each aspect to its sentiment.
"""
doc = nlp(text)
aspects = extract_aspects(text)
results = {}
for aspect in aspects:
sentences = get_sentences_with_aspect(doc, aspect)
sentiment, score = analyze_sentiment(sentences)
results[aspect] = {'sentiment': sentiment, 'score': round(score, 4)}
return results
# Example usage
if __name__ == "__main__":
review = "The battery life of this phone is amazing, but the screen resolution is poor. " \
"I love the performance, although the camera quality could be better. " \
"The design is sleek and the user interface is intuitive."
absa_results = absa(review)
for aspect, sentiment_info in absa_results.items():
print(f"Aspect: {aspect.capitalize()}, Sentiment: {sentiment_info['sentiment']} (Score: {sentiment_info['score']})")
Explanation of the Components
Aspect Extraction (extract_aspects Function):
Noun Chunks: These are continuous sequences of tokens that have a noun as their head. Noun chunks are a good source of potential aspects.
Filtering: The function filters out pronouns and overly generic terms to focus on meaningful aspects like "battery life" or "screen resolution".
For each aspect, the function retrieves all sentences from the text that mention the aspect. This localized context helps in accurately determining the sentiment associated with that aspect.
Sentiment Analysis (analyze_sentiment Function):
Processing Sentences: Each sentence containing the aspect is analyzed for sentiment.
Aggregation: The sentiments of individual sentences are aggregated to determine the overall sentiment for the aspect. Scores are used to handle cases where multiple sentiments are expressed about the same aspect.
ABSA Pipeline (absa Function):
Combines aspect extraction and sentiment analysis to produce a final dictionary mapping each aspect to its sentiment and corresponding confidence score.
Sample Output
When you run the provided code with the example review, you might get an output similar to the following:
Handling Multi-word Aspects: The current implementation effectively handles multi-word aspects (e.g., "battery life"). However, depending on the complexity of the text, more sophisticated techniques like dependency parsing or phrase matching can be incorporated for improved accuracy.
Neutral Sentiments: If an aspect does not have a clearly positive or negative sentiment, it is marked as "NEUTRAL". Depending on your use case, you might want to handle neutral sentiments differently or refine the conditions under which sentiments are classified.
Performance Optimization: For larger texts, consider optimizing the sentiment analysis step by minimizing repeated sentiment evaluations or leveraging parallel processing.
Advanced Sentiment Models: The sentiment-analysis pipeline uses a general-purpose sentiment model. For more nuanced sentiment detection, especially in complex domains, you might want to fine-tune a model specifically for your dataset or domain.
Aspect Relevance Filtering: Depending on the application, you may want to implement additional filtering to ensure that only relevant aspects are considered (e.g., based on a predefined ontology or relevance scores).
Extending Aspect Extraction: While noun chunks are a good starting point, incorporating other linguistic features such as adjectives, verbs, or even using machine learning-based aspect extraction models can enhance the extraction process.
Conclusion
This implementation provides a robust foundation for Aspect-Based Sentiment Analysis by combining the linguistic strengths of SpaCy with the powerful sentiment analysis capabilities of Hugging Face's Transformers. Depending on your specific requirements and dataset, you can further refine and extend this approach to achieve even better results.