Generative AI (1)
Generative AI (1)
Sl.NO Experiments
1. Explore pre-trained word vectors. Explore word relationships using vector arithmetic. Perform arithmetic
operations and analyze results.
2. Use dimensionality reduction (e.g., PCA or t-SNE) to visualize word embeddings for Q 1. Select 10 words from a
specific domain (e.g., sports, technology) and visualize their embeddings. Analyze clusters and relationships. Generate
contextually rich outputs using embeddings. Write a program to generate 5 semantically similar words for a given
input.
3. Train a custom Word2Vec model on a small dataset. Train embeddings on a domain-specific corpus (e.g., legal,
medical) and analyze how embeddings capture domain-specific semantics.
4. Use word embeddings to improve prompts for Generative AI model. Retrieve similar words using word embeddings.
Use the similar words to enrich a GenAI prompt. Use the AI model to generate responses for the original and enriched
prompts. Compare the outputs in terms of detail and relevance.
5. Use word embeddings to create meaningful sentences for creative tasks. Retrieve similar words for a seed word. Create
a sentence or story using these words as a starting point. Write a program that: Takes a seed word. Generates similar
words. Constructs a short paragraph using these words.
6. Use a pre-trained Hugging Face model to analyze sentiment in text. Assume a real-world application, Load the
sentiment analysis pipeline. Analyze the sentiment by giving sentences to input.
7. Summarize long texts using a pre-trained summarization model using Hugging face model. Load the
summarization pipeline. Take a passage as input and obtain the summarized text.
8. Install langchain, cohere (for key), langchain-community. Get the api key( By logging into Cohere and obtaining the
cohere key). Load a text document from your google drive . Create a prompt template to display the output in a
particular manner.
9. Take the Institution name as input. Use Pydantic to define the schema for the desired output and create a custom output
parser. Invoke the Chain and Fetch Results. Extract the below Institution related details from Wikipedia: The founder
of the Institution. When it was founded. The current branches in the institution . How many employees are
working in it. A brief 4-line summary of the institution.
10 Build a chatbot for the Indian Penal Code. We'll start by downloading the official Indian Penal Code document, and
then we'll create a chatbot that can interact with it. Users will be able to ask questions about the Indian Penal Code
and have a conversation with it.
PROGRAM 1:
1. Explore pre-trained word vectors. Explore word relationships using vector arithmetic. Perform
arithmetic operations and analyze results.
OUTPUT
import gensim
from gensim.models import Word2Vec
import spacy
import re
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
print_similar_words('plaintiff')
print_similar_words('contract')
step3:- Fix TensorFlow one DNN Warnings run the program in VSCODE termninal
if word_lower in embedding_model:
similar_words = embedding_model.most_similar(word_lower, topn=n)
similar_word_list = [w[0] for w in similar_words]
enriched_prompt.append(" ".join(similar_word_list)) # Join similar words as a phrase
else:
enriched_prompt.append(word) # Keep the word as is if not found
return " ".join(enriched_prompt)
# Generate responses
original_response = generator(original_prompt, max_length=50, num_return_sequences=1)
enriched_response = generator(enriched_prompt, max_length=50,
num_return_sequences=1)
# Print results
print("Original prompt response")
print(original_response[0]['generated_text'])
OUTPUT
Original prompt response
Describe the beautiful landscapes during sunset. View the entire project »
View gallery
import random
import gensim.downloader as api
def create_paragraph(seed_word):
"""Generate a short paragraph using the seed word and its similar words."""
similar_words = get_similar_words(seed_word)
if not similar_words:
return f"Could not find similar words for '{seed_word}'. Try another word!"
return paragraph
# Example usage
seed_word = input("Enter a seed word: ").strip().lower()
print("\nGenerated Story:\n")
print(create_paragraph(seed_word))
OUTPUT
Enter a seed word: adventure
Generated Story:
def analyze_sentiment(text):
"""Analyze sentiment of the input text using Hugging Face pipeline."""
result = sentiment_analyzer(text)
label = result[0]['label']
score = result[0]['score']
# Example usage
while True:
user_input = input("Enter a sentence for sentiment analysis (or 'exit' to quit):
").strip()
if user_input.lower() == 'exit':
break
print(analyze_sentiment(user_input))
OUTPUT
Device set to use CPU
Enter a sentence for sentiment analysis (or 'exit' to quit): I love this product! It's
amazing
Sentiment: POSITIVE (Confidence: 1.00)
Enter a sentence for sentiment analysis (or 'exit' to quit): This is the worst
experience ever
Sentiment: NEGATIVE (Confidence: 1.00)
Enter a sentence for sentiment analysis (or 'exit' to quit): The service was okay,
nothing special
Sentiment: NEGATIVE (Confidence: 0.99)
PROGRAM 8
Summarize long texts using a pre-trained summarization model using Hugging
face model. Load the summarization pipeline. Take a passage as input and
obtain the summarized text.
def summarize_text(text):
"""Summarize the input text using Hugging Face's summarization model."""
summary = summarizer(text, max_length=100, min_length=30, do_sample=False)
return summary[0]['summary_text']
# Example usage
print("Enter a long passage for summarization (or 'exit' to quit):")
while True:
long_text = input("\nPaste your text: ").strip()
if long_text.lower() == 'exit':
break
print("\nSummarized Text:\n")
print(summarize_text(long_text))
OUTPUT
Device set to use cpu
Enter a long passage for summarization (or 'exit' to quit):
Summarized Text:
Your max_length is set to 100, but your input_length is only 70. Since this is a
summarization task, where outputs shorter than the input are typically wanted, you
might consider decreasing max_length manually, e.g. summarizer('...',
max_length=35)
From healthcare to finance, AI is automating processes, improving efficiency, and
enabling data-driven decision-making . Companies are investing heavily in AI
research to stay competitive . But ethical concerns, bias in AI models and the need
for regulation remain critical issues .