- Python Snacks
- Posts
- Generative vs Discriminative AI in Python
Generative vs Discriminative AI in Python
Learn when to use Generative and Discriminative AI with practical Python examples.

The rapidly changing tech industry demands every IT professional to upskill and find ways to integrate AI and machine learning models into their workflows.
With nearly half of tech leaders reporting full AI integration in their businesses, the gap between AI-ready and AI-behind professionals is widening fast.
In this newsletter, we will explore different types of AI and its applications in real-world scenarios using Python. There are two main types:
Discriminative AI
Generative AI
Discriminative AI
Discriminative AI helps differentiate between various types of data and machine learning enables us to categorize new data based on prior training.
Any workflow involving categorization of data can be automated and optimized using Discriminative AI models. A common use of discriminative AI is spam detection. Using scikit-learn we can build a small spam classifier as such:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
'''
First run these commands on terminal
pip install numpy
pip install scipy
pip install scikit-learn
'''
# Sample data
texts = ["Win a free ticket now", "Hi, how are you?", "Limited time offer", "Let's meet tomorrow"]
labels = [1, 0, 1, 0] # 1 = spam, 0 = not spam
# Convert text to numbers
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
# Train classifier
model = MultinomialNB()
model.fit(X, labels)
# Predict new text
new_text = ["Win a free offer now!"]
X_new = vectorizer.transform(new_text)
prediction = model.predict(X_new)
print("Spam" if prediction[0] == 1 else "Not Spam")
# output: spam
This spam classifier works using:
CountVectorizer: turns text into word frequency counts
MultinomialNB: a machine learning model (Naive Baytes classifier) trained on those counts" flows better
In this example, messages labeled as ‘spam’ contain keywords like ‘win’ and ‘free’, so any new message with those words is likely to be classified as spam using a machine learning model.
» Machine Learning is a subset of AI that focuses on enabling systems to learn patterns from data and make decisions or predictions without being explicitly programmed
Generative AI
As the name suggests, it uses already available data to generate new ideas based on instructions. It can create text, images, videos, music, algorithms, or anything that requires creative skill.
Programmers can benefit by integrating pre-trained machine learning models into their applications. These models, available as APIs and libraries, support business use cases such as:
Text summarization or report generation
Automated reply bots
Test case generation
Content creation
Documentation assistance
Below is a brief example of content creation using GPT-2 (from Hugging Face).
from transformers import pipeline
import torch
#pip install torch
#pip install transformers
generator = pipeline('text-generation', model='openai-community/gpt2', torch_dtype=torch.float16, device=0)
prompt = "Can you write me FAQs for Masters in data science enrollement in USA?"
result = generator(prompt, max_new_tokens=400, num_return_sequences=1)
print(result[0]['generated_text'])
» Try changing how you ask the AI questions - small tweaks can make the answers much better without needing to change the model.
Conclusion:
Understanding the different types of AI and their applications empowers you to automate processes effectively. By refining your prompts and improving training data over time, you can maximize the impact of AI and drive greater efficiency in your work.
Pro tip: Check out OpenAI’s API - it’s easy to use and can quickly be added to your web apps for powerful AI features.
Happy coding!
📧 Join the Python Snacks Newsletter! 🐍
Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:
Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.
Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.
Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.
You can unsubscribe at any time.
Interested in starting a newsletter or a blog?
Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.
If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.
This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.
Reply