{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Cancer Knowledge Base — quickstart (3 minutes)\n", "\n", "The open, **CC-BY-4.0**, **de-identified** oncology knowledge base: 58 documents, 402 sections, 175 guideline statements (NCCN/ESMO/ASCO/USPSTF/WHO), 115 evidence rows with verified **PMID/NCT/citation URLs**, 4,728 code-anchored glossary terms across **9 locales**, and a **provable 152-question MCQ benchmark** with `golden_docs`.\n", "\n", "**Dataset card**: https://huggingface.co/datasets/ranjithraj/cancer-knowledge-base\n", "**Repo**: https://gitlab.com/ranjithraj/cancer-knowledge-base\n", "\n", "In 3 minutes you will:\n", "1. Load the knowledge base\n", "2. Explore guidelines + verified trial citations\n", "3. Run BM25 retrieval over the benchmark pool\n", "4. Reproduce the benchmark baseline\n", "5. Peek at the multilingual glossary\n", "\n", "_Educational reference only — not medical advice._" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip -q install pandas pyarrow" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "HF = \"hf://datasets/ranjithraj/cancer-knowledge-base\"\n", "\n", "documents = pd.read_parquet(f\"{HF}/documents.parquet\")\n", "guidelines = pd.read_parquet(f\"{HF}/guidelines.parquet\")\n", "evidence = pd.read_parquet(f\"{HF}/evidence_levels.parquet\")\n", "mcq = pd.read_parquet(f\"{HF}/mcq_questions.parquet\")\n", "glossary = pd.read_parquet(f\"{HF}/glossary.parquet\")\n", "\n", "print(f\"documents: {len(documents)} | guidelines: {len(guidelines)} | evidence: {len(evidence)} | MCQs: {len(mcq)} | glossary terms: {len(glossary)}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Explore the knowledge base" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "documents[[\"path\", \"title\", \"category\"]].head(8)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Every guideline statement for breast cancer, with provenance\n", "guidelines[guidelines.source == \"know/breast-ref.md\"].head(5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Verified citations: 110/115 evidence rows carry PMID + NCT + URL\n", "cited = evidence[evidence.pmid.notna()]\n", "print(f\"evidence rows with verified citation: {cited.shape[0]}/{len(evidence)}\")\n", "cited[[\"entity\", \"entity_type\", \"pmid\", \"nct\", \"citation_url\"]].head(5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Run BM25 retrieval over the benchmark pool" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import re, math\n", "from collections import Counter\n", "\n", "pool = pd.read_parquet(f\"{HF}/benchmark/retrieval_pool.parquet\")\n", "print(f\"retrieval pool: {len(pool)} chunks\")\n", "\n", "def tokenize(t):\n", " stop = set(\"a an and are as at be by for from has have in is it of on or that the this to was were with which who will you your we they their its not no but than what when where how do does did can could should may might about into over under\".split())\n", " return [w for w in re.findall(r\"[a-z0-9]+\", t.lower()) if w not in stop and len(w) > 1]\n", "\n", "docs = [tokenize(c) for c in pool.text]\n", "N = len(docs); avgdl = sum(len(d) for d in docs) / max(N, 1)\n", "df = Counter(t for d in docs for t in set(d))\n", "idf = {t: math.log(1 + (N - f + 0.5) / (f + 0.5)) for t, f in df.items()}\n", "\n", "def bm25(query, k=3, k1=1.5, b=0.75):\n", " q = tokenize(query)\n", " scores = []\n", " for i, d in enumerate(docs):\n", " tf = Counter(d); s = 0.0\n", " for t in q:\n", " if t not in idf or t not in tf: continue\n", " f = tf[t]\n", " s += idf[t] * (f * (k1 + 1)) / (f + k1 * (1 - b + b * len(d) / avgdl))\n", " scores.append((s, i))\n", " scores.sort(reverse=True)\n", " return [i for _, i in scores[:k]]\n", "\n", "for q in [\"What is the first-line treatment for RAS wild-type left-sided mCRC?\",\n", " \"Adjuvant osimertinib for EGFR-mutant NSCLC\",\n", " \"BCLC stage C hepatocellular carcinoma systemic therapy\"]:\n", " top = bm25(q)\n", " print(\"Q:\", q)\n", " for i in top[:2]:\n", " print(\" ->\", pool.source[i], \"|\", pool.text[i][:90].replace(chr(10), \" \"))\n", " print()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Reproduce the benchmark baseline" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bench = pd.read_parquet(f\"{HF}/benchmark/mcq_benchmark.parquet\")\n", "preds = pd.read_json(f\"{HF}/benchmark/baseline_preds.jsonl\", lines=True)\n", "\n", "merged = bench.merge(preds, on=\"question_id\", suffixes=(\"_gold\", \"_pred\"))\n", "acc = (merged.answer_index_pred == merged.answer_index_gold).mean()\n", "print(f\"BM25@top3 baseline sufficiency accuracy: {acc:.1%} (random = 25%)\")\n", "print(f\"correct: {(merged.answer_index_pred == merged.answer_index_gold).sum()}/{len(merged)}\")\n", "print(f\"retrieval@3 (golden doc in top-3): 61.8% — see benchmark card for details\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Sample the provable MCQs" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "\n", "row = mcq[mcq.id == 1].iloc[0]\n", "options = json.loads(row.options_json)\n", "print(\"Q:\", row.question)\n", "for i, opt in enumerate(options):\n", " mark = \" <-- ANSWER\" if i == row.answer_index else \"\"\n", " print(f\" {i}. {opt}{mark}\")\n", "print(\"\\ndifficulty:\", row.difficulty)\n", "print(\"evidence:\", row.evidence_level)\n", "print(\"citation:\", row.citation)\n", "print(\"golden_docs:\", row.golden_docs)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Multilingual glossary (code-anchored)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"locales:\", sorted(glossary.locale.unique()))\n", "glossary[glossary.concept.str.contains(\"breast\", case=False, na=False)].groupby(\"locale\").first().reset_index()[[\"locale\", \"concept\", \"code\", \"local_term\"]].head(9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Next steps\n", "\n", "- Score **your own** RAG/LLM: clone the repo and run `python3 scripts/eval_mcq.py --predictions preds.jsonl`\n", "- Audit a synthetic oncology dataset against this KB (validation scorecards for CancerGUIDE / OncoBench / MedGUIDE)\n", "- Use the 9-locale code-anchored glossary for localized oncology content\n", "\n", "Cite it:\n", "```bibtex\n", "@misc{cancer-knowledge-base-2026,\n", " title={{Cancer Knowledge Base}: an open, verified, provable oncology KB for RAG and LLM evaluation},\n", " author={Ranjithraj, R},\n", " year={2026},\n", " howpublished={\\url{https://huggingface.co/datasets/ranjithraj/cancer-knowledge-base}}}\n", "```" ] } ], "metadata": { "colab": {"provenance": []}, "kernelspec": {"display_name": "Python 3", "name": "python3"}, "language_info": {"name": "python"} }, "nbformat": 4, "nbformat_minor": 0 }