JustPaste
HomeCategoriesAboutDonateContactTerms of UsePrivacy Policy
JustPaste

Free online notepad — write and share instantly

Navigate

  • Home
  • Timeline
  • Categories

Info

  • About
  • Donate
  • Contact

Legal

  • Terms of Use
  • Privacy Policy

© 2026 JustPaste.app. All rights reserved.

Made with ♥ by JustPaste

siri | JustPaste.app
28 days ago6 views
👨‍💻Programming

siri

prog 1

!pip install gensim

import gensim.downloader as api

print("Loading model... (This may take a while)")
m = api.load("word2vec-google-news-300")
print("Model loaded!")

# Similar words
print("\nWords similar to 'king':")
for word, score in m.most_similar("king")[:5]:
    print(f"{word}: {score:.4f}")

# Word arithmetic
result = m.most_similar(
    positive=['woman', 'king'],
    negative=['man']
)

print(f"\n'king' - 'man' + 'woman' = '{result[0][0]}' (Most similar word)")

# Similarity
sim = m.similarity("king", "queen")
print(f"\nSimilarity between 'king' and 'queen': {sim:.4f}")

# Odd one out
odd = m.doesnt_match(["apple", "banana", "grape", "car"])
print(f"\nOdd one out from ['apple', 'banana', 'grape', 'car']: {odd}")
-------------------------------------------------------------------------------------------------------------------------------
prog 2

!pip install gensim

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

print("Loading model . (This may take a while)")
model = api.load("word2vec-google-news-300")
print("Model loaded!")

tech_words = ["computer", "algorithm", "software", "hardware", "AI", "cloud", "database", "network", "cybersecurity", "encryption"]

word_vectors = np.array([model[word] for word in tech_words])

pca = PCA(n_components=2)
reduced_vectors = pca.fit_transform(word_vectors)

plt.figure(figsize=(8,6))
for word, (x,y) in zip(tech_words, reduced_vectors):
    plt.scatter(x, y)

    plt.text(x+0.02, y+0.02, word, fontsize=12)

plt.title("2D Visualization of Technology Word Embeddings")
plt.xlabel("PCA Component 1")
plt.ylabel("PCA Component 2")
plt.grid()
plt.show()

print("\nWords similar to 'king':")
for word, score in model.most_similar("king")[:5]:
    print(f"{word}: {score:.4f}")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

prog 3

!pip install gensim
from gensim.models import Word2Vec
import nltk, matplotlib.pyplot as plt
from nltk.tokenize import word_tokenize
from sklearn.manifold import TSNE

nltk.download('punkt'); nltk.download('punkt_tab')
corpus = ["The doctor diagnosed the patient with diabetes.", "Insulin is used to treat diabetes.", "A cardiologist specializes in heart diseases.", "Patients with hypertension should reduce salt intake.", "Antibiotics treat bacterial infections.", "Vaccines help build immunity.", "Surgery removes tumors.", "A neurologist treats nervous system disorders."]

model = Word2Vec(sentences=[word_tokenize(s.lower()) for s in corpus], vector_size=50, window=5,
min_count=1, workers=4)
model.save('medical_word2vec.model')
words = list(model.wv.index_to_key)
r = TSNE(n_components=2, random_state=42).fit_transform(model.wv[words])
plt.figure(figsize=(12, 8))
for i, w in enumerate(words):
    plt.scatter(*r[i], s=120, zorder=3)
    plt.annotate(w, r[i], textcoords="offset points", xytext=(10, 5), fontsize=11, fontweight='bold',
    bbox=dict(boxstyle="round,pad=0.3", fc="lightyellow", ec="gray", alpha=0.8))
plt.title("Word Embeddings Visualization")
plt.tight_layout(); plt.show()
print(f"Words similar to 'diabetes':")
[print(f"{w} (Similarity: {s:.2f})") for w,s in model.wv.most_similar("diabetes", topn=5)]
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

prog 4

!pip install gensim
import gensim.downloader as api
from transformers import pipeline

# Load embedding model
embedding_model = api.load("glove-wiki-gigaword-100")

original_prompt = "Describe the beautiful landscapes during sunset."

def enrich_prompt(prompt, embedding_model, n=5):
    words = prompt.split()
    enriched_prompt = []
    for word in words:
        word_lower = word.lower()
        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: # Keep the word as is if not found
            enriched_prompt.append(word)
    return " ".join(enriched_prompt)

enriched_prompt = enrich_prompt(original_prompt, embedding_model)

# Load text generation model
generator = pipeline("text-generation", model="gpt2")

# 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'])
print("\nEnriched prompt response")
print(enriched_response[0]['generated_text'])
-----------------------------------------------------------------------------------------------------------------------------------------------------------

prog 5

import gensim.downloader as api

# Load pre-trained model
model = api.load("glove-wiki-gigaword-100")

# Input seed word
seed_word = input("Enter a seed word: ")

# Get similar words
similar_words = [word for word, score in model.most_similar(seed_word, topn=4)]

# Generate story
story = f"""
Once upon a time, a {seed_word} embarked on a journey.
Along the way, it encountered {similar_words[0]}, which led it to a hidden {similar_words[1]}.
Despite the challenges, it found {similar_words[2]} and embraced the adventure with {similar_words[3]}.
In the end, the journey was a tale of mystery and discovery.
"""

print("\nGenerated Story:")
print(story)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
prog 6

from transformers import pipeline
sentiment_analyzer = pipeline("sentiment-analysis")
def analyze_sentiment(text):
    r = sentiment_analyzer(text)[0]
    return f"Sentiment: {r['label']} (Confidence: {r['score']:.2f})"
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))
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

prog 7

from transformers import AutoTokenizer, BartForConditionalGeneration
import torch

# Load summarization model
print("Loading Summarization Model (BART)...")
tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")
model = BartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")

# Function to summarize text
def summarize_text(text, max_length=None, min_length=None):

    # Remove unnecessary line breaks
    text = " ".join(text.split())

    # Encode the input text (BART typically doesn't need a special prefix for summarization)
    input_ids = tokenizer.encode(text, return_tensors="pt", max_length=1024, truncation=True)

    # Auto-adjust summary length based on text size
    if max_length is None:
        max_length = min(input_ids.shape[-1] // 3, 150)
    if min_length is None:
        min_length = max(30, max_length // 3)

    # Generate summary using model.generate directly
    summary_ids = model.generate(
        input_ids,
        max_length=max_length,
        min_length=min_length,
        do_sample=False, # Use greedy decoding for a deterministic summary
        num_beams=1,     # Only 1 beam for greedy decoding
        early_stopping=True
    )

    # Decode the generated summary
    summary_text = tokenizer.decode(summary_ids[0], skip_special_tokens=True)

    print("\nOriginal Text:")
    print(text)

    print("\nSummarized Text:")
    print("\nDefault:")
    print(summary_text)


# Example long text
long_text = """
Artificial Intelligence (AI) is a rapidly evolving field of computer science
focused on creating intelligent machines capable of mimicking human cognitive
functions such as learning, problem-solving, and decision-making. In recent
years, AI has significantly impacted various industries, including healthcare,
finance, education, and entertainment. AI-powered technologies, such as chatbots,
self-driving cars, and recommendation systems, have transformed the way we
interact with technology. Machine learning and deep learning, subsets of AI,
enable systems to learn from data and improve over time without explicit programming.
However, AI also poses ethical challenges, such as bias in decision-making and
concerns over job displacement. As AI technology continues to advance, it is
crucial to balance innovation with ethical considerations to ensure responsible
development and deployment.
"""

# Summarize the passage
summarize_text(long_text)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
← Back to timeline