Machine Learning Models in Knowledge Graphs

This article accompanies my new book, Semantic Webs of Meaning: Building Contextual Knowledge Graphs for Deduction and Integration published by Technics Publications. This is an extension to the topic, Machine Learning Models as Data Products, on page 173. In that topic, iris.py is an example of a Python program that creates an ML model (a k-means cluster created from the iris data set) and converts it into an RDF/turtle file. In this article, I wish to offer an example of creating related graphs in a distributed manner.

I wrote this article such that it can stand on its own, apart from the book. However, I do assume some familiarity with concepts covered in Semantic Webs of Meaning. For example, RDF, Protégé, knowledge graphs, turtle, IRI, and Jena Fuseki. You do not need to be an expert in any of them, but it will help to have a good idea of what the following terms listed in Table 1a and Table 1b mean.

TermWhat you need to know for this article
Knowledge graphA graph of things and the meaningful relationships among them. In this article, the ML model itself becomes one of those things.
RDFThe basic subject-predicate-object model used to express the knowledge in the graph.
TurtleA human-readable syntax for writing RDF. The generated files in this exercise are expressed in Turtle.
IRIA globally identifiable name for a resource. A major point of the exercise is linking locally generated concepts to known IRIs in resources such as Wikidata.
Class / IndividualA class describes a kind of thing; an individual represents one particular thing. In this article, Machine Learning Model is a class, while the specific Iris KMeans Model created by iris.py is an individual of that class. Very similar to the concept of class and instance in object-oriented programming.
ProtégéThe ontology editor used here to inspect and visualize the generated RDF.
RDFS / OWLSemantic Web vocabularies used to express things such as classes, subclasses, individuals, and relationships. You do not need much OWL knowledge to follow the exercise, but you will see constructs such as rdfs:seeAlso, owl:Class, and owl:NamedIndividual.
SPARQLThe query language for RDF graphs. It becomes important when we query the resulting knowledge graph.
Apache Jena FusekiThe RDF server used later to load the graph and execute SPARQL queries and Jena rules.
Table 1a – Semantic Web terms mentioned in the book.
ML termMeaning here
k-meansAn algorithm that divides observations into groups, or clusters, based on similarity.
ClusterOne of the groups discovered by the k-means model.
CentroidThe center of a cluster. In this example, the centroid contains representative sepal and petal measurements.
FeatureAn input variable used by the ML algorithm, such as sepal length or petal width.
ModelThe trained result produced by the ML process. Importantly for this article, the model is represented in the knowledge graph as an individual in its own right.
Table 1b – Machine learning terms mentioned in the book.

The value of this exercise is to demonstrate a concept, which is the automatic generation of business rules into an enterprise knowledge graph. Composing knowledge graphs (KG) is generally a meticulous, tedious process. Any automation (and I describe a few methods in the book), eases that burden. In this case, employing LLMs into this process, but within its comfort zone.

Normally, I would post this exercise on the book’s accompanying GitHub repo. However, given the book’s very recent publication, I decided to post this article here to draw awareness to the book and the repo.

Notes:

  • Some of the figures are very busy. For a full view, click on the Figure, and hit the Browser’s back arrow to return to the this article.
  • If purchasing the book from the Technics Publications website, use the code TP25 for a 25% discount.
  • The file, iris_rdf.rdf, should really be iris_rdf.ttl. This example has been a part of my “presentation” arsenal for years. Back then, that was the file name, and it got into the book with that name.

Business Rules in the Knowledge Graph

ML models could be thought of as business rules, or at least potential business rules. For example, a business rule might be to offer a discount to a customer based on the relationship with customer, the severity of the issue, whether it was our mistake, etc. We can plug in “great customer”, “critical”, and “our fault” into a function and out pops a percentage discount. But determining those three inputs are each business rules themselves. What are the criteria for a great customer, a critical issue, and whether a problem was our fault?

Business rules affect a business, therefore ML models and all forms of business rules should be incorporated into an enterprise knowledge graph (EKG)—a KG encoding anything related to our business.

Before looking at iris.py, there is an important KG modeling concept to discuss—classes and instances/individuals. A class describes a kind of thing, an individual represents a particular thing. For example, Machine Learning Model is a class, while the particular Iris k-means model created by iris.py is an individual of that class. There may be many machine-learning models, and even many models created using k-means, but this trained model is one specific thing with its own training data, parameters, learned clusters, provenance, and other properties.

One important point about iris.py is that its primary output is not just a k-means model of the Iris dataset itself. It is intended to say things about a particular machine-learning model created from that dataset and link it to known resources. The ML model is therefore represented as an individual in the KG, much as a particular company, person, building, or software system would be represented as an individual.

Modeling the trained model as an individual gives us a node to which all of that knowledge can be attached. The algorithm, dataset, model file, learned clusters, metrics, dates, and other information can describe or relate to this particular model rather than describing machine-learning models in general.

That gives us a place to attach knowledge about the model: which algorithm produced it, which features were used, which dataset it was trained from, when it was created, what clusters it discovered, the centroids of those clusters, evaluation information, and other provenance or model metadata. The learned clusters can then be related back to this specific model rather than existing as unexplained concepts floating in the graph.

This is important because the RDF is not trying to replace the executable ML model. It is creating a semantic representation of the model and what the model learned. Once represented this way, the model becomes another thing the KG can describe, relate to other things, query, reason about, and connect to shared knowledge outside the local system.

Please see Appendix E – Clustering Models for an idea of how the iris k-means model could be implemented in a KG for querying (executing the model to make a prediction) using SWRL. And there is an exercise using Jena rules for Iris.

We start with a Turtle encoding of a k-means model created by a Python script named iris.py:

  1. Uses the famous iris data set to generate an ML model using the k-means algorithm.
  2. That is serialized into iris_k-means_model.pkl.
  3. Generates a turtle file, iris_rdf.rdf, that reflects the k-means model.

Per #1, Table 2 lists the first few rows from the iris data set (Fisher’s Iris data (UCI / scikit-learn ordering):

sepal length (cm)sepal width (cm)petal length (cm)petal width (cm)species
5.13.51.40.2setosa
4.93.01.40.2setosa
4.73.21.30.2setosa
4.63.11.50.2setosa
5.03.61.40.2setosa
Table 2 – First few rows of the iris data set.

iris.py is actually coded by an LLM from a prompt and the iris data set. That’s just one relatively meaningless example. At scale, the data sets and requirements will constantly shift. Meaning, there will be a need to create and maintain dozens, if not hundreds of Python scripts. So the assistance from LLMs is crucial.

Figure 1 outlines the process as we’re covering it in this article.

  1. The iris data set is fed into the iris.py program.
  2. The iris.py program discovers clusters within the iris data set, and creates a turtle file of the metadata.
  3. The turtle file and an LLM prompt of instructions are submitted to an LLM to link resources to IRI.
  4. The result is returned as a turtle file, a supplement to the turtle file generated by iris.py.
This image has an empty alt attribute; its file name is image-40.png
Figure 1 – Narrower process –iris data set to world links.

iris.py handles quite a bit, but it is specialized for this particular dataset and example. It discovers clusters based on the sepal and petal measurements. The somewhat coerced part is that it then names those clusters using the species that happen to be dominant within them. That happens to work out nicely with the Iris dataset, since the clusters correspond closely to the known species. You might think of that part as the model validating the existing species designations rather than independently discovering and naming them.

In a more automated process, the cluster name would not need to come from a preexisting label such as species. A reasonable default would be to name the cluster from whatever characteristic distinguishes it most strongly from the others. That might be a dominant categorical feature, an unusually high or low metric, or some combination of attributes that most clearly describes the cluster. The name would therefore be a generated shorthand for the most noticeable pattern in the cluster, not necessarily a formal semantic classification. It could later be refined, mapped to a known concept, or replaced during human review.

Alternatively, is it possible to ask an LLM to directly do everything that iris.py does? Yes. However, relying on an LLM to generate the iris_rdf.rdf file directly is currently beyond the level of reliability of LLMs, at the time of writing. But an LLM can generate a starting version of the python and validate/test it in a human-supervised manner. That’s probably what the LLM will do anyway if asked to create the file.

Figure 2 illustrates a more robust process, which I intend to cover in the future.

Figure 2 – Process from data set to world links.

Here are the descriptions of the items in Figure 2:

  1. Input — Supply the prompt, source dataset, and configuration identifying which columns are features and which are metrics or targets.
  2. Detect Best ML Algorithms — Inspect the configured data—feature types, ranges, distributions, cardinality, target characteristics, and other properties—to determine which ML algorithms are appropriate candidates.
  3. Create ML Models — Run the corresponding ML functions to train, test, validate, and evaluate the candidate models, including the MLflow-like lifecycle needed to produce usable model artifacts.
  4. ML Model — Produce the selected trained model and its relevant learned structure, parameters, metrics, and other metadata needed for semantic representation.
  5. Transform to RDF/Turtle — Pass the model to its corresponding transformation function, which expresses the learned model and its important properties as RDF/Turtle. A script such as iris.py may perform both model creation and this transformation.
  6. Model Turtle + Prompt — Combine the generated Turtle representation with a prompt that tells the LLM what kinds of concepts or terms should be identified for connection to external knowledge.
    • Note that as of February 2026, LLMs such as Grok and ChatGPT were fairly unreliable as far as matching terms to IRI. I wrote about that in my blog, Explorer Subgraph—The Dynamic Cartography of Relation Space. LLM vs Chat Window. Although the Chat access to Grok and ChatGPT appear much better at it since then, it’s still not nearly accurate enough for production. I advise the method I propose in the blog for production.
  7. Extract Salient Terms — Use the LLM to examine the model semantics and identify meaningful domain terms—classes, properties, concepts, measurements, entities, and other terms worth grounding in shared knowledge.
  8. Candidate Terms — Produce the distilled list of salient terms that should be resolved against external semantic resources.
  9. Map to IRIs — Use RAG/API access to resources such as Wikidata, DBpedia, and other shared knowledge sources to find appropriate IRIs for the candidate terms, using context to disambiguate competing possibilities.
  10. World-Linked Turtle — Generate the enriched Turtle file containing the original model semantics plus links to external IRIs, connecting the locally learned ML model to the wider Semantic Web.

Steps 2–3 are analogous to an AutoML process that determines suitable machine-learning algorithms, trains and validates candidate models, compares their performance, and produces the selected model artifacts. MLflow or a similar experiment-management system could be used underneath this process to track runs, metrics, parameters, and model versions.

Viewing the ML Model as a Graph

As we do in the book, we’ll use Standford Protégé for the rendering the sample graph.

Figure 3 shows the graph view of the turtle output of iris.py, iris_rdf.rdf. It’s fairly simple, a mini taxonomy of iris species (1) and classes for ML concepts (2).

Figure 3 – Graph view of the k-means model.

Figure 4 looks at the Iris class (1), which is a subclass of a “Flowering Plant” (2). Setosa, Versicolor, and Virginica are three species of the genus, Iris (3).

Figure 4 – Iris k-means cluster model created by iris.py displayed in Protégé.

Figure 5 highlights a class for Machine Learning Models. We’ll see in a bit (Figure 7) that this is used to say that the k-means model we created (named “Iris K-means Model”) “is a” ML model.

Figure 5 – Class describing a machine learning model.

Figure 6 is a class for Machine learned cluster (1). A “cluster” is what is discovered by the k-means algorithm applied to the iris dataset. We see that it’s not a subclass of anything (2), but there are three “instances” of it (3).

Figure 6 – Class describing a machine learning cluster using th k-means algorithm.

Figure 7 shows “individuals”, in this case, the kmeans model.

  1. Note that we switched from the Classes tab to the Individuals tab.
  2. Selected the “Iris KMeans Model” individual. This refers to the model created from the kmeans algorithm.
  3. This states: “Iris KMeans Model” is a “Machine Learning Model”.
  4. The name of the actual kmeans model, the pickle file.
Figure 7 – The instance of a k-means model.

Figure 8 shows an example of one of the clusters that belong to the “Iris KMeans Model” (Figure 7).

  1. Selected “cluster 0”, the one that happens to match versicolor, therefore it’s named after that species.
  2. Says: “Iris KMeans cluster 0” is a “Machine learned cluster” (see Figure 6).
  3. An example of one of the parameters of the cluster: the centroid sepal width is 2.748.
Figure 8 – The instance of a k-means cluster.

Linking to the Rest of the World

Most English speakers know what petals are, or at least they think they do—there are many examples of what look like petals but are actually bracts. Fewer might know what a sepal is. Petals vs. bracts doesn’t matter in casual conversation because we generally know what the other means and the difference generally doesn’t matter. That is, unless you’re a biologist, horticulturist, an AI, or like the average redditor on YouTube (hilarious).

The goal is to map ontology entities (classes, individuals, properties) in the iris_rdf.rdf file to well-known Internationalized Resource Identifiers (IRI)—for example, from Wikidata and Dbpedia. That is a tedious but conceptually straightforward process, one that isn’t readily reducible to deterministic code (Python, Java, C++, etc.). It’s just the sort of thing AI can help with, even though the results still need to be validated.

For that task, I’ve employed Grok (“Expert”), using a new private chat (so that it doesn’t leverage anything from our past conversations). As the prompt, I provided Grok with these two files listed in Table 3:

FileRole in the process
iris_rdf.rdfSemantic representation of the trained Iris K-Means model. It describes the model, its learned clusters, centroid values, model provenance, and the learned Iris classes that later stages can enrich with external meaning.
iris_create_world_links_ttl_llm_prompt.mdPrompt supplied to the LLM to examine the model RDF, identify salient domain terms, and create the world-link Turtle that connects those local concepts to external IRIs and shared knowledge resources such as Wikidata.
Table 3 – Files provided to Grok for the task of generating semantic links.

The main output from Grok, is the file, iris_rdf_world_links.ttl. This file contains the RDF equivalent of what is shown in Table 4. It did a surprisingly good job for this one-shot exercise. Table 4 lists the IRI it mapped for ontology entities it deemed useful to know:

Concept in sourceLinked fromWikidata
Flowering plant / angiospermsex:FloweringPlantQ25314
Iris (plant genus)ex:IrisQ156901
Iris setosaex:IrisCluster_SetosaLike, ex:IrisKMeansCluster_1Q894226
Iris versicolorex:IrisCluster_VersicolorLike, ex:IrisKMeansCluster_0Q164844
Iris virginicaex:IrisCluster_VirginicaLike, ex:IrisKMeansCluster_2Q7934335
Petalex:petalLengthCentroid, ex:petalWidthCentroidQ107412
Sepalex:sepalLengthCentroid, ex:sepalWidthCentroidQ107216
Machine learningex:MachineLearningModelQ2539
k-means clusteringex:IrisKMeansModel, world ontologyQ310401
Iris flower data setex:IrisKMeansModel, world ontologyQ4203254
Table 4 – IRI found by Grok

It’s important to note that these resource terms were derived from the iris_rdf.rdf file, which happens to offer many clues, such as the species names and comments. That inline documentation was provided by the iris.py program. So, you will need to provide some extra commentary in case your file doesn’t contain that sort of commentary.

Now that we have the iris_rdf_world_links.ttl file, we can import it alongside iris_rdf.rdf and see what it adds to the graph.

Figure 9 shows the import of iris_rdf_world_links.ttl into the ontology already containing iris_rdf.rdf. The world-link file is kept separate from the original model RDF, but Protégé can load and merge the two together. This lets us add links to outside resources without any changes to the Turtle originally generated by iris.py.

Figure 9 – Import iris_rdf_world_links.ttl, alongside iris_rdf.rdf.

Figure 10 shows the result of the import. The world-link ontology now appears under Direct Imports, along with its ontology IRI and the location of the Turtle file. The assertions from iris_rdf_world_links.ttl are now available alongside those from iris_rdf.rdf.

Figure 10 – This is what will show if iris_rdf_world_links.ttl was correctly imported.

Figure 11 returns to the Iris class that we saw earlier in Figure 4. The original iris_rdf.rdf file says that Iris is a class and a subclass of Flowering Plant. The imported iris_rdf_world_links.ttl file adds an rdfs:seeAlso link to Wikidata Q156901, the entry for the Iris genus. The local class is now connected to a concept outside our little Iris knowledge graph.

Figure 11 – IRI appears under the Iris node, as opposed to Figure 4.

Figure 12 shows the same thing for Setosa-like Iris. The class and its description come from iris_rdf.rdf, while the world-link file adds an rdfs:seeAlso link to Wikidata Q894226, the entry for Iris setosa. We have not replaced our local concept; we have connected it to shared knowledge about the species.

Figure 12 – IRI for “Setosa” appears.

Figure 13 shows the enrichment of the actual Iris KMeans Model individual. iris_rdf.rdf describes the local model and identifies it as a Machine Learning Model. The world-link file adds links to Wikidata for k-means clustering (Q310401) and the Iris flower dataset (Q4203254). We can therefore move from this particular trained model to information about both the algorithm that produced it and the dataset from which it was created.

Figure 13 – IRIs for k-means clustering and the Iris flower dataset now appear.

Figure 14 returns to KMeans cluster 0, the cluster that predominantly corresponds to Versicolor. The information on the left and right comes from the original model RDF: the cluster identity, centroid values, dominant species, and relationship to the learned Versicolor-like class. The world-link file adds an rdfs:seeAlso link to Wikidata Q164844 for Iris versicolor. The learned result of the ML model is therefore connected to knowledge about the real-world species it represents.

Figure 14 – IRI for Versicolor species now appears.

Figure 15 shows that the same approach can be applied to properties, not just classes and individuals. The original RDF uses sepalLengthCentroid to describe one of the measurements learned by the k-means model. The world-link file adds an rdfs:seeAlso link from that property to Wikidata Q107216 for sepal. This gives outside meaning to what would otherwise be merely a locally named data property.

Figure 15 – IRI for sepal now appears.

Conclusion

The larger point of this exercise isn’t the Iris data set or even k-means. It is the automatic generation of knowledge into a knowledge graph—a tremendously laborious and ongoing process.

A machine-learning model is particularly interesting because it represents something the machine learned from data. If that model is going to influence decisions in the business, then in an important sense it has become a business rule. It shouldn’t sit off to the side as an unexplained pickle file. The enterprise knowledge graph should know that the model exists, what it was trained from, what it learned, and how its concepts relate to the rest of what the enterprise knows.

And as much of that process as possible should be automated.

My general rule is that if a procedure can be programmed reliably, it should be programmed. There is no reason to risk “misunderstanding” and/or repeatedly ask an LLM to perform deterministic work that ordinary software can perform faster, cheaper, and more predictably. That’s what “machines” do. That is why iris.py creates the model and generates its basic RDF representation.

The LLM is useful where conventional programming becomes cumbersome. In this example, that is examining the semantic clues in the generated RDF, deciding which concepts are worth linking, finding candidate resources in places such as Wikidata, and producing the supplemental Turtle containing those links. That is a fuzzy, contextual task with enough variation that encoding every possibility procedurally would be difficult. At least for now, an LLM can serve almost like another function in the pipeline for that sort of work. The article already demonstrates this division of labor: ordinary code produces the model and its RDF, while the LLM assists with mapping the resulting concepts to outside IRIs.

That does not mean blindly accepting the LLM’s output. The mappings still require human validation. Automation moves the human away from doing all of the tedious work manually and toward reviewing the parts where judgment is actually needed.

The small demonstration here packages several steps together because that makes the idea easier to see. A production implementation should be much more loosely coupled. Model discovery and training, model management, RDF generation, semantic term extraction, IRI resolution, validation, and publication to the knowledge graph can each be separate components. Systems such as MLflow could manage the model lifecycle underneath that process.

The result is not merely documentation about an ML model. It is a way for knowledge discovered by machines to become part of the enterprise’s explicit knowledge—and, increasingly, for that process of adding knowledge to happen automatically.

Leave a comment