Spaces:
Runtime error
Runtime error
nirajandhakal
commited on
Commit
•
f97b093
1
Parent(s):
61529ee
initial commit
Browse files- .gitattributes +1 -0
- app.py +272 -0
- authors_w2v.model +3 -0
- recommendation_model.keras +3 -0
- recommender.h5 +3 -0
- requirements.txt +6 -0
- title_w2v.model +3 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
recommendation_model.keras filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This is a book recommendation system.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import pickle
|
6 |
+
import streamlit as st
|
7 |
+
import pandas as pd
|
8 |
+
import numpy as np
|
9 |
+
from sklearn.preprocessing import LabelEncoder
|
10 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
11 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
12 |
+
from tensorflow.keras.models import load_model
|
13 |
+
|
14 |
+
# Load datasets
|
15 |
+
books = pd.read_csv("./dataset/books.csv")
|
16 |
+
ratings = pd.read_csv("./dataset/ratings.csv")
|
17 |
+
|
18 |
+
# Preprocess data
|
19 |
+
user_encoder = LabelEncoder()
|
20 |
+
book_encoder = LabelEncoder()
|
21 |
+
|
22 |
+
|
23 |
+
ratings["user_id"] = user_encoder.fit_transform(ratings["user_id"])
|
24 |
+
ratings["book_id"] = book_encoder.fit_transform(ratings["book_id"])
|
25 |
+
|
26 |
+
# Load TF-IDF models
|
27 |
+
with open("tfidf_model_authors.pkl", "rb") as f:
|
28 |
+
tfidf_model_authors = pickle.load(f)
|
29 |
+
|
30 |
+
with open("tfidf_model_titles.pkl", "rb") as f:
|
31 |
+
tfidf_model_titles = pickle.load(f)
|
32 |
+
|
33 |
+
# Define TF-IDF vectorizer
|
34 |
+
tfidf_vectorizer = TfidfVectorizer(stop_words="english")
|
35 |
+
|
36 |
+
# Fit and transform the book descriptions
|
37 |
+
tfidf_matrix = tfidf_vectorizer.fit_transform(books["original_title"].fillna(""))
|
38 |
+
|
39 |
+
# Load collaborative filtering model
|
40 |
+
model_cf = load_model("recommendation_model.keras")
|
41 |
+
|
42 |
+
|
43 |
+
# Content-Based Recommendation
|
44 |
+
def content_based_recommendation(
|
45 |
+
query, books, tfidf_model_authors, tfidf_model_titles, num_recommendations=10
|
46 |
+
):
|
47 |
+
"""
|
48 |
+
Recommend books based on content similarity.
|
49 |
+
Args:
|
50 |
+
query (str): The name of the book or author.
|
51 |
+
books (DataFrame): DataFrame containing book information.
|
52 |
+
tfidf_model_authors: Pre-trained TF-IDF model for authors.
|
53 |
+
tfidf_model_titles: Pre-trained TF-IDF model for titles.
|
54 |
+
num_recommendations (int): The number of books to recommend.
|
55 |
+
Returns:
|
56 |
+
DataFrame: A DataFrame containing recommended books with details.
|
57 |
+
"""
|
58 |
+
# Check if the query corresponds to an author or a book
|
59 |
+
if query in books["authors"].values:
|
60 |
+
book_name = books.loc[books["authors"] == query, "original_title"].values[0]
|
61 |
+
elif query in books["original_title"].values:
|
62 |
+
book_name = query
|
63 |
+
else:
|
64 |
+
print("Query not found in authors or titles.")
|
65 |
+
return None
|
66 |
+
|
67 |
+
book_author = books.loc[books["original_title"] == book_name, "authors"].values[0]
|
68 |
+
book_title = books.loc[books["title"] == book_name, "title"].values[0]
|
69 |
+
|
70 |
+
# Transform book author, title, and description into TF-IDF vectors
|
71 |
+
book_author_tfidf = tfidf_model_authors.transform([book_author])
|
72 |
+
book_title_tfidf = tfidf_model_titles.transform([book_title])
|
73 |
+
|
74 |
+
# Compute cosine similarity for authors and titles separately
|
75 |
+
similarity_scores_authors = cosine_similarity(
|
76 |
+
book_author_tfidf, tfidf_model_authors.transform(books["authors"])
|
77 |
+
)
|
78 |
+
similarity_scores_titles = cosine_similarity(
|
79 |
+
book_title_tfidf, tfidf_model_titles.transform(books["title"])
|
80 |
+
)
|
81 |
+
|
82 |
+
# Combine similarity scores for authors and titles
|
83 |
+
similarity_scores_combined = (
|
84 |
+
similarity_scores_authors + similarity_scores_titles
|
85 |
+
) / 2
|
86 |
+
|
87 |
+
# Get indices of recommended books
|
88 |
+
recommended_indices = np.argsort(similarity_scores_combined.flatten())[
|
89 |
+
-num_recommendations:
|
90 |
+
][::-1]
|
91 |
+
|
92 |
+
# Get recommended books
|
93 |
+
recommended_books = books.iloc[recommended_indices]
|
94 |
+
|
95 |
+
return recommended_books
|
96 |
+
|
97 |
+
|
98 |
+
# Collaborative Recommendation
|
99 |
+
def collaborative_recommendation(user_id, model_cf, ratings, num_recommendations=10):
|
100 |
+
"""
|
101 |
+
Recommend books based on collaborative filtering.
|
102 |
+
Args:
|
103 |
+
user_id (int): The user ID.
|
104 |
+
model_cf: The trained collaborative filtering model.
|
105 |
+
ratings (DataFrame): DataFrame containing user ratings.
|
106 |
+
num_recommendations (int): The number of books to recommend.
|
107 |
+
Returns:
|
108 |
+
DataFrame: A DataFrame containing recommended books with details.
|
109 |
+
"""
|
110 |
+
# Check if the user ID exists in the ratings dataset
|
111 |
+
if user_id not in ratings["user_id"].unique():
|
112 |
+
print("User ID not found in ratings dataset.")
|
113 |
+
return None
|
114 |
+
|
115 |
+
# Get unrated books for the user
|
116 |
+
unrated_books = ratings[
|
117 |
+
~ratings["book_id"].isin(ratings[ratings["user_id"] == user_id]["book_id"])
|
118 |
+
]["book_id"].unique()
|
119 |
+
|
120 |
+
# Check if there are unrated books
|
121 |
+
if len(unrated_books) == 0:
|
122 |
+
print("No unrated books found for the user.")
|
123 |
+
return None
|
124 |
+
|
125 |
+
# Predict ratings for unrated books
|
126 |
+
predictions = model_cf.predict(
|
127 |
+
[np.full_like(unrated_books, user_id), unrated_books]
|
128 |
+
).flatten()
|
129 |
+
|
130 |
+
# Get top indices based on predictions
|
131 |
+
top_indices = np.argsort(predictions)[-num_recommendations:][::-1]
|
132 |
+
|
133 |
+
# Get recommended books
|
134 |
+
recommended_books = books.iloc[top_indices][["original_title", "authors"]]
|
135 |
+
return recommended_books
|
136 |
+
|
137 |
+
|
138 |
+
# History-Based Recommendation
|
139 |
+
def history_based_recommendation(user_id, ratings, num_recommendations=10):
|
140 |
+
"""
|
141 |
+
Recommend books based on user's historical ratings.
|
142 |
+
Args:
|
143 |
+
user_id (int): The user ID.
|
144 |
+
ratings (DataFrame): DataFrame containing user ratings.
|
145 |
+
num_recommendations (int): The number of books to recommend.
|
146 |
+
Returns:
|
147 |
+
DataFrame: A DataFrame containing recommended books with details.
|
148 |
+
"""
|
149 |
+
user_ratings = ratings[ratings["user_id"] == user_id]
|
150 |
+
top_books = user_ratings.sort_values(by="rating", ascending=False).head(
|
151 |
+
num_recommendations
|
152 |
+
)["book_id"]
|
153 |
+
recommended_books = books[books["book_id"].isin(top_books)]
|
154 |
+
return recommended_books
|
155 |
+
|
156 |
+
|
157 |
+
# Hybrid Recommendation
|
158 |
+
def hybrid_recommendation(
|
159 |
+
user_id,
|
160 |
+
query,
|
161 |
+
model_cf,
|
162 |
+
books,
|
163 |
+
ratings,
|
164 |
+
tfidf_model_authors,
|
165 |
+
tfidf_model_titles,
|
166 |
+
num_recommendations=10,
|
167 |
+
):
|
168 |
+
"""
|
169 |
+
Recommend books using hybrid recommendation approach.
|
170 |
+
Args:
|
171 |
+
user_id (int): The user ID.
|
172 |
+
query (str): The name of the book or author.
|
173 |
+
model_cf: The collaborative filtering model.
|
174 |
+
books (DataFrame): DataFrame containing book information.
|
175 |
+
ratings (DataFrame): DataFrame containing user ratings.
|
176 |
+
tfidf_model_authors: Pre-trained TF-IDF model for authors.
|
177 |
+
tfidf_model_titles: Pre-trained TF-IDF model for titles.
|
178 |
+
num_recommendations (int): The number of books to recommend.
|
179 |
+
Returns:
|
180 |
+
DataFrame: A DataFrame containing recommended books with details.
|
181 |
+
"""
|
182 |
+
content_based_rec = content_based_recommendation(
|
183 |
+
query,
|
184 |
+
books,
|
185 |
+
tfidf_model_authors,
|
186 |
+
tfidf_model_titles,
|
187 |
+
num_recommendations=num_recommendations,
|
188 |
+
)
|
189 |
+
collaborative_rec = collaborative_recommendation(
|
190 |
+
user_id, model_cf, ratings, num_recommendations=num_recommendations
|
191 |
+
)
|
192 |
+
history_based_rec = history_based_recommendation(
|
193 |
+
user_id, ratings, num_recommendations=num_recommendations
|
194 |
+
)
|
195 |
+
|
196 |
+
# Combine recommendations from different approaches
|
197 |
+
hybrid_rec = pd.concat(
|
198 |
+
[content_based_rec, collaborative_rec, history_based_rec]
|
199 |
+
).drop_duplicates(subset="book_id", keep="first")
|
200 |
+
return hybrid_rec
|
201 |
+
|
202 |
+
|
203 |
+
# Top Recommendations (most popular books)
|
204 |
+
def top_recommendations(books, num_recommendations=10):
|
205 |
+
"""
|
206 |
+
Recommend top books based on popularity (highest ratings count).
|
207 |
+
Args:
|
208 |
+
books (DataFrame): DataFrame containing book information.
|
209 |
+
num_recommendations (int): The number of books to recommend.
|
210 |
+
Returns:
|
211 |
+
DataFrame: A DataFrame containing recommended books with details.
|
212 |
+
"""
|
213 |
+
top_books = books.sort_values(by="ratings_count", ascending=False).head(
|
214 |
+
num_recommendations
|
215 |
+
)
|
216 |
+
return top_books
|
217 |
+
|
218 |
+
|
219 |
+
# Test the recommendation functions
|
220 |
+
query = input("Enter book name or author: ")
|
221 |
+
USER_ID = 0 # Example user ID for collaborative and history-based recommendations
|
222 |
+
|
223 |
+
print("Content-Based Recommendation:")
|
224 |
+
print(
|
225 |
+
content_based_recommendation(query, books, tfidf_model_authors, tfidf_model_titles)
|
226 |
+
)
|
227 |
+
|
228 |
+
print("\nCollaborative Recommendation:")
|
229 |
+
print(collaborative_recommendation(USER_ID, model_cf, ratings))
|
230 |
+
|
231 |
+
print("\nHistory-Based Recommendation:")
|
232 |
+
print(history_based_recommendation(USER_ID, ratings))
|
233 |
+
|
234 |
+
print("\nHybrid Recommendation:")
|
235 |
+
print(
|
236 |
+
hybrid_recommendation(
|
237 |
+
user_id,
|
238 |
+
query,
|
239 |
+
model_cf,
|
240 |
+
books,
|
241 |
+
ratings,
|
242 |
+
tfidf_model_authors,
|
243 |
+
tfidf_model_titles,
|
244 |
+
)
|
245 |
+
)
|
246 |
+
|
247 |
+
print("\nTop Recommendations:")
|
248 |
+
print(top_recommendations(books))
|
249 |
+
|
250 |
+
# Streamlit App
|
251 |
+
st.title("Book Recommendation System")
|
252 |
+
|
253 |
+
# Sidebar for user input
|
254 |
+
user_input = st.text_input("Enter book name or author:", "")
|
255 |
+
|
256 |
+
# Get recommendations on button click
|
257 |
+
if st.button("Get Recommendations"):
|
258 |
+
st.write("Content-Based Recommendation:")
|
259 |
+
content_based_rec = content_based_recommendation(
|
260 |
+
user_input, books, tfidf_model_authors, tfidf_model_titles
|
261 |
+
)
|
262 |
+
st.write(content_based_rec)
|
263 |
+
|
264 |
+
st.write("Collaborative Recommendation:")
|
265 |
+
collaborative_rec = collaborative_recommendation(0, model_cf, ratings)
|
266 |
+
st.write(collaborative_rec)
|
267 |
+
|
268 |
+
st.write("Hybrid Recommendation:")
|
269 |
+
hybrid_rec = hybrid_recommendation(
|
270 |
+
0, user_input, model_cf, books, ratings, tfidf_model_authors, tfidf_model_titles
|
271 |
+
)
|
272 |
+
st.write(hybrid_rec)
|
authors_w2v.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:254a7bb6b32780bbc3df2575c65fad32042738af828cf11b634f5bc9066f817d
|
3 |
+
size 4978284
|
recommendation_model.keras
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:60e07d12b6cfde3b5ac7c9589a3fa1dc7890716c94f26fd8dd3bc8ae70d1f3dc
|
3 |
+
size 38171840
|
recommender.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bb8b80df7fbbfe345a51a8f826b260c4ce30d33dfc386b91b7b3eaaa9750f02e
|
3 |
+
size 38177168
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit
|
2 |
+
numpy
|
3 |
+
pandas
|
4 |
+
tensorflow
|
5 |
+
sklearn
|
6 |
+
keras
|
title_w2v.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a05d399ab55578c046a190d2d3015bcfc36fc0e7289f09c257eb17c0e78035ce
|
3 |
+
size 6747050
|