Introduction
In this tutorial, you'll learn how to create a simple AI-powered shopping recommendation system using Python and basic machine learning concepts. This tutorial mirrors the technology that helped Amazon's Prime Day achieve record-breaking sales by using AI to recommend products to customers. We'll build a system that can suggest products based on user preferences and shopping history.
Prerequisites
To follow this tutorial, you'll need:
- A computer with Python installed (version 3.6 or higher)
- Basic understanding of Python programming concepts
- Internet connection for downloading required packages
Step-by-Step Instructions
Step 1: Set Up Your Python Environment
First, we need to create a new Python project and install the necessary libraries. Open your terminal or command prompt and run the following commands:
mkdir ai-shopping-recommender
cd ai-shopping-recommender
python -m venv shopping_env
source shopping_env/bin/activate # On Windows use: shopping_env\Scripts\activate
pip install pandas scikit-learn
Why we do this: We're creating a separate environment to avoid conflicts with other Python projects. The libraries we install will help us process data and build our recommendation model.
Step 2: Create Sample Product Data
Next, we'll create a simple dataset of products. Create a file called products.py:
import pandas as pd
def create_sample_products():
products = {
'product_id': [1, 2, 3, 4, 5, 6, 7, 8],
'name': ['Wireless Headphones', 'Smartphone', 'Laptop', 'Smart Watch', 'Tablet', 'Camera', 'Speaker', 'Gaming Console'],
'category': ['Electronics', 'Electronics', 'Electronics', 'Electronics', 'Electronics', 'Electronics', 'Electronics', 'Electronics'],
'price': [89.99, 699.99, 1299.99, 249.99, 399.99, 599.99, 129.99, 499.99],
'rating': [4.5, 4.7, 4.8, 4.3, 4.6, 4.4, 4.2, 4.9]
}
return pd.DataFrame(products)
if __name__ == '__main__':
df = create_sample_products()
print(df)
Why we do this: This creates a realistic dataset of products that we can use to train our recommendation system. The data includes key attributes that users might consider when shopping.
Step 3: Create User Preference Data
Now, let's create a user profile system. Create a file called users.py:
import pandas as pd
def create_sample_users():
users = {
'user_id': [1, 2, 3],
'preferred_category': ['Electronics', 'Electronics', 'Electronics'],
'max_budget': [1000, 2000, 500],
'min_rating': [4.0, 4.5, 4.0]
}
return pd.DataFrame(users)
if __name__ == '__main__':
df = create_sample_users()
print(df)
Why we do this: Users have different preferences, budgets, and rating requirements. This data helps our AI understand what each user is likely to buy.
Step 4: Build the Recommendation Engine
Now, let's create the core recommendation system. Create a file called recommender.py:
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
class ShoppingRecommender:
def __init__(self, products_df, users_df):
self.products = products_df
self.users = users_df
def recommend_products(self, user_id, num_recommendations=3):
# Get user preferences
user = self.users[self.users['user_id'] == user_id].iloc[0]
# Filter products based on user preferences
filtered_products = self.products[
(self.products['price'] <= user['max_budget']) &
(self.products['rating'] >= user['min_rating'])
]
# Sort by rating (highest first)
recommended = filtered_products.sort_values('rating', ascending=False)
# Return top recommendations
return recommended.head(num_recommendations)
def get_similar_products(self, product_id, num_similar=3):
# Simple similarity based on price and rating
target_product = self.products[self.products['product_id'] == product_id].iloc[0]
# Calculate similarity scores
self.products['similarity'] = (
(self.products['price'] - target_product['price']).abs() * -1 +
(self.products['rating'] - target_product['rating']) * 10
)
# Get similar products
similar = self.products[self.products['product_id'] != product_id].sort_values('similarity', ascending=False)
return similar.head(num_similar)
if __name__ == '__main__':
# Load data
from products import create_sample_products
from users import create_sample_users
products_df = create_sample_products()
users_df = create_sample_users()
# Create recommender
recommender = ShoppingRecommender(products_df, users_df)
# Get recommendations for user 1
recommendations = recommender.recommend_products(1)
print("Recommendations for User 1:")
print(recommendations[['name', 'price', 'rating']])
Why we do this: This is the heart of our AI shopping system. The code filters products based on user preferences and ranks them by rating to provide personalized recommendations.
Step 5: Run the Complete System
Now, let's create a main script to run everything together. Create a file called main.py:
from products import create_sample_products
from users import create_sample_users
from recommender import ShoppingRecommender
def main():
print("AI Shopping Recommendation System")
print("==================================")
# Load datasets
products_df = create_sample_products()
users_df = create_sample_users()
# Create recommender
recommender = ShoppingRecommender(products_df, users_df)
# Show all products
print("\nAll Available Products:")
print(products_df[['name', 'price', 'rating']])
# Get recommendations for each user
for user_id in users_df['user_id']:
print(f"\nRecommendations for User {user_id}:")
recommendations = recommender.recommend_products(user_id)
print(recommendations[['name', 'price', 'rating']])
# Show similar products
print("\nSimilar Products to Wireless Headphones:")
similar = recommender.get_similar_products(1)
print(similar[['name', 'price', 'rating']])
if __name__ == '__main__':
main()
Why we do this: This script ties everything together, showing how our AI system would work in a real shopping scenario. It demonstrates both personalized recommendations and product similarity features.
Step 6: Test Your System
Run your complete system by executing the following command in your terminal:
python main.py
You should see output showing all products, personalized recommendations for each user, and similar products. This simulates how Amazon's AI chatbot might recommend products to users during Prime Day.
Summary
In this tutorial, you've built a simple AI-powered shopping recommendation system that mimics the technology behind Amazon's Prime Day success. You've learned how to:
- Create product and user data structures
- Build a recommendation engine that filters products based on user preferences
- Implement a basic similarity algorithm to find related products
- Run a complete shopping recommendation system
This system demonstrates the core concepts that make AI shopping effective - understanding user preferences and matching them with relevant products. While this is a simplified version, real systems like Amazon's would use more complex algorithms, larger datasets, and machine learning models to provide even better recommendations.



