I am unable to resolve the error with the below code:
The main.html does not bring back the recommended products and throws this error on dataframe.
def content_based_recommendations(train_data, item_name, top_n=10):
if item_name not in train_data['Name'].values:
print(f"Item '{item_name}' not found in the training data.")
return pd.DataFrame()
tfidf_vectorizer = TfidfVectorizer(stop_words='english')
tfidf_matrix_content = tfidf_vectorizer.fit_transform(train_data['Tags'])
cosine_similarities_content = cosine_similarity(tfidf_matrix_content, tfidf_matrix_content)
item_index = train_data[train_data['Name'] == item_name].index[0]
similar_items = list(enumerate(cosine_similarities_content[item_index]))
similar_items = sorted(similar_items, key=lambda x: x[1], reverse=True)
top_similar_items = similar_items[1:top_n+1]
recommended_item_indices = [x[0] for x in top_similar_items]
recommended_items_details = train_data.iloc[recommended_item_indices][['Name', 'ReviewCount', 'Brand', 'ImageURL', 'Rating']]
return recommended_items_details
@app.route("/recommendations", methods=['POST'])
def recommendations():
try:
prod = request.form.get('prod')
nbr = request.form.get('nbr')
if not prod or not nbr:
return render_template('main.html', message="Product name or number of recommendations is missing.")
try:
nbr = int(nbr)
except ValueError:
return render_template('main.html', message="Invalid number of recommendations.")
df = pd.read_csv('clean_data.csv')
print(df.to_string())
content_based_rec = content_based_recommendations(train_data, prod, top_n=nbr)
if content_based_rec.empty:
return render_template('main.html', message="No recommendations available for this product.")
else:
random_product_image_urls = [random.choice(random_image_urls) for _ in range(len(content_based_rec))]
price = [40, 50, 60, 70, 100, 122, 106, 50, 30, 50]
return render_template('main.html', content_based_rec=content_based_rec, truncate=truncate,
random_product_image_urls=random_product_image_urls,
random_price=random.choice(price))
except Exception as e:
return render_template('main.html', message=f"An error occurred: {str(e)}")
How to resolve it?
I was expecting the list of similar items displayed on the template.
1