Introduction
OpenAI's announcement of a $1 billion annual run rate for ChatGPT's advertising business highlights the growing commercial potential of AI platforms. This tutorial will teach you how to build a simple ad targeting system using Python and machine learning concepts that mirror the foundational technologies behind such advertising platforms. You'll learn to create a basic recommendation engine that can suggest relevant advertisements based on user behavior and content analysis.
Prerequisites
- Basic Python programming knowledge
- Understanding of machine learning concepts (clustering, classification)
- Installed Python libraries: scikit-learn, pandas, numpy
- Basic understanding of how advertising platforms work
Step-by-Step Instructions
1. Set Up Your Development Environment
First, we need to install the required Python packages. Open your terminal and run:
pip install scikit-learn pandas numpy
This installs the necessary libraries for data processing and machine learning. We'll use scikit-learn for our clustering algorithms and pandas for data manipulation.
2. Create Sample User and Ad Data
We'll create sample datasets that represent users and advertisements. This simulates the kind of data an advertising platform would collect:
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
# Sample user data
users = pd.DataFrame({
'user_id': range(1, 101),
'age': np.random.randint(18, 65, 100),
'interests': ['technology', 'sports', 'music', 'travel', 'food'] * 20,
'previous_clicks': np.random.randint(0, 100, 100)
})
# Sample ad data
ads = pd.DataFrame({
'ad_id': range(1, 21),
'category': ['technology', 'sports', 'music', 'travel', 'food'] * 4,
'description': ['Latest smartphone', 'Football match', 'Concert tickets', 'Beach vacation', 'Cooking class'] * 4
})
print("User data sample:")
print(users.head())
print("\nAd data sample:")
print(ads.head())
This creates two datasets - one representing users with their demographics and behavior, and another with advertising content. The real-world equivalent would involve much more complex data collection and processing.
3. Prepare Text Data for Analysis
Advertising content often includes text that needs to be analyzed for relevance matching. We'll use TF-IDF vectorization to convert ad descriptions into numerical features:
# Vectorize ad descriptions
vectorizer = TfidfVectorizer(stop_words='english')
ad_features = vectorizer.fit_transform(ads['description'])
# Display feature names
print("Feature names (first 10):")
print(vectorizer.get_feature_names_out()[:10])
TF-IDF (Term Frequency-Inverse Document Frequency) helps identify important words in ad descriptions while downplaying common words. This is crucial for matching ads to user interests.
4. Implement User Clustering
We'll cluster users based on their interests and behavior to create targeted advertising groups:
# Prepare user data for clustering
user_data = users[['age', 'previous_clicks']].copy()
# Add interest encoding
interest_mapping = {'technology': 0, 'sports': 1, 'music': 2, 'travel': 3, 'food': 4}
user_data['interest_encoded'] = users['interests'].map(interest_mapping)
# Perform K-means clustering
kmeans = KMeans(n_clusters=3, random_state=42)
user_data['cluster'] = kmeans.fit_predict(user_data[['age', 'previous_clicks', 'interest_encoded']])
print("User clusters:")
print(user_data.groupby('cluster').size())
This clustering approach groups users with similar characteristics, allowing for more effective ad targeting. The number of clusters (3) can be adjusted based on business requirements.
5. Create Ad Recommendation Engine
Now we'll build a simple recommendation system that matches users to relevant ads:
def recommend_ads(user_cluster, ad_features, ads, top_n=3):
# Get ads in the same category as the user cluster
cluster_categories = ['technology', 'sports', 'music', 'travel', 'food']
category = cluster_categories[user_cluster % 5]
# Find ads in the same category
category_ads = ads[ads['category'] == category]
if len(category_ads) == 0:
# Fallback to any ad
category_ads = ads
# Simple similarity based on TF-IDF
similarities = []
for idx, ad in category_ads.iterrows():
ad_vector = ad_features[ad.name] # Using ad index
similarity = np.dot(ad_vector.toarray()[0], ad_features[ad.name].toarray()[0])
similarities.append((ad['ad_id'], similarity))
# Sort by similarity and return top N
similarities.sort(key=lambda x: x[1], reverse=True)
return [ad_id for ad_id, sim in similarities[:top_n]]
# Test recommendation system
print("Recommendations for cluster 0:")
recommendations = recommend_ads(0, ad_features, ads)
print(recommendations)
This system uses both category matching and content similarity to suggest relevant advertisements. The real-world version would use more sophisticated algorithms and larger datasets.
6. Evaluate and Optimize
Let's create a simple evaluation function to measure recommendation quality:
def evaluate_recommendations(user_data, ads, ad_features):
total_accuracy = 0
total_recommendations = 0
for cluster in user_data['cluster'].unique():
cluster_users = user_data[user_data['cluster'] == cluster]
# For each user in the cluster
for _, user in cluster_users.iterrows():
user_cluster = user['cluster']
recommendations = recommend_ads(user_cluster, ad_features, ads)
# Simple accuracy check - how many recommendations match user interests?
category = ['technology', 'sports', 'music', 'travel', 'food'][user_cluster % 5]
matched = sum(1 for ad_id in recommendations if ads[ads['ad_id'] == ad_id]['category'].iloc[0] == category)
total_accuracy += matched
total_recommendations += len(recommendations)
accuracy = total_accuracy / total_recommendations if total_recommendations > 0 else 0
return accuracy
# Evaluate our system
accuracy = evaluate_recommendations(user_data, ads, ad_features)
print(f"Recommendation accuracy: {accuracy:.2f}")
This evaluation provides a basic measure of how well our recommendations match user preferences. In production systems, this would involve more complex metrics and A/B testing.
Summary
This tutorial demonstrated how to build a foundational ad targeting system using Python and machine learning. While this is a simplified version of what OpenAI and other platforms implement, it covers key concepts like user clustering, text analysis, and recommendation matching. The core principles involve understanding user behavior, analyzing content relevance, and creating targeted advertising experiences. Real-world advertising platforms would incorporate more sophisticated algorithms, larger datasets, and real-time processing capabilities to achieve the scale and effectiveness seen in companies like OpenAI.
The techniques shown here form the building blocks of modern advertising technology, demonstrating how data science and machine learning can be applied to create effective, personalized user experiences.



