Text Share Online

genai67

———————Program 1————————
!pip install gensim numpy
import gensim.downloader as api
print(“Loading pre-trained word vectors…”)
wv = api.load(“word2vec-google-news-300”)
# Word relationships
for a, b, c in [
(“king”, “man”, “woman”),
(“paris”, “france”, “germany”),
(“apple”, “fruit”, “carrot”)
]:
print(f”nWord Relationship: {a} – {b} + {c}”)
print(“Most similar words to the result (excluding input words):”)

for word, score in wv.similar_by_vector(wv[a] – wv[b] + wv[c], topn=10):
if word not in {a, b, c}:
print(f”{word}: {score:.4f}”)

# Similarity analysis
for w1, w2 in [
(“cat”, “dog”),
(“computer”, “keyboard”),
(“music”, “art”)
]:
print(f”nSimilarity between ‘{w1}’ and ‘{w2}’: {wv.similarity(w1, w2):.4f}”)

# Most similar words
for word in [“happy”, “sad”, “technology”]:
print(f”nMost similar words to ‘{word}’:”)
for w, score in wv.most_similar(word, topn=5):
print(f”{w}: {score:.4f}”)

———————Program 2————————————-

(a)——————————————————-
!pip install gensim numpy matplotlib scikit-learn

import gensim.downloader as api
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE

print(“Loading pre-trained word vectors…”)
wv = api.load(“word2vec-google-news-300”)

words = [“king”,”man”,”woman”,”queen”,”prince”,”princess”,”royal”,”throne”]

print(“nWord Relationship: king – man + woman”)
print(“Most similar words to the result (excluding input words):”)

sim = []
for w,s in wv.similar_by_vector(wv[“king”]-wv[“man”]+wv[“woman”], topn=10):
if w not in {“king”,”man”,”woman”}:
print(f”{w}: {s:.4f}”)
sim.append(w)

words += sim[:5]
vecs = np.array([wv[w] for w in words])

for name,R in [(“PCA”,PCA(2)),(“TSNE”,TSNE(n_components=2,random_state=42,perplexity=3))]:
x = R.fit_transform(vecs)
plt.figure(figsize=(8,6))
for i,w in enumerate(words):
plt.scatter(x[i,0],x[i,1])
plt.text(x[i,0],x[i,1],w)
plt.title(f”Word Embeddings Visualization using {name}”)
plt.show()

(b)———————————————————
!pip install gensim numpy matplotlib scikit-learn

import gensim.downloader as api
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE

print(“Loading pre-trained word vectors…”)
wv = api.load(“word2vec-google-news-300”)

words = [“computer”,”software”,”hardware”,”algorithm”,”data”,
“network”,”programming”,”machine”,”learning”,”artificial”]

vecs = np.array([wv[w] for w in words])

for name,R in [(“PCA”,PCA(2)),(“TSNE”,TSNE(n_components=2,random_state=42,perplexity=3))]:
x = R.fit_transform(vecs)
plt.figure(figsize=(8,6))
for i,w in enumerate(words):
plt.scatter(x[i,0],x[i,1])
plt.text(x[i,0],x[i,1],w)
plt.title(f”Word Embeddings Visualization using {name}”)
plt.show()

for word in [“computer”,”learning”]:
print(f”nTop 5 semantically similar words to ‘{word}’:”)
for w,s in wv.most_similar(word, topn=5):
print(f”{w}: {s:.4f}”)

———————————Program 3————————————————-

!pip install gensim matplotlib scikit-learn

from gensim.models import Word2Vec
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import numpy as np

corpus = [
“The patient was diagnosed with diabetes and hypertension.”,
“MRI scans reveal abnormalities in the brain tissue.”,
“The treatment involves antibiotics and regular monitoring.”,
“Symptoms include fever, fatigue, and muscle pain.”,
“The vaccine is effective against several viral infections.”,
“Doctors recommend physical therapy for recovery.”,
“The clinical trial results were published in the journal.”,
“The surgeon performed a minimally invasive procedure.”,
“The prescription includes pain relievers and anti-inflammatory drugs.”,
“The diagnosis confirmed a rare genetic disorder.”
]

data = [s.lower().split() for s in corpus]

print(“Training Word2Vec model…”)
model = Word2Vec(data, vector_size=100, window=5, min_count=1, epochs=50)
print(“Model training complete!”)

words = model.wv.index_to_key
vecs = np.array([model.wv[w] for w in words])

x = TSNE(n_components=2, random_state=42, perplexity=5).fit_transform(vecs)

plt.figure(figsize=(10,8))
plt.scatter(x[:,0], x[:,1])

for i,w in enumerate(words):
plt.text(x[i,0], x[i,1], w)

plt.title(“Word Embeddings Visualization (Medical Domain)”)
plt.show()

for word in [“treatment”, “vaccine”]:
print(f”nWords similar to ‘{word}’:”)
for w,s in model.wv.most_similar(word, topn=5):
print(f”{w} ({s:.2f})”)

——————————————-Program 4————————————————-

!pip install gensim transformers nltk

import gensim.downloader as api
from transformers import pipeline
import nltk

nltk.download(‘punkt’)

print(“Loading pre-trained word vectors…”)
wv = api.load(“glove-wiki-gigaword-100”)

print(“nLoading GPT-2 model…”)
gen = pipeline(“text-generation”, model=”gpt2″)

prompt = “Who is king.”
print(f”nOriginal Prompt: {prompt}”)

new_word = wv.most_similar(“king”, topn=1)[0][0]
print(f”Replacing ‘king’ → ‘{new_word}'”)

enriched = prompt.replace(“king”, new_word)

print(f”n Enriched Prompt: {enriched}”)

orig = gen(prompt, max_length=100, num_return_sequences=1)[0][“generated_text”]
enr = gen(enriched, max_length=100, num_return_sequences=1)[0][“generated_text”]

print(“nGenerating response for the original prompt…”)
print(“nOriginal Prompt Response:”)
print(orig)

print(“nGenerating response for the enriched prompt…”)
print(“nEnriched Prompt Response:”)
print(enr)

print(“nComparison of Responses:”)
print(“nOriginal Prompt Response Length:”, len(orig))
print(“Enriched Prompt Response Length:”, len(enr))
print(“nOriginal Prompt Response Detail:”, orig.count(“.”))
print(“Enriched Prompt Response Detail:”, enr.count(“.”))

———————–Program 5————————————————–

!pip install gensim

import gensim.downloader as api

print(“Loading pre-trained word vectors…”)
wv = api.load(“glove-wiki-gigaword-100”)

seed = input(“Enter a seed word: “)

try:
words = [w for w, _ in wv.most_similar(seed, topn=5)]

print(“nGenerated Paragraph:n”)

print(
f”The {seed} was surrounded by {words[0]} and {words[1]}. “
f”People often associate {seed} with {words[2]} and {words[3]}. “
f”In the land of {seed}, {words[4]} was a common sight. “
f”A story about {seed} would be incomplete without {words[1]} and {words[3]}.”
)

except KeyError:
print(f”‘{seed}’ not found in vocabulary. Try another word.”)

——————————Program 6———————————————-

!pip install transformers

from transformers import pipeline

print(“Loading Sentiment Analysis Model…”)
sa = pipeline(“sentiment-analysis”)

reviews = [
“The product is amazing! I love it so much.”,
“I’m very disappointed. The service was terrible.”,
“It was an average experience, nothing special.”,
“Absolutely fantastic quality! Highly recommended.”,
“Not great, but not the worst either.”
]

print(“nCustomer Sentiment Analysis Results:”)

for review in reviews:
r = sa(review)[0]
print(f”nInput Text: {review}”)
print(f”Sentiment: {r[‘label’]} (Confidence: {r[‘score’]:.4f})”)

——————————-Program 7———————————————-

!pip install transformers==4.36.2

from transformers import pipeline

print(“Loading Summarization Model…”)
summarizer = pipeline(“summarization”, model=”facebook/bart-large-cnn”)

text = “””
Artificial Intelligence (AI) is a branch of computer science that focuses on creating systems capable of performing tasks that normally require human intelligence. These tasks include learning from experience, reasoning, problem-solving, understanding natural language, recognizing patterns, and making decisions. AI has evolved significantly over the past few decades due to advancements in computing power, the availability of large datasets, and improvements in machine learning algorithms.

One of the most important areas of AI is machine learning, which enables computers to learn from data without being explicitly programmed. Machine learning algorithms analyze large volumes of data, identify patterns, and make predictions or decisions based on the information they have learned. Deep learning, a subset of machine learning, uses artificial neural networks inspired by the structure of the human brain. Deep learning has achieved remarkable success in areas such as image recognition, speech processing, natural language understanding, and autonomous driving.

AI has transformed numerous industries. In healthcare, AI assists doctors in diagnosing diseases, analyzing medical images, discovering new drugs, and personalizing treatment plans for patients. In finance, AI is used for fraud detection, algorithmic trading, risk assessment, and customer service through intelligent chatbots. In education, AI-powered systems provide personalized learning experiences, automate administrative tasks, and help educators track student performance. In transportation, self-driving vehicles use AI to perceive their surroundings, make decisions, and navigate safely.

The entertainment industry also benefits from AI through recommendation systems that suggest movies, music, and content based on user preferences. Social media platforms rely on AI to personalize feeds, detect harmful content, and improve user engagement. Businesses use AI for market analysis, customer support, supply chain optimization, and predictive maintenance of equipment.

Despite its benefits, AI presents several challenges and ethical concerns. Bias in training data can lead to unfair or discriminatory outcomes. Privacy concerns arise when AI systems process large amounts of personal information. There are also fears regarding job displacement as automation replaces certain human tasks. Additionally, the increasing use of AI raises questions about transparency, accountability, and the responsible use of intelligent systems.

Researchers, governments, and organizations worldwide are working to establish ethical guidelines and regulations for AI development. The goal is to ensure that AI technologies are developed and deployed responsibly while maximizing their benefits for society. As AI continues to advance, it is expected to play an even greater role in shaping the future of technology, business, healthcare, education, and everyday life.
“””

default_summary = summarizer(
text,
max_length=250,
min_length=120,
do_sample=False
)

creative_summary = summarizer(
text,
max_length=250,
min_length=120,
do_sample=True,
temperature=0.9
)

print(“nORIGINAL TEXT:n”)
print(text)

print(“nDEFAULT SUMMARY:n”)
print(default_summary[0][“summary_text”])

print(“nCREATIVE SUMMARY:n”)
print(creative_summary[0][“summary_text”])

————————————–Program 8——————————————————

!pip install langchain cohere langchain-community

from langchain import PromptTemplate
from langchain.llms import Cohere
import getpass

text = open(“/content/drive/My Drive/Teaching.txt”).read()

llm = Cohere(
cohere_api_key=getpass.getpass(“API Key: “),
model=”command”
)

prompt = PromptTemplate(
input_variables=[“text”],
template=”Summarize, give 3 key points and sentiment:n{text}”
)

print(llm.predict(prompt.format(text=text)))

————————————Program 9———————————————————-

from google.colab import drive
drive.mount(‘/content/drive’, force_remount=True)

!pip install wikipedia-api pydantic

from pydantic import BaseModel
import wikipediaapi

class Institution(BaseModel):
founder:str=None
founded:str=None
branches:list=None
employees:int=None
summary:str=None

def parser(page):
return Institution(
founder=”N/A”,
founded=”N/A”,
branches=[],
employees=None,
summary=page.summary[:500]
)

name = input(“Enter Institution Name: “)

wiki = wikipediaapi.Wikipedia(
user_agent=”MyApp/1.0″,
language=”en”
)

page = wiki.page(name)

if page.exists():
result = parser(page)

print(“nFounder:”, result.founder)
print(“Founded:”, result.founded)
print(“Branches:”, result.branches)
print(“Employees:”, result.employees)
print(“Summary:”, result.summary)
else:
print(“Institution not found.”)

—————————-Program 10——————————————-

!pip install langchain-cohere wikipedia-api

from langchain_cohere import ChatCohere
import wikipediaapi,getpass

llm = ChatCohere(
cohere_api_key=getpass.getpass(“API Key: “),
model=”command-a-03-2025″
)

ipc = wikipediaapi.Wikipedia(
user_agent=”IPCBot”,
language=”en”
).page(“Indian Penal Code”).summary

q = input(“Ask IPC Question: “)

response = llm.invoke(
f”IPC Info:n{ipc}nnQuestion: {q}nAnswer:”
)

print(“nChatbot Response:n”)
print(response.content)

————————————END—————————————————

 

 

 

  • genai67
  • none/plain text
  • Never
Share This: