• bitcoinBitcoin(BTC)$84,608.000.62%
  • ethereumEthereum(ETH)$2,688.120.33%
  • tetherTether(USDT)$1.000.00%
  • binancecoinBNB(BNB)$777.820.93%
  • rippleXRP(XRP)$1.520.44%
  • usd-coinUSDC(USDC)$1.000.00%
  • solanaSolana(SOL)$122.881.76%
  • tronTRON(TRX)$0.333637-0.45%
  • zcashZcash(ZEC)$1,605.530.93%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.062.87%
  • HyperliquidHyperliquid(HYPE)$91.810.14%
  • dogecoinDogecoin(DOGE)$0.0971371.03%
  • chainlinkChainlink(LINK)$14.050.37%
  • moneroMonero(XMR)$547.57-0.85%
  • whitebitWhiteBIT Coin(WBT)$84.380.62%
  • USDSUSDS(USDS)$1.00-0.01%
  • cardanoCardano(ADA)$0.2556691.72%
  • RainRain(RAIN)$0.012566-2.22%
  • leo-tokenLEO Token(LEO)$9.050.71%
  • stellarStellar(XLM)$0.2166280.47%
  • nearNEAR Protocol(NEAR)$5.4814.18%
  • bitcoin-cashBitcoin Cash(BCH)$334.35-0.16%
  • uniswapUniswap(UNI)$9.722.12%
  • litecoinLitecoin(LTC)$71.26-0.33%
  • CantonCanton(CC)$0.1379533.16%
  • suiSui(SUI)$1.2711.11%
  • Ethena USDeEthena USDe(USDE)$1.000.02%
  • avalanche-2Avalanche(AVAX)$10.962.52%
  • daiDai(DAI)$1.000.00%
  • the-open-networkGram (prev. Toncoin)(GRAM)$1.633.89%
  • USD1USD1(USD1)$1.00-0.01%
  • hedera-hashgraphHedera(HBAR)$0.0948572.39%
  • BittensorBittensor(TAO)$326.233.42%
  • shiba-inuShiba Inu(SHIB)$0.0000060.50%
  • crypto-com-chainCronos(CRO)$0.0672582.19%
  • BitwayBitway(BTW)$1.2116.29%
  • Global DollarGlobal Dollar(USDG)$1.000.00%
  • quant-networkQuant(QNT)$198.9762.59%
  • EthenaEthena(ENA)$0.2801764.71%
  • paypal-usdPayPal USD(PYUSD)$1.000.00%
  • MemeCoreMemeCore(M)$1.19-1.78%
  • OndoOndo(ONDO)$0.553.75%
  • tether-goldTether Gold(XAUT)$4,278.49-0.03%
  • okbOKB(OKB)$121.450.89%
  • Ripple USDRipple USD(RLUSD)$1.000.01%
  • Circle USYCCircle USYC(USYC)$1.140.00%
  • aaveAave(AAVE)$154.57-0.02%
  • Pump.funPump.fun(PUMP)$0.00507917.56%
  • BlackRock USD Institutional Digital Liquidity FundBlackRock USD Institutional Digital Liquidity Fund(BUIDL)$1.000.00%
  • Ondo US Dollar YieldOndo US Dollar Yield(USDY)$1.150.16%
TradePoint.io
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop
No Result
View All Result
TradePoint.io
No Result
View All Result

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

March 7, 2025
in AI & Technology
Reading Time: 6 mins read
A A
A Coding Guide to Sentiment Analysis of Customer Reviews Using IBM’s Open Source AI Model Granite-3B and Hugging Face Transformers
ShareShareShareShareShare

In this tutorial, we will look into how to easily perform sentiment analysis on text data using IBM’s open-source Granite 3B model integrated with Hugging Face Transformers. Sentiment analysis, a widely-used natural language processing (NLP) technique, helps quickly identify the emotions expressed in text. It makes it invaluable for businesses aiming to understand customer feedback and enhance their products and services. Now, let’s walk you through installing the necessary libraries, loading the IBM Granite model, classifying sentiments, and visualizing your results, all effortlessly executable in Google Colab.

!pip install transformers torch accelerate

First, we’ll install the essential libraries—transformers, torch, and accelerate—required for loading and running powerful NLP models seamlessly. Transformers provides pre-built NLP models, torch serves as the backend for deep learning tasks, and accelerate ensures efficient resource utilization on GPUs.

YOU MAY ALSO LIKE

Bill Gates Says It’s ‘Completely Irresponsible’ For AI To Not Have Safeguards

Why The iPhone Duo Could Be Beneficial For Samsung’s Galaxy Z Fold 8

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

Then, we’ll import the required Python libraries. We’ll use torch for efficient tensor operations, transformers for loading pre-trained NLP models from Hugging Face, pandas for managing and processing data in structured formats, and matplotlib for visually interpreting your analysis results clearly 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’ll load IBM’s open-source Granite 3B instruction-following model, specifically ibm-granite/granite-3.0-3b-a800m-instruct, using Hugging Face’s AutoTokenizer and AutoModelForCausalLM. This compact, instruction-tuned model is optimized to handle tasks like sentiment classification directly within Colab, even under limited computational 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’ll define the core function classify_sentiment. This function leverages the IBM Granite 3B model through an instruction-based prompt to classify the sentiment of any given review into Positive, Negative, or Neutral. The function formats the input review, invokes the model with precise instructions, and extracts the resulting sentiment from the generated 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’ll create a simple DataFrame reviews_df using Pandas, containing a collection of example reviews. These sample reviews serve as input data for sentiment classification, enabling us to observe how effectively the IBM Granite model can determine customer sentiments in a practical scenario.

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

After defining the reviews, we’ll apply the classify_sentiment function to each review in the DataFrame. This will generate a new column, sentiment, where the IBM Granite model classifies each review as Positive, Negative, or Neutral. By printing the updated reviews_df, we can see the original text and its corresponding sentiment classification.

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()

Lastly, we’ll visualize the sentiment distribution in a pie chart. This step provides a clear, intuitive overview of how the reviews are classified, making interpreting the model’s overall performance easier. Matplotlib lets us quickly see the proportion of Positive, Negative, and Neutral sentiments, bringing your sentiment analysis pipeline full circle.

Plot

In conclusion, we have successfully implemented a powerful sentiment analysis pipeline using IBM’s Granite 3B open-source model hosted on Hugging Face. You learned how to leverage pre-trained models to quickly classify text into positive, negative, or neutral sentiments, visualize insights effectively, and interpret your findings. This foundational approach allows you to easily adapt these skills to analyze datasets or explore other NLP tasks. IBM’s Granite models combined with Hugging Face Transformers offer an efficient way to perform advanced NLP tasks.


Here is the Colab Notebook. Also, don’t forget to follow us on Twitter and join our Telegram Channel and LinkedIn Group. Don’t Forget to join our 80k+ ML SubReddit.

🚨 Recommended Read- LG AI Research Releases NEXUS: An Advanced System Integrating Agent AI System and Data Compliance Standards to Address Legal Concerns in AI Datasets


Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is committed to harnessing the potential of Artificial Intelligence for social good. His most recent endeavor is the launch of an Artificial Intelligence Media Platform, Marktechpost, which stands out for its in-depth coverage of machine learning and deep learning news that is both technically sound and easily understandable by a wide audience. The platform boasts of over 2 million monthly views, illustrating its popularity among audiences.

🚨 Recommended Open-Source AI Platform: ‘IntellAgent is a An Open-Source Multi-Agent Framework to Evaluate Complex Conversational AI System’ (Promoted)

Credit: Source link

ShareTweetSendSharePin

Related Posts

Bill Gates Says It’s ‘Completely Irresponsible’ For AI To Not Have Safeguards
AI & Technology

Bill Gates Says It’s ‘Completely Irresponsible’ For AI To Not Have Safeguards

September 27, 2026
Why The iPhone Duo Could Be Beneficial For Samsung’s Galaxy Z Fold 8
AI & Technology

Why The iPhone Duo Could Be Beneficial For Samsung’s Galaxy Z Fold 8

September 27, 2026
How To Improve Your Router’s Security In 10 Minutes
AI & Technology

How To Improve Your Router’s Security In 10 Minutes

September 27, 2026
Humanoid Robots Are Getting Even Creepier (This One Can Cry On Command)
AI & Technology

Humanoid Robots Are Getting Even Creepier (This One Can Cry On Command)

September 27, 2026
Next Post
Luigi Mangione makes first court appearance since arraignment in CEO murder case

Luigi Mangione makes first court appearance since arraignment in CEO murder case

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search

No Result
View All Result
US judge blocks deportation of DoorDash driver shot by ICE – bbc.com

US judge blocks deportation of DoorDash driver shot by ICE – bbc.com

September 22, 2026
‘America’s Bishop’ Was Beatified. 50,000 Catholics Showed Up. – The New York Times

‘America’s Bishop’ Was Beatified. 50,000 Catholics Showed Up. – The New York Times

September 25, 2026
How the U.S. government went from a balanced budget to  trillion in debt

How the U.S. government went from a balanced budget to $40 trillion in debt

September 25, 2026

About

Learn more

Our Services

Legal

Privacy Policy

Terms of Use

Bloggers

Learn more

Article Links

Contact

Advertise

Ask us anything

©2020- TradePoint.io - All rights reserved!

Tradepoint.io, being just a publishing and technology platform, is not a registered broker-dealer or investment adviser. So we do not provide investment advice. Rather, brokerage services are provided to clients of Tradepoint.io by independent SEC-registered broker-dealers and members of FINRA/SIPC. Every form of investing carries some risk and past performance is not a guarantee of future results. “Tradepoint.io“, “Instant Investing” and “My Trading Tools” are registered trademarks of Apperbuild, LLC.

This website is operated by Apperbuild, LLC. We have no link to any brokerage firm and we do not provide investment advice. Every information and resource we provide is solely for the education of our readers. © 2020 Apperbuild, LLC. All rights reserved.

No Result
View All Result
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop

© 2023 - TradePoint.io - All Rights Reserved!