File size: 2,217 Bytes
97aae78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import torch
from transformers import AutoTokenizer, AutoModel
from sentence_transformers import SentenceTransformer
import networkx as nx
import matplotlib.pyplot as plt

# Load pre-trained model and tokenizer
model_name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)

# Function to get embeddings
def get_embeddings(texts):
    inputs = tokenizer(texts, return_tensors="pt", padding=True, truncation=True, max_length=512)
    with torch.no_grad():
        outputs = model(**inputs)
    return outputs.last_hidden_state[:, 0, :].numpy()

# Sample data (replace with your own data import)
documents = [
    "The quick brown fox jumps over the lazy dog.",
    "A journey of a thousand miles begins with a single step.",
    "To be or not to be, that is the question.",
    "All that glitters is not gold.",
]

# Get embeddings for documents
embeddings = get_embeddings(documents)

# Create graph
G = nx.Graph()

# Add nodes and edges based on cosine similarity
threshold = 0.5  # Adjust this threshold as needed
for i in range(len(documents)):
    G.add_node(i, text=documents[i])
    for j in range(i+1, len(documents)):
        similarity = torch.cosine_similarity(torch.tensor(embeddings[i]), torch.tensor(embeddings[j]), dim=0)
        if similarity > threshold:
            G.add_edge(i, j, weight=similarity.item())

# Visualize the graph
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=500, font_size=8, font_weight='bold')
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.title("Document Similarity Graph")
plt.show()

# Example of querying the graph
query = "What is the meaning of life?"
query_embedding = get_embeddings([query])[0]

# Find most similar document
similarities = [torch.cosine_similarity(torch.tensor(query_embedding), torch.tensor(emb), dim=0) for emb in embeddings]
most_similar_idx = max(range(len(similarities)), key=similarities.__getitem__)

print(f"Most similar document to the query: {documents[most_similar_idx]}")

# You can extend this to implement more complex graph-based retrieval algorithms