Machine Learning project 19
Machine Learning E-commerce Product Recommendation Project
Build and evaluate a complete e-commerce product recommendation workflow with reproducible Python code, explicit metrics, and honest limitations.
Explore Machine Learning training in VizagView all project ideas
Dataset and objective
A small embedded table of anonymous example users, product names, and interaction-strength values.
Skills practised
- Implicit interactions
- Product-user matrices
- Cosine similarity
- Ranking safeguards
Requirements
- Python 3.10 or later
- A terminal or command prompt
python -m pip install pandas scikit-learn- About 45-60 minutes to build and review
Machine Learning workflow
- Data: A small embedded table of anonymous example users, product names, and interaction-strength values.
- Preprocessing: A product-by-user matrix fills absent interactions with zero for a compact implicit-similarity demonstration.
- Model: Cosine similarity ranks products whose interaction vectors resemble the selected seed item.
- Evaluation: The script returns three different products; real systems need offline ranking metrics and controlled online experiments.
Complete Python code
Save the code as ml_ecommerce_recommendation.py. The random state and data handling are included so the result can be reproduced and reviewed.
"""Recommend e-commerce products from a small implicit-interaction matrix."""
from __future__ import annotations
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
INTERACTIONS = [
("u1", "Laptop Stand", 3), ("u1", "Wireless Mouse", 4), ("u1", "USB-C Hub", 2),
("u2", "Laptop Stand", 2), ("u2", "Wireless Mouse", 5), ("u2", "Keyboard", 4),
("u3", "Running Shoes", 5), ("u3", "Sports Bottle", 3), ("u3", "Fitness Band", 2),
("u4", "Running Shoes", 4), ("u4", "Sports Bottle", 4), ("u4", "Yoga Mat", 3),
("u5", "USB-C Hub", 4), ("u5", "Keyboard", 4), ("u5", "Wireless Mouse", 3),
("u6", "Yoga Mat", 5), ("u6", "Fitness Band", 4), ("u6", "Sports Bottle", 3),
("u7", "Laptop Stand", 4), ("u7", "USB-C Hub", 4), ("u7", "Keyboard", 3),
("u8", "Running Shoes", 4), ("u8", "Fitness Band", 5), ("u8", "Sports Bottle", 2),
]
def similarity_table() -> pd.DataFrame:
frame = pd.DataFrame(INTERACTIONS, columns=["user", "product", "strength"])
matrix = frame.pivot_table(index="product", columns="user", values="strength", fill_value=0)
return pd.DataFrame(cosine_similarity(matrix), index=matrix.index, columns=matrix.index)
def recommend(product: str, count: int = 3) -> pd.Series:
similarities = similarity_table()
if product not in similarities.index:
raise ValueError(f"Unknown product. Choose from: {', '.join(similarities.index)}")
return similarities.loc[product].drop(product).sort_values(ascending=False).head(count)
def main() -> None:
products = list(similarity_table().index)
print("Products:", ", ".join(products))
product = input("Product to use as the seed: ").strip()
try:
suggestions = recommend(product)
except ValueError as error:
print(error)
return
print("\nCustomers with similar interactions also considered:")
for name, score in suggestions.items():
print(f"- {name}: similarity {score:.3f}")
print("Real recommenders need offline ranking metrics, diversity, privacy controls, and online experiments.")
if __name__ == "__main__":
main()
How the pipeline works
A product-by-user matrix fills absent interactions with zero for a compact implicit-similarity demonstration.
Cosine similarity ranks products whose interaction vectors resemble the selected seed item. The script returns three different products; real systems need offline ranking metrics and controlled online experiments.
Run the project
- Create and activate a virtual environment.
- Install the dependencies with
python -m pip install pandas scikit-learn. - Run
python ml_ecommerce_recommendation.py. - Review every printed metric together with the limitation below; a single score never proves deployment readiness.
How to interpret the evaluation
Classification projects report class-aware metrics so majority classes do not hide weak performance. Regression projects report errors in target units and include R-squared or a simple baseline where appropriate. Always verify the split strategy matches how new data will arrive.
Accuracy, ethics, and safety limits
The data is synthetic and too small for personalisation claims. Real recommenders need privacy, diversity, inventory, popularity-bias, feedback-loop, and safety controls.
Ways to extend the project
Add purchases and views with different weights, filter unavailable stock, evaluate recall@K and diversity, handle new products, and run consented experiments.
Continue learning Machine Learning
Try the next project, return to the Softenant project library, or explore the Machine Learning course in Vizag for guided data preparation, model evaluation, and portfolio feedback.