Docsity

NLP Lab Experiment/Assignment 9 Group C 2 Mini-Project Program SPPU TE AIDS 2024 Pattern, Papers of Natural Language Processing (NLP)

Toggle sidebar
bg1
import pandas as pd
import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
# Load FAQ Dataset
faq_url = "https://raw.githubusercontent.com/hellohaptik/faq-
datasets/refs/heads/master/transformed_quora_dataset/quora_train_1.csv"
faq = pd.read_csv(faq_url)
print("FAQ Dataset Loaded")
print(faq.head())
# Custom Queries Dataset
custom_queries = [
{"Task":"Q&A","Input":"What is Artificial Intelligence?"},
{"Task":"Q&A","Input":"Explain Machine Learning in simple words."},
{"Task":"Summarization","Input":"Artificial Intelligence is a branch of computer science that enables
machines to learn from data, reason, solve problems and make decisions. AI is used in healthcare, banking,
education and transportation."},
{"Task":"Summarization","Input":"Natural Language Processing helps computers understand human
language. It is widely used in chatbots, translation systems, speech recognition and sentiment analysis."},
{"Task":"Classification","Input":"The movie was amazing and I enjoyed every scene."},
{"Task":"Classification","Input":"The food was terrible and the service was slow."}
]
# Load FLAN-T5 Model
print("\nLoading FLAN-T5 Model...")
model_name = "google/flan-t5-large"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)
print("Model Loaded Successfully")
# Prompt Engineering
def create_prompt(task, text):
if task == "Q&A":
return f"""
You are a friendly AI chatbot.
Answer politely and accurately.
If the user greets you, greet them back.
If the user asks a math question, solve it.
If the user asks a general question, answer in simple English.
User: {text}
Assistant:
"""
elif task == "Summarization":
return f"Summarize the following paragraph in two sentences.\n{text}"
elif task == "Classification":
return f"Classify the sentiment as Positive or Negative.\nSentence: {text}\nSentiment:"
# Generate Response
def generate_response(task, text):
prompt = create_prompt(task, text)
inputs = tokenizer(
prompt,
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download NLP Lab Experiment/Assignment 9 Group C 2 Mini-Project Program SPPU TE AIDS 2024 Pattern and more Papers Natural Language Processing (NLP) in PDF only on Docsity!

import pandas as pd import torch from transformers import AutoTokenizer, AutoModelForSeq2SeqLM

Load FAQ Dataset

faq_url = "https://raw.githubusercontent.com/hellohaptik/faq- datasets/refs/heads/master/transformed_quora_dataset/quora_train_1.csv" faq = pd.read_csv(faq_url) print("FAQ Dataset Loaded") print(faq.head())

Custom Queries Dataset

custom_queries = [ {"Task":"Q&A","Input":"What is Artificial Intelligence?"}, {"Task":"Q&A","Input":"Explain Machine Learning in simple words."}, {"Task":"Summarization","Input":"Artificial Intelligence is a branch of computer science that enables machines to learn from data, reason, solve problems and make decisions. AI is used in healthcare, banking, education and transportation."}, {"Task":"Summarization","Input":"Natural Language Processing helps computers understand human language. It is widely used in chatbots, translation systems, speech recognition and sentiment analysis."}, {"Task":"Classification","Input":"The movie was amazing and I enjoyed every scene."}, {"Task":"Classification","Input":"The food was terrible and the service was slow."} ]

Load FLAN-T5 Model

print("\nLoading FLAN-T5 Model...") model_name = "google/flan-t5-large" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) print("Model Loaded Successfully")

Prompt Engineering

def create_prompt(task, text): if task == "Q&A": return f""" You are a friendly AI chatbot. Answer politely and accurately. If the user greets you, greet them back. If the user asks a math question, solve it. If the user asks a general question, answer in simple English. User: {text} Assistant: """ elif task == "Summarization": return f"Summarize the following paragraph in two sentences.\n{text}" elif task == "Classification": return f"Classify the sentiment as Positive or Negative.\nSentence: {text}\nSentiment:"

Generate Response

def generate_response(task, text): prompt = create_prompt(task, text) inputs = tokenizer( prompt,

return_tensors="pt", truncation=True, max_length= ) inputs = {k: v.to(device) for k, v in inputs.items()} outputs = model.generate( **inputs, max_new_tokens=80, do_sample=False ) response = tokenizer.decode( outputs[0], skip_special_tokens=True ) return response

Test Model

print("\nTesting Model\n") test = generate_response( "Q&A", "What is Artificial Intelligence?" ) print(test)

Run Chatbot

print("\n") print("=" * 70) print("CHATBOT RESPONSES") print("=" * 70) for item in custom_queries: print("\nTask :", item["Task"]) print("Input :", item["Input"]) response = generate_response(item["Task"], item["Input"]) print("Response :") print(response)

FAQ Search

print("\n") print("=" * 70) print("FAQ SEARCH") print("=" * 70) faq_queries = [ "How can i make money online easily?", "How do I prepare for the IAS exam at home?", "What is Artificial Intelligence?" ] for question in faq_queries: print("\nUser Query :", question) result = faq[faq["query"].str.lower() == question.lower()] if len(result) > 0: print("Found in FAQ Dataset") print("Question :", result.iloc[0]["query"]) print("Answer ID :", result.iloc[0]["ans"])

"Similar prompts give similar answers.", "Responses are meaningful.", "Grammar is correct.", "Some complex questions need more details." ] }) print(evaluation)

Performance Analysis

print("\n") print("=" * 70) print("PERFORMANCE ANALYSIS") print("=" * 70) print("1. FLAN-T5 successfully performs Question Answering.") print("2. It generates summaries using prompt engineering.") print("3. It classifies text into Positive or Negative sentiment.") print("4. Prompt engineering improves response quality.") print("5. FAQ dataset answers known questions instantly.") print("6. LLM answers unseen questions without predefined rules.")

Limitations

print("\n") print("=" * 70) print("LIMITATIONS") print("=" * 70) limitations = [ "Responses depend on the pretrained FLAN-T5 model.", "Very complex questions may produce incomplete answers.", "The FAQ dataset contains only predefined questions.", "Response quality depends on prompt design.", "The small FLAN-T5 model is less accurate than larger LLMs." ] for i, item in enumerate(limitations, 1): print(str(i) + ".", item)

Future Improvements

print("\n") print("=" * 70) print("FUTURE IMPROVEMENTS") print("=" * 70) future = [ "Use FLAN-T5 Base or Large model for better responses.", "Connect the chatbot to a real-time knowledge base.", "Add voice input and speech output.", "Store conversation history for better context.", "Fine-tune the model on a domain-specific FAQ dataset.", "Deploy the chatbot as a web application using Streamlit or Flask." ] for i, item in enumerate(future, 1): print(str(i) + ".", item)

Conclusion

print("\n") print("=" * 70)

print("CONCLUSION") print("=" * 70) print("This mini-project demonstrates a chatbot using the FLAN-T5 Large Language Model.") print("The chatbot performs Question Answering, Summarization and Text Classification using prompt engineering.") print("A FAQ dataset is used for predefined questions while the LLM answers unseen queries.") print("Prompt engineering improves the relevance, clarity and consistency of generated responses.") print("The project shows how pretrained Large Language Models can be used to build intelligent conversational systems.")

Project Summary

print("\n") print("=" * 70) print("PROJECT SUMMARY") print("=" * 70) summary = pd.DataFrame({ "Requirement":[ "Custom Queries Dataset", "FAQ Dataset", "Large Language Model", "Prompt Engineering", "Question Answering", "Summarization", "Classification", "Response Evaluation", "Performance Analysis", "Future Improvements" ], "Status":[ "Completed", "Completed", "Completed", "Completed", "Completed", "Completed", "Completed", "Completed", "Completed", "Completed" ] }) print(summary)

Sample Interactive Chat

print("\n") print("=" * 70) print("SAMPLE CHATBOT") print("=" * 70) while True: query = input("\nEnter your question (type exit to quit): ") if query.lower() == "exit": print("\nThank you for using the FLAN-T5 Chatbot.")