A semantic book recommendation system built with sentence-transformers and cosine similarity. Input a natural language description of what you're in the mood for and get the closest matching books from a Goodreads dataset.
- Book descriptions from a Goodreads dataset are converted into vector embeddings using a pretrained sentence-transformer model
- When a user inputs a natural language query (e.g. "a dark mystery set in Victorian London"), it is embedded into the same vector space
- Cosine similarity is computed between the query vector and all book vectors
- The closest matching books are returned ranked by similarity
Input: "a dark mystery set in Victorian London"
Output:
I recommend the following books:
- 'The Crimes of Jack The Ripper', which is a pictorial excursion into the dark underbelly of Victorian London...
- 'Oh! Where are Bloody Mary's Earrings?', which is a mystery set in the court of Queen Victoria...
- 'The Shadow of William Quest', which is a Victorian thriller set in the gaslit alleys of London...
sentence-transformers: generates semantic embeddings usingall-MiniLM-L6-v2scikit-learn: cosine similarity computationpandas: data loading and manipulationnumpy: saving and loading embeddingsHuggingFace datasets: loading the Goodreads book descriptions dataset
1. Install dependencies
pip install sentence-transformers scikit-learn pandas numpy datasets2. Load the dataset and generate embeddings
from datasets import load_dataset
from sentence_transformers import SentenceTransformer
import numpy as np
ds = load_dataset("booksouls/goodreads-book-descriptions")
df = ds["train"].to_pandas()
model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = model.encode(df["description"].tolist(), show_progress_bar=True)
np.save("embeddings.npy", embeddings)3. Run a recommendation
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
embeddings = np.load("embeddings.npy")
def recommend(query, top_n=5):
query_vec = model.encode([query])
scores = cosine_similarity(query_vec, embeddings)[0]
top_indices = scores.argsort()[::-1][:top_n]
results = df.iloc[top_indices][["title", "description"]]
return results
results = recommend("a dark mystery set in Victorian London")
print("I recommend the following books:\n")
for _, row in results.iterrows():
print(f"- '{row['title']}', which is a {row['description']}\n")The dataset used is booksouls/goodreads-book-descriptions via HuggingFace, which contains book titles and descriptions sourced from Goodreads.
- Embeddings are generated once and saved to
embeddings.npyto avoid recomputing on every run - For faster embedding generation, enable GPU in your environment (e.g. Google Colab: Runtime → Change runtime type → T4 GPU)
- The model
all-MiniLM-L6-v2runs fine on CPU for small subsets (~500 books) but a GPU is recommended for the full dataset
Develop the same project with the CMU Book Summary Dataset, which is more a complete dataset with authors, dates, etc.