Issue while creating an API for recommendation system for users

19 views Asked by At
from flask import Flask, jsonify, request
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
import joblib

app = Flask(__name__)

# Load pre-trained user-user similarity matrix
user_user_similarity_matrix = joblib.load('Predictive Model/user_user_similarity_matrix.pkl')

# Load your dataset from an Excel file (This line is not required for API functionality)
data = pd.read_excel('Predictive Model/DDDD.xlsx')

# Add a placeholder column 'PurchasedYes' to the data DataFrame
data['PurchasedYes'] = 1

@app.route('/recommend', methods=['POST'])
def recommend():
    user_id = request.json['user_id']  # Get user ID from request
    recommendations = generate_recommendations(user_user_similarity_matrix, data, user_id, n_recommendations=10)
    return jsonify({'user_id': user_id, 'recommendations': recommendations})


def generate_recommendations(user_similarity_matrix, data, user_id, n_recommendations=10):
    # Pivot table to get a matrix where rows represent customers and columns represent items
    customer_item_matrix = data.pivot_table(index='Customer', columns='SalesItem', values='PurchasedYes', fill_value=0)

    # Get items purchased by the user
    user_purchases = customer_item_matrix.loc[user_id].values.reshape(1, -1)  # Reshape to row vector

    # Calculate user-user similarity scores (Ensure user_similarity_matrix has same number of rows as customers)
    user_similarity_scores = user_similarity_matrix[user_id].reshape(1, -1)  # Transpose the matrix

    # Option 1 (Ensure user_similarity_matrix has compatible dimensions)
    # Check how `user_user_similarity_matrix` is loaded to have the same number of rows as customers

    # Option 2 (Reshape user_similarity_scores to match customer_item_matrix.columns)
    # user_similarity_scores = user_similarity_scores.reshape(-1, customer_item_matrix.shape[1])

    # Weighted sum of purchases by similar users
    weighted_purchases = customer_item_matrix.values.dot(user_similarity_scores.T)

    # Filter out items already purchased by the user
    weighted_purchases[customer_item_matrix.loc[user_id] != 0] = -np.inf

    # Get indices of top n recommendations
    top_indices = np.argsort(weighted_purchases.flatten())[::-1][:n_recommendations]

    # Get recommended items
    recommended_items = [customer_item_matrix.columns[i] for i in top_indices]

    return recommended_items


if __name__ == '__main__':
    app.run(debug=True)

For this code I am getting an error I am not able to solve this error.

Error: weighted_purchases = customer_item_matrix.values.dot(user_similarity_scores.T)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: shapes (35,3725) and (32,1) not aligned: 3725 (dim 1) != 32 (dim 0)

I did try to modify the code by making the dimensions same for both the matrices. Also used chatgpt but no use. Please give me good solutions also if you can modify this code for me that would be huge help.

This is my dataset overview. Dataset Overview

This is the drive link for the pkl file and the dataset as well. text

0

There are 0 answers