Turn a whole book into a queryable knowledge graph in R
About forty lines of R convert Christoph Molnar’s Interpretable Machine Learning into an Open Knowledge Format bundle. The okf package then loads it into DuckDB, checks it, draws the graph and searches it, with data.table doing the querying.
A long technical book is good to read and awkward to query. Which chapters cover local explanation methods? Where exactly is the Shapley value explanation? What links to what? This post turns a book into a small knowledge graph you can query with data.table and search by meaning, deterministically, with no language model deciding what the structure is.
The book is Christoph Molnar’s Interpretable Machine Learning, whose Quarto sources are public under CC BY-NC-SA. The tool is the R package okf from okf-ingest, which reads an Open Knowledge Format bundle into a DuckDB catalog. Disclosure: I wrote okf-ingest.
OKF itself is a short convention. A bundle is a folder of markdown files, one concept per file, each with YAML frontmatter. The only required field is type. Ordinary markdown links are the graph. Two filenames are reserved: index.md, the map, and log.md, the history.
Step 1: install, and get the book
install.packages("okf", repos = c(
travisjakel = "https://travisjakel.r-universe.dev",
CRAN = "https://cloud.r-project.org"
))CRAN carries an older release of okf. This post needs the r-universe build.
git clone --depth 1 https://github.com/christophM/interpretable-ml-book srcStep 2: make it OKF
This is the only conversion step. The book is 47 Quarto chapters grouped into Parts. Each chapter becomes a concept whose type is its Part, with a title and a one-sentence description taken from its first line of prose. Each Part becomes a concept that links to its chapters, and index.md links to the Parts, so the folder has a real graph instead of a flat list.
src <- "src/manuscript"; out <- "iml-okf"; at <- "2026-07-07T00:00:00Z" # the book's last commit
parts <- list(
"Foundations" = c("intro","interpretability","goals","overview","data"),
"Interpretable Models" = c("limo","logistic","extend-lm","tree","rules","rulefit"),
"Local Model-Agnostic Methods" = c("ceteris-paribus","ice","lime","counterfactual","anchors","shapley","shap"),
"Global Model-Agnostic Methods" = c("pdp","ale","interaction","decomposition","feature-importance","lofo","global","proto"),
"Neural Network Interpretation" = c("cnn-features","pixel-attribution","detecting-concepts","adversarial","influential"),
"Beyond the Methods" = c("evaluation","storytime","future","translations"),
"Back Matter" = c("cite","acknowledgements"),
"Appendix" = c("what-is-machine-learning","math-terms","r-packages","references"))
unlink(out, recursive = TRUE); dir.create(out)
pslug <- function(p) paste0("part-", gsub("[^a-z0-9]+", "-", tolower(p)))
yq <- function(s) paste0("'", gsub("'", "''", s, fixed = TRUE), "'") # YAML single-quoted string
clean <- function(x) { # keep prose; links come from structure
x <- x[!grepl("^\\s*(\\{\\{<|:::)", x)] # drop Quarto directives
x <- sub("\\s*\\{#[^}]+\\}\\s*$", "", x) # strip {#label} from headings
x <- gsub("!\\[[^]]*\\]\\([^)]*\\)", "", x) # remove image embeds
gsub("\\[([^]]+)\\]\\([^)]*\\)", "\\1", x) # de-link to prose
}
first_sentence <- function(body) { # becomes the description
ln <- body[nzchar(trimws(body)) & !startsWith(body, "#")][1]
if (is.na(ln)) "" else substr(sub("([.!?]).*$", "\\1", trimws(ln)), 1, 200)
}
fm <- function(type, title, desc) c(
"---", paste0("type: ", type), paste0("title: ", yq(title)), paste0("description: ", yq(desc)),
sprintf('generated: { by: "process:convert", at: "%s" }', at),
"tags: [interpretable-ml]", "---", "")
put <- function(name, lines) { # UTF-8, LF line endings
con <- file(file.path(out, name), "wb"); on.exit(close(con))
writeLines(enc2utf8(lines), con, sep = "\n", useBytes = TRUE)
}
for (part in names(parts)) for (stub in parts[[part]]) { # one concept per chapter
raw <- readLines(file.path(src, paste0(stub, ".qmd")), warn = FALSE, encoding = "UTF-8")
h1 <- grep("^#\\s", raw, value = TRUE)[1] # three chapters have no H1
title <- if (is.na(h1)) stub else trimws(gsub("\\{#[^}]+\\}", "", sub("^#\\s+", "", h1)))
body <- clean(raw)
put(paste0(stub, ".md"), c(fm(part, title, first_sentence(body)), body))
}
for (part in names(parts)) # one concept per Part
put(paste0(pslug(part), ".md"), c(fm("Part", part, sprintf("Chapters in the %s part.", part)),
paste0("# ", part), "", sprintf("- [%s](%s.md)", parts[[part]], parts[[part]])))
put("index.md", c("---", 'okf_version: "0.3"', "title: Interpretable Machine Learning", # bundle metadata
"description: Christoph Molnar's book on making black box models explainable, one concept per chapter.",
"license: CC-BY-NC-SA-4.0", "---", "",
"# Interpretable Machine Learning", "", sprintf("- [%s](%s.md)", names(parts), pslug(names(parts)))))
put("log.md", c("# Bundle history", "", "## 2026-11-30", "",
"- Converted from the Quarto sources of *Interpretable Machine Learning*."))Two details follow OKF v0.3. The root index.md carries bundle metadata, including the book’s licence. And log.md has no frontmatter and dates its entries with ## YYYY-MM-DD headings; a log with frontmatter is a conformance error in v0.3.
Step 3: ingest, and query it with data.table
library(okf)
library(DBI)
library(data.table)
res <- okf_ingest("iml-okf", db_path = "iml.duckdb")
as.data.table(res$summary[c("n_concepts", "conformant", "errors", "warnings", "links_total", "links_broken")])
#> n_concepts conformant errors warnings links_total links_broken
#> 1: 49 TRUE 0 0 49 0
con <- res$con49 concepts: 41 chapters and 8 Part pages, conformant, with no broken links. res$con is an ordinary DuckDB connection, so the rest is DBI and data.table. Where does the book spend its words?
concepts <- as.data.table(dbGetQuery(con, "SELECT path, type, title, length(body) AS chars
FROM okf_concept WHERE NOT reserved"))
concepts[, .(chapters = .N, chars = sum(chars)), by = type][order(-chars)]
#> type chapters chars
#> 1: Interpretable Models 6 171156
#> 2: Global Model-Agnostic Methods 8 170853
#> 3: Local Model-Agnostic Methods 7 160891
#> 4: Neural Network Interpretation 5 115830
#> 5: Foundations 5 78995
#> 6: Beyond the Methods 4 39440
#> 7: Appendix 4 5472
#> 8: Back Matter 2 3527
#> 9: Part 8 1340
concepts[type == "Local Model-Agnostic Methods", .(title, chars)][order(-chars)]
#> title chars
#> 1: LIME 31456
#> 2: SHAP 31424
#> 3: Counterfactual Explanations 28784
#> 4: Shapley Values 25364
#> 5: Scoped Rules (Anchors) 20175
#> 6: Ceteris Paribus Plots 14358
#> 7: Individual Conditional Expectation (ICE) 9330Step 4: health check
okf_doctor() goes past conformance: duplicate titles, orphans, missing recommended fields, stale timestamps, links to deprecated concepts.
d <- okf_doctor(con)
d$score
#> [1] 100
length(d$by_rule)
#> [1] 0A clean score, and it was not clean on my first attempt. Three chapters of the book start at a level-two heading, so my first converter gave all three the title NA. The bundle was still conformant. okf_doctor() scored it 94 and named the rule, duplicate_title, which is how I found the bug. The fallback to the file name in the loop above is the fix.
Step 5: see it
okf_graph_html(con, "iml-graph.html")
#> [okf_graph_html] wrote iml-graph.html (51 nodes, 49 edges)
The output is one self-contained HTML page with no external scripts. You can pan, zoom and search it.
Step 6: ask it a question
Embedding is the one place a model is used, and it is optional. okf_embed() chunks the chapter text and embeds it with a local model (Ollama’s nomic-embed-text by default), storing the vectors in the same DuckDB file.
okf_embed(con)
#> [1] 1369
hits <- as.data.table(okf_rag(con, "How are Shapley values used to explain a prediction?", k = 4))
hits[, .(score = round(score, 3), path, title)]
#> score path title
#> 1: 0.852 shapley.md Shapley Values
#> 2: 0.848 shapley.md Shapley Values
#> 3: 0.846 shapley.md Shapley Values
#> 4: 0.844 shapley.md Shapley Values1,369 chunks, and all four hits are passages of the Shapley Values chapter.
The same bundle from Python
okf-ingest has a Python package with the same functions and the same catalog tables. I ran the Python version of this converter on the same book: it wrote the same 51 files, byte for byte, and its catalog gave the same counts, the same health score and the same four search hits with the same scores. A companion post walks through that side.
Why not let a model read the book?
Because nothing here asks a model what the structure is. The graph is exactly the structure the author wrote down in the book’s table of contents. The same sources always give the same catalog, the same graph and the same health score, which means you can assert on them in a test. A model enters only at the embedding step, and only if you want it.
okf-ingest is open source (Apache-2.0): GitHub, r-universe. The book is Interpretable Machine Learning by Christoph Molnar, used here under CC BY-NC-SA for demonstration. The converted bundle is not redistributed; the code above rebuilds it from the author’s repository. Read the real thing at https://christophm.github.io/interpretable-ml-book/.
Run with okf 0.14.2 installed from r-universe, R 4.5.0, duckdb 1.3.2 and data.table 1.17.6, against the book repository at commit 8f470c8. Embeddings came from nomic-embed-text on a local server. The script that produced every output above is in this blog’s repository under _runs/okf_r_book.R.