Code Explanation:
Step 1: Importing the pipeline from transformers
from transformers import pipeline
The pipeline function from the transformers library simplifies access to various pre-trained models.
Here, it's used for sentiment analysis.
Step 2: Creating a Sentiment Analysis Pipeline
classifier = pipeline("sentiment-analysis")
This automatically loads a pre-trained model for sentiment analysis.
By default, it uses distilbert-base-uncased-finetuned-sst-2-english, a model trained on the Stanford Sentiment Treebank (SST-2) dataset.
The model classifies text into positive or negative sentiment.
Step 3: Running Sentiment Analysis on a Given Text
result = classifier("I love AI and Python!")
The classifier analyzes the input "I love AI and Python!" and returns a list of dictionaries containing:
label: The predicted sentiment (POSITIVE or NEGATIVE).
score: The confidence score of the prediction (between 0 and 1).
Example output:
[{'label': 'POSITIVE', 'score': 0.9998}]
Here, the model predicts POSITIVE sentiment with a high confidence score.
Step 4: Extracting and Printing the Sentiment Label
print(result[0]['label'])
Since result is a list with a single dictionary, result[0] gives:
{'label': 'POSITIVE', 'score': 0.9998}
result[0]['label'] extracts the sentiment label, which is "POSITIVE".
Final Output:
POSITIVE
0 Comments:
Post a Comment