How to make an Ai recommendation system with Django and Prophet
Introduction
Recommendation systems have become a crucial part of many online platforms, from e-commerce sites to streaming services. These systems use historical data and machine learning algorithms to predict what users might like based on their behavior and preferences. In this tutorial, we’ll build a recommendation system that suggests products, content, or items to users.
Setting up the Environment
Before we begin, ensure you have Python, Django, and the required libraries installed. You can set up a virtual environment to keep your project dependencies isolated:
python -m venv recommendation-system
source recommendation-system/bin/activate
pip install django pandas prophet
Understanding AI Recommendation Systems
AI recommendation systems typically fall into two categories: content-based and collaborative filtering. In this tutorial, we’ll focus on content-based recommendations using the Prophet library for forecasting.
Using Prophet for Forecasting
Prophet is a powerful forecasting tool developed by Facebook for time series data. It’s particularly useful when dealing with trends and seasonal patterns. We’ll leverage Prophet’s capabilities to predict user preferences and interests.
Integrating Prophet with Django
Our first step is to load historical data into Django models. Suppose we have a model named UserActivity
with fields user
, item
, timestamp
, and rating
. We'll extract user-item interactions and timestamps to prepare the data for forecasting.
Step 1: Load Historical Data
- Create a Django model to represent user activity. For example, you can define a model named
UserActivity
with fieldsuser
,item
,timestamp
, andrating
. - Populate your database with historical user activity data. Each record should include the user, the item they interacted with, the timestamp of the interaction, and potentially a rating or preference score.
Step 2: Data Preprocessing
- Import the required libraries at the beginning of your Django view or script:
from django.shortcuts import render
import pandas as pd
from prophet import Prophet
Building the Recommendation Engine
Create a function that generates recommendations for a specific user based on their historical activity:
def generate_recommendations(user_activity):
# Convert user activity to a DataFrame
data = [
{'ds': activity.timestamp, 'y': activity.rating} # Use 'y' as per your dataset
for activity in user_activity
]
df = pd.DataFrame(data)
# Prepare the DataFrame for Prophet
df.rename(columns={'ds': 'ds', 'y': 'y'}, inplace=True)
# Create and fit a Prophet model
model = Prophet()
model.fit(df)
# Create a future DataFrame for predictions
future = model.make_future_dataframe(periods=7) # Adjust 'periods' as needed
# Generate forecasts
forecast = model.predict(future)
# Extract the last predicted values as recommendations
recommendations = forecast[['ds', 'yhat']].tail(7) # Get the last 7 predicted values
return recommendations
Step 2: Retrieving User Activity
In your Django views, retrieve the historical activity for a specific user:
user_id = 123 # Adjust with the user's actual ID
user_activity = UserActivity.objects.filter(user_id=user_id).order_by('-timestamp')
Step 3: Generating Recommendations
- Call the
generate_recommendations
function with the user's activity:
recommendations = generate_recommendations(user_activity)
Frontend Implementation
- In your Django template, use a loop to display the recommended items:
<h2>Recommended Items:</h2>
<ul>
{% for item in recommendations %}
<li>{{ item.ds|date:"Y-m-d" }} - Rating: {{ item.yhat }}</li>
{% endfor %}
</ul>
Conclusion
Integrating Prophet with Django allows you to leverage the forecasting capabilities of Prophet for building an AI recommendation system. By preparing historical data, training the model, and making predictions, you can provide personalized recommendations to users based on their past interactions.
This integration offers a solid foundation for creating a user-friendly and engaging recommendation system that enhances user experience and encourages further engagement on your Django-based platform.