• bitcoinBitcoin(BTC)$78,324.002.13%
  • ethereumEthereum(ETH)$2,311.382.45%
  • tetherTether(USDT)$1.000.03%
  • binancecoinBNB(BNB)$703.821.63%
  • rippleXRP(XRP)$1.282.01%
  • usd-coinUSDC(USDC)$1.000.02%
  • solanaSolana(SOL)$93.191.34%
  • tronTRON(TRX)$0.3220070.37%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.03-0.22%
  • zcashZcash(ZEC)$1,292.7313.70%
  • HyperliquidHyperliquid(HYPE)$85.802.74%
  • moneroMonero(XMR)$637.531.93%
  • dogecoinDogecoin(DOGE)$0.0751331.64%
  • USDSUSDS(USDS)$1.000.03%
  • whitebitWhiteBIT Coin(WBT)$75.342.14%
  • chainlinkChainlink(LINK)$11.180.67%
  • leo-tokenLEO Token(LEO)$9.310.24%
  • cardanoCardano(ADA)$0.1914282.35%
  • stellarStellar(XLM)$0.1639411.46%
  • bitcoin-cashBitcoin Cash(BCH)$276.850.58%
  • nearNEAR Protocol(NEAR)$4.037.08%
  • uniswapUniswap(UNI)$7.486.26%
  • daiDai(DAI)$1.000.04%
  • Ethena USDeEthena USDe(USDE)$1.000.10%
  • RainRain(RAIN)$0.006226-2.32%
  • litecoinLitecoin(LTC)$54.651.68%
  • CantonCanton(CC)$0.0991605.80%
  • avalanche-2Avalanche(AVAX)$8.633.45%
  • USD1USD1(USD1)$1.000.06%
  • suiSui(SUI)$0.915.23%
  • the-open-networkGram (prev. Toncoin)(GRAM)$1.181.23%
  • tether-goldTether Gold(XAUT)$4,017.793.08%
  • hedera-hashgraphHedera(HBAR)$0.0704781.72%
  • quant-networkQuant(QNT)$194.390.15%
  • Global DollarGlobal Dollar(USDG)$1.000.03%
  • shiba-inuShiba Inu(SHIB)$0.0000053.11%
  • paypal-usdPayPal USD(PYUSD)$1.000.02%
  • BittensorBittensor(TAO)$230.114.04%
  • Ripple USDRipple USD(RLUSD)$1.000.00%
  • crypto-com-chainCronos(CRO)$0.0510221.93%
  • EthenaEthena(ENA)$0.1809237.97%
  • Ondo US Dollar YieldOndo US Dollar Yield(USDY)$1.150.00%
  • okbOKB(OKB)$108.500.53%
  • Circle USYCCircle USYC(USYC)$1.140.01%
  • pepePepe(PEPE)$0.0000058.02%
  • Pump.funPump.fun(PUMP)$0.00444312.98%
  • aaveAave(AAVE)$131.323.29%
  • BlackRock USD Institutional Digital Liquidity FundBlackRock USD Institutional Digital Liquidity Fund(BUIDL)$1.000.00%
  • OndoOndo(ONDO)$0.4037225.72%
  • MemeCoreMemeCore(M)$0.852.11%
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

Fractal Analytics Profit Climbs 139% as Healthcare Leads Growth – Unite.AI

Cat Wu Steps Down as Claude Code Product Chief After Two Years – Unite.AI

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

Fractal Analytics Profit Climbs 139% as Healthcare Leads Growth – Unite.AI
AI & Technology

Fractal Analytics Profit Climbs 139% as Healthcare Leads Growth – Unite.AI

November 4, 2026
Cat Wu Steps Down as Claude Code Product Chief After Two Years – Unite.AI
AI & Technology

Cat Wu Steps Down as Claude Code Product Chief After Two Years – Unite.AI

November 4, 2026
iPad Mini OLED Vs. iPad Mini: What’s New?
AI & Technology

iPad Mini OLED Vs. iPad Mini: What’s New?

November 4, 2026
Your Phone’s Apps Could Have More Permissions Than They Need – Here’s How To Check
AI & Technology

Your Phone’s Apps Could Have More Permissions Than They Need – Here’s How To Check

November 4, 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
He Has 0,000 Of “Bad” Debt

He Has $200,000 Of “Bad” Debt

October 30, 2026
Microsoft Posts 19% Revenue Growth as Azure Revenue Jumps 48% – Unite.AI

Microsoft Posts 19% Revenue Growth as Azure Revenue Jumps 48% – Unite.AI

October 28, 2026
Binance Suspends Transactions After It Is Targeted in Biggest-Ever Cyber Heist – WSJ

Binance Suspends Transactions After It Is Targeted in Biggest-Ever Cyber Heist – WSJ

October 30, 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!