Views
No views yet
1# Split the data into training and test sets
2
3from sklearn.model_selection import train_test_split
4
5# Stratify by city to keep the same proportion of samples from each city
6
7virginia_subset, _ = train_test_split(
8 virginia_restaurants_forRAG,
9 train_size=4000,
10 stratify=virginia_restaurants_forRAG['city'],
11 random_state=5002
12)1# text for embedding column with combined details - it's recommended
2virginia_subset['text_for_embedding'] = (
3 "RESTAURANT: " + virginia_subset['name'] + "\n" +
4 "LOCATION: " + virginia_subset['street'] + ", " + virginia_subset['city'] + ", " + virginia_subset['zipcode'].astype(str) + "\n" +
5 "RESTAURANT CATEGORY: " + virginia_subset['restaurant category'] + "\n" +
6 "MENU CATEGORY: " + virginia_subset['menu category'] + "\n" +
7 "MENU ITEMS: " + virginia_subset['menu item'] + "\n" +
8 "PRICE RANGE: " + virginia_subset['min price'].astype(str) + " to " + virginia_subset['max price'].astype(str)
9)
10| Model | Exact Match | F1-Score | ROUGE | Cosine Similarity |
|---|---|---|---|---|
| Qwen2.5-1.5B-Instruct | 0.33 | 0.33 | 0.4580 | 0.5850 |
| Falcon-H1-1.5B-Instruct | 0.00 | 0.00 | 0.1453 | 0.5850 |
| meta-llama/Llama-3.2-3B-Instruct | 0.00 | 0.00 | 0.1500 | 0.5850 |
1# Loading the Virginia Subset Dataset
2import numpy as np
3import pandas as pd
4
5virginia_subset = pd.read_csv('virginia_subset_RAGtraining.csv')
6virginia_subset.head()1# Load the Huggingface Model
2from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
3
4tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct")
5model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct",
6 device_map ="auto", dtype = torch.float16)
71# Convert each row to it's own document
2
3documents = []
4
5for row in virginia_subset.itertuples(index=False):
6 documents.append(
7 Document(
8 page_content=row.text_for_embedding, # text for embedding
9 metadata={
10 "name": row.name,
11 "city": row.city,
12 "zipcode": row.zipcode,
13 "restaurant_category": row.restaurant_category # clean column name
14 }
15 )
16 )
17
18# Embed each document and store in vector database
19
20hf_embedding_model = HuggingFaceEmbeddings(model_name="Qwen/Qwen3-Embedding-0.6B",
21 model_kwargs={"device": "cuda"}
22 )
23
24vectorstore = FAISS.from_documents(documents, hf_embedding_model) 1def user_query(query, top_k=1, max_tokens=300, return_documents=False):
2 documents = vectorstore.similarity_search_with_score(query, k=top_k)
3
4 documents_only = [document[0] for document in documents]
5 faiss_distances = [score for _, score in documents]
6
7 # Convert FAISS L2 distance → cosine similarity
8 # Assumes embeddings were normalized when added to FAISS
9 cosine_scores = [1 - (d / 2) for d in faiss_distances]
10
11 # Combine the context
12 context_info = [document.page_content for document, _ in documents]
13 context_text = "\n".join(context_info)
14
15
16 messages = [
17 {"role": "system",
18 "content": ( "You are an assistant specializing in locating Virginia Restaurants "
19 "that offer food delivery. User the context to answer accurately. "
20 "If the context does not contain the answer, say so."
21 )
22 },
23 {"role": "user",
24 "content": (
25 f"Context:\n{context_text}\n\n"
26 f"Question:{query}"
27 )
28 }
29 ]
30
31 text = tokenizer.apply_chat_template(
32 messages,
33 tokenize=False,
34 add_generation_prompt=True
35 )
36 model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
37
38 generated_ids = model.generate(
39 **model_inputs,
40 max_new_tokens=512,
41 repetition_penalty=1.1,
42 temperature = 0.2,
43 do_sample = True,
44 eos_token_id=tokenizer.eos_token_id,
45 pad_token_id=tokenizer.pad_token_id
46 )
47
48 generated_ids = [
49 output_ids[len(input_ids):]
50 for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
51 ]
52
53 response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
54
55 if return_documents:
56 return response, context_info, faiss_distances, cosine_scores
57
58 return responseuser_query function1# -------------------------
2# Step 1: Load evaluation prompts
3# -------------------------
4# These are your test queries with expected answers
5
6test_data = [
7 {
8 "prompt": "What restaurants in Richmond, VA serves southern food?",
9 "ground_truth": "Big Herm's Kitchen"
10 },
11 {
12 "prompt": "Which is the price range at Iron Paffles and Coffee located in Charlottesville, VA?",
13 "ground_truth": "$1.00 - $15.00"
14 }]
15
16# -------------------------
17# Step 2: Generate answers using user_query
18# -------------------------
19results = []
20for sample in test_data:
21 prompt = sample["prompt"]
22 ground_truth = sample["ground_truth"]
23
24 # Call your existing retrieval + generation function
25 generated, retrieved_context, faiss_scores,
26 cosine_scores = user_query(prompt, top_k=1, max_tokens=300, return_documents=True)
27
28 # Convert FAISS L2 → cosine similarity
29 cosine_scores = [1 - (d / 2) for d in faiss_scores]
30
31
32 results.append({
33 "prompt": prompt,
34 "ground_truth": ground_truth,
35 "generated": generated,
36 "retrieved_context": retrieved_context,
37 "cosine_similarity": cosine_scores
38 })
39
40# -------------------------
41# Step 3: Compute metrics
42# -------------------------
43# User-defined evaluation metrics (e.g., Exact Match, F1, ROUGE, Cosine Similarity)
44# Implementation is omitted for flexibility.
45
46# -------------------------
47# Step 4: Print results
48# -------------------------
49# User-defined result formatting and display
50# Implementation is omitted.1Sample outputs:
2Prompt: What restaurants in Richmond, VA serves southern food?
3Ground Truth: Big Herm's Kitchen
4Generated: Big Herm's Kitchen
5
6Retrieved Context & Cosine Similarity:
7--------------------------------------------------
8[Doc 0] Cosine=0.5850
9RESTAURANT: Big Herm's Kitchen
10LOCATION: 315 N 2Nd St, Richmond, 23219
11CATEGORIES: southern, black-owned, american
12MENU CATEGORIES: Picked for you, Appetizers, Sides, Sandwiches and Baskets, Burgers, Salads, Homemade Desserts, Beverages
13MENU ITEMS: Roasted Corn and Asparagus Salad, Blackened Chicken ...
14
15------------------------------------------------------------
16Prompt: Which is the price range at Iron Paffles and Coffee located in Charlottesville, VA?
17Ground Truth: $1.00 - $15.00
18Generated: The price range at Iron Paffles and Coffee, located in Charlottesville, VA, is $1.00 to $15.00.
19
20Retrieved Context & Cosine Similarity:
21--------------------------------------------------
22[Doc 0] Cosine=0.7914
23RESTAURANT: Iron Paffles and Coffee
24LOCATION: 214 Water St W, Charlottesville, 22902
25CATEGORIES: american, sandwich, desserts, allergy friendly
26MENU CATEGORIES: Picked for you, Savory Paffles, Sweet Paffles, Beverages, Sides, Build your Own, Espresso
27MENU ITEMS: Maine Root Root Beer, Iced Mocha, 12o ...user_query implementation & Output1query = "What restaurants offer delivery for Indian cuisines in Virginia Beach?"
2answer = user_query(query, top_k=1)
3print("=== Generated Answer ===")
4print(answer)
5
6=== Generated Answer ===
7Saffron Indian Bistro offers delivery of Indian cuisine in Virginia Beach.
8
9
10query = "Are there any vegan or vegetarian options in Northern Virginia?"
11answer = user_query(query, top_k=1)
12print("=== Generated Answer ===")
13print(answer)
14
15=== Generated Answer ===
16Yes, there are several vegetarian and vegan options available at Biryani Hub in Northern Virginia. Some of these include:
17
18- Channa Masala
19- Chilli Garlic Naan
20- Murgh Tikka (Chicken) Tandoor
21- Gosht Kurma (Goat)
22- Butter Naan
23- Dal Fry
24- Paneer (Cottage Cheese) Butter Masala
25- Murgh Saag (Chicken)
26- Dum Ka Veg
27- Chef's Special Murgh (Chicken)
28- Shrimp Apollo
29- Kheema (Ground Goat) Biryani
30
31Note: This list is cut short, but there were more results.1@misc{lewis2020retrievalaugmented,
2 title = {Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks},
3 author = {Lewis, Patrick and Perez, Ethan and Piktus, Aleksandra and Petroni, Fabio
4 and Karpukhin, Vladimir and Goyal, Naman and Küttler, Heinrich and
5 Lewis, Mike and Yih, Wen-tau and Rocktäschel, Tim and Riedel, Sebastian
6 and Kiela, Douwe},
7 year = {2020},
8 note = {arXiv:2005.11401}
9}
10
11@misc{palakkode2025buildcsvrag,
12 title = {Build a Simple RAG System with CSV Files: Step‑by‑Step Guide for Beginners},
13 author = {Palakkode, Abhay},
14 year = {2025},
15 howpublished = {\url{https://www.machinelearningplus.com/gen-ai/build-a-simple-rag-system-with-csv-files-step-by-step-guide-for-beginners/}},
16}
17
18@misc{sakib2023ubereats,
19 author = {Ahmed Shahriar Sakib},
20 title = {Uber Eats USA Restaurants Menus},
21 year = {2023},
22 url = {https://www.kaggle.com/datasets/ahmedshahriarsakib/uber-eats-usa-restaurants-menus},
23 note = {Accessed: 2023-12-14}
24}
25