book-recommender / README.md
Deepak Sahu
readme update approach section
10b6366
|
raw
history blame
8.54 kB
metadata
title: Book Recommender
emoji: 
colorFrom: indigo
colorTo: gray
sdk: gradio
sdk_version: 5.6.0
app_file: app.py
pinned: false
short_description: A content based book recommender.

Content-Based-Book-Recommender

A HyDE based approach for building recommendation engine.

Try it out: https://huggingface.co/spaces/LunaticMaestro/book-recommender

image

Table of Content

All images are my actual work please source powerpoint of them in .resources folder of this repo.

Running Inference Locally

Libraries

I used google colab with following libraries extra.

pip install sentence-transformers datasets

Running

Local System

python app.py

access at http://localhost:7860/

Goolge Colab

Modify app.py edit line 93 to demo.launch(share=True) then run following in cell.

!python app.py

Approach

image

References:

Training Steps

ALL files Paths are at set as CONST in beginning of each script, to make it easier while using the paths while inferencing; hence not passing as CLI arguments

Step 1: Data Clean

I am going to do basic steps like unwanted column removal (the first column of index), missing values removal (drop rows), duplicate rows removal. Output Screenshot attached.

I am NOT doing any text pre-processing steps like stopword removal, stemming/lemmatization or special character removal because my approach is to use the casual language modelling (later steps) hence makes no sense to rip apart the word meaning via these word-based techniques.

A little tinker in around with the dataset found that some titles can belong to multiple categories. (this code I ran separately, is not part of any script)

image

A descriptive analysis shows that there are just 1230 unique titles. (this code I ran separately, is not part of any script)

image

We are not going to remove them rows that shows same titles (& summaries) with different categories but rather create a separate file for unique titles.

python z_clean_data.py

image

Output: clean_books_summary.csv, unique_titles_books_summary.csv

Step 2: Generate vectors of the books summaries.

Here, I am going to use pretrained sentence encoder that will help get the meaning of the sentence. As the semantic meaning of the summaries themselves are not changed.

We perform this over unique_titles_books_summary.csv dataset

image

Use command

python z_embedding.py

Just using CPU should take <1 min

image

Output: app_cache/summary_vectors.npy

Step 3: Fine-tune GPT-2 to Hallucinate but with some bounds.

Lets address the Hypothetical part of HyDE approach. Its all about generating random summaries,in short hallucinating. While the Document Extraction (part of HyDE) is about using these hallucinated summaries to do semantic search on database.

Two very important reasons why to fine-tune GPT-2

  1. We want it to hallucinate but withing boundaries i.e. speak words/ language that we have in books_summaries.csv NOT VERY DIFFERENT OUT OF WORLD LOGIC.

  2. Prompt Tune such that we can get consistent results. (Screenshot from https://huggingface.co/openai-community/gpt2); The screenshot show the model is mildly consistent.

image

we are going to use ``clean_books_summary.csv` dataset in this training to align with the prompt of ingesting different genre.

Reference:

Command

You must supply your token from huggingface, required to push model to HF

huggingface-cli login

We are going to use dataset clean_books_summary.csv while triggering this training.

python z_finetune_gpt.py

(Training lasts ~30 mins for 10 epochs with T4 GPU)

image

The loss you see is cross-entryopy loss; as ref in the fine-tuning instructions (see above reference) states : Transformers models all have a default task-relevant loss function, so you don’t need to specify one

image

So all we care is lower the value better is the model trained :)

We are NOT going to test this unit model for some test dataset as the model is already proven (its GPT-2 duh!!). But we are going to evaluate our HyDE approach end-2-end next to ensure sanity of the approach.

Evaluation

Before discussing evaluation metric let me walk you through two important pieces recommendation generation and similarity matching;

Recommendation Generation

The generation is handled by script z_hypothetical_summary.py. Under the hood following happens

image

Code Preview. I did the minimal post processing to chop of the prompt from the generated summaries before returning the result.

image

Similarity Matching

image

image

Because there are 1230 unique titles so we get the averaged similarity vector of same size.

image

Evaluation Metric

So for given input title we can get rank (by desc order cosine similarity) of the store title. To evaluate we the entire approach we are going to use a modified version Mean Reciprocal Rank (MRR).

image

We are going to do this for random 30 samples and compute the mean of their reciprocal ranks. Ideally all the title should be ranked 1 and their MRR should be equal to 1. Closer to 1 is good.

image

The values of TOP_P and TOP_K (i.e. token sampling for our generator model) are sent as CONST in the z_evaluate.py; The current set of values of this are borrowed from the work: https://www.kaggle.com/code/tuckerarrants/text-generation-with-huggingface-gpt2#Top-K-and-Top-P-Sampling

MRR = 0.311 implies that there's a good change that the target book will be in rank (1/.311) ~ 3 (third rank) i.e. within top 5 recommendations

Inference

app.py is written so that it can best work with gradio interface in the HuggingFace, althought you can try it out locally as well :)

python app.py
  1. I rewrote the snippets from z_evaluate.py to app.py with minor changes to expriment with view.
  2. DONT set debug=True for gradio in HF space, else it doesn't start.
  3. HF space work differently for retaining models across module scipts; local running (tried in colab space) works faster. You will see lot of my commits in HF Space to work around this problem.