To generate embeddings for a list of entities from a Knowledge Graph (KG), follow these steps:
- Load entities: Prepare a list of entity URIs (e.g., from a CSV/TSV).
- Define the KG: Initialize a
KG object using a SPARQL endpoint or a local file. - Configure the Transformer: Create an
RDF2VecTransformer by specifying an embedder (e.g., Word2Vec) and a walking strategy (e.g., RandomWalker). - Run transformation: Call
fit_transform(knowledge_graph, entities) to obtain the embeddings and associated literals.
Tip: For better accuracy in most datasets, set with_reverse=True in your walking strategy (like RandomWalker) to allow the model to learn from both parents and children.
import pandas as pd
from pyrdf2vec import RDF2VecTransformer
from pyrdf2vec.embedders import Word2Vec
from pyrdf2vec.graphs import KG
from pyrdf2vec.walkers import RandomWalker
# 1. Load entities
data = pd.read_csv("samples/countries-cities/entities.tsv", sep="\t")
entities = [entity for entity in data["location"]]
# 2. Define Knowledge Graph (SPARQL endpoint)
knowledge_graph = KG(
"https://dbpedia.org/sparql",
skip_predicates={"www.w3.org/1999/02/22-rdf-syntax-ns#type"},
literals=[
["http://dbpedia.org/ontology/wikiPageWikiLink", "http://www.w3.org/2004/02/skos/core#prefLabel"],
["http://dbpedia.org/ontology/humanDevelopmentIndex"],
],
)
# 3. Create transformer
transformer = RDF2VecTransformer(
Word2Vec(epochs=10),
walkers=[RandomWalker(4, 10, with_reverse=True, n_jobs=2)],
)
# 4. Get embeddings and literals
embeddings, literals = transformer.fit_transform(knowledge_graph, entities)