AI

A Coding Guide to Sentiment Analysis of Customer Reviews Using IBM’s Open Source AI Model Granite-3B and Hugging Face Transformers

In this tutorial, we will search how to easily make feelings analysis on text data using the 3B model of open -exported IBM granite model with embracing facial transformers. Feelings analysis, which is the normal language processing technique (NLP) widely used, rapidly identifies the emotions expressed in the text. It makes it invaluable for companies that aim to understand customer observations and enhance their products and services. Now, let’s walk for you by installing the necessary libraries, downloading the IBM Granite model, classifying feelings, and depicting your results, all of which are booked in Google Colab.

!pip install transformers torch accelerate

First, we will install the basic libraries – transformers, shape, and acceleration – required to download and operate the strong NLP models smoothly. Transformers provides pre -designed NLP models, Torch acts as the back interface for deep learning tasks, and ensures acceleration of effective resources on graphics processing units.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import pandas as pd
import matplotlib.pyplot as plt

Then, we will import the required Python libraries. We will use Torch for effective tensioners and transformers to download pre -trained NLP models from embracing face, pandas to manage and process data in organized formats, and MATPLOTLIB to explain the results of the analysis visually and intuitively.

model_id = "ibm-granite/granite-3.0-3b-a800m-instruct"


tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    device_map='auto',
    torch_dtype=torch.bfloat16,
    trust_remote_code=True
)


generator = pipeline("text-generation", model=model, tokenizer=tokenizer)

Here, we will download the IBM 3B IBM 3B Granite 3B, specifically IBM-Granite/Granite-3.0-3B-A800M-Instruct, using Autototenizer and Automodelforcausallm. This built -in model has been improved for the instructions to deal with tasks such as classifying feelings directly within the Colab, even in light of the limited mathematical resources.

def classify_sentiment(review):
    prompt = f"""Classify the sentiment of the following review as Positive, Negative, or Neutral.


Review: "{review}"


Sentiment:"""


    response = generator(
        prompt,
        max_new_tokens=5,
        do_sample=False,
        pad_token_id=tokenizer.eos_token_id
    )


    sentiment = response[0]['generated_text'].split("Sentiment:")[-1].split("n")[0].strip()
    return sentiment

Now we will determine the basic position Classify_Sentiment. This function works to take advantage of the IBM Granite 3B model through an instructor -based mentor to classify the feelings of any specific to positive, negative or neutral. The job coordinates the entry review, calls the model with accurate instructions, and extracts the feelings resulting from the created text.

import pandas as pd


reviews = [
    "I absolutely loved the service! Definitely coming back.",
    "The item arrived damaged, very disappointed.",
    "Average product. Nothing too exciting.",
    "Superb experience, exceeded all expectations!",
    "Not worth the money, poor quality."
]


reviews_df = pd.DataFrame(reviews, columns=['review'])

Next, we will create simple data reviews using Pandas, which contains a set of example reviews. These sample reviews act as entry for morale, which allows us to note how effective the IBM granite model that can determine the feelings of customers in a practical scenario.

reviews_df['sentiment'] = reviews_df['review'].apply(classify_sentiment)
print(reviews_df)

After selecting the reviews, we will apply the Classify_Sentiment function on each review in Dataframe. This will create a new column, the feeling, as the IBM granite model is classified as positive, negative or neutral. By printing updated reviews _DF, we can see the original text and classify the corresponding morale.

import matplotlib.pyplot as plt


sentiment_counts = reviews_df['sentiment'].value_counts()


plt.figure(figsize=(8, 6))
sentiment_counts.plot.pie(autopct="%1.1f%%", explode=[0.05]*len(sentiment_counts), colors=['#66bb6a', '#ff7043', '#42a5f5'])
plt.ylabel('')
plt.title('Sentiment Distribution of Reviews')
plt.show()

Finally, we will imagine the distribution of feelings in the pie. This step provides a clear and intuitive overview of how to classify reviews, which makes the interpretation of the total performance of the model easier. Matplotlib allows us to see the proportion of positive, negative and neutral feelings, which brings the circuit of your feelings analysis.

Plot

In conclusion, we have successfully implemented a strong pipeline to analyze feelings with an open source Granite 3B from IBM. I learned how to take advantage of pre -trained models to quickly classify the text into positive, negative or neutral feelings, visualize effective visions, and explain your results. This foundational approach allows you to easily adapt these skills to analyze data groups or explore other NLP tasks. IBM granite models with embraced facial transformers provide an effective way to perform advanced NLP tasks.


Here is Clap notebook. Also, do not forget to follow us twitter And join us Telegram channel and LinkedIn GrOup. Don’t forget to join 80k+ ml subreddit.

🚨 Recommended Reading- AI Nexus Research is published: an advanced system that combines AI system and data compliance standards to address legal concerns in artificial intelligence data groups


Asif Razzaq is the CEO of Marktechpost Media Inc .. As a pioneer and vision engineer, ASIF is committed to harnessing the potential of artificial intelligence for social goodness. His last endeavor is to launch the artificial intelligence platform, Marktechpost, which highlights its in -depth coverage of machine learning and deep learning news, which is technically sound and can be easily understood by a wide audience. The platform is proud of more than 2 million monthly views, which shows its popularity among the masses.

🚨 A platform recommended by Amnesty International Open Source: “Intelagent is an open source of action to evaluate AI Summary Conversation System” (promoted)

2025-03-07 04:51:00

Related Articles

Back to top button