Data Science Technical Writing
Great analysis that nobody reads is wasted analysis. Technical writing is the skill that converts modelling work into decisions: it turns a notebook into a recommendation, a README into a handover, and a stakeholder email into a signed-off project. This lesson covers the structures, patterns, and review habits that make data science communication clear without dumbing it down.
Writing framework: audience, goal, structure
Every piece of writing starts with three decisions. Who is reading, what do you want them to do, and in what order do they need the information. A product manager evaluating a launch needs the business result and the risk first; an engineer integrating your model needs the API contract and the failure modes first; a researcher needs the method and the assumptions first. Writing one document that serves all three usually serves none of them well, so either split the audiences or write a short summary that points to the detail.
Structure follows the inverted pyramid: conclusion first, supporting evidence second, methodological detail last. Readers skim, so every heading should be a complete takeaway rather than a vague label. A section titled "Latency stayed under fifty milliseconds at the ninetieth percentile" tells the skimmer everything; a section titled "Performance" tells them nothing.
| Audience | Primary question | Lead with |
|---|---|---|
| Executive or product manager | What should we do? | Decision, impact, risk |
| Engineering partner | How do I integrate it? | Contract, limits, failure modes |
| Data science peer | Is the method sound? | Assumptions, evaluation, ablations |
| Interviewer or recruiter | Can this person do the job? | Problem, approach, quantified result |
Blog post structure for data science work
A data science blog post has a predictable skeleton: a hook that states the surprising result, the problem and constraints, the approach with the key trade-off, the results with numbers, and the lessons. Length matters less than completeness; one thousand well-aimed words beats three thousand that wander.
blog_template = """
# [Action-oriented title with a number or concrete outcome]
## Introduction (100 to 150 words)
- Hook: the surprising result or the pain the reader recognises
- Context: the real-world scenario and the data available
- Promise: what the reader will be able to do after reading
## The Problem (200 to 300 words)
- Business context and the cost of the status quo
- Why existing solutions fall short for this specific case
- Constraints: latency, privacy, interpretability, budget
## The Approach (500 to 800 words)
- Solution overview with one architecture diagram
- The central design decision and the trade-off it accepted
- Short, focused code snippets that illustrate rather than dump
## Results (300 to 500 words)
- Headline metric against a named baseline
- Ablation or sensitivity analysis
- Business translation of the metric
## Lessons (200 to 300 words)
- What worked and why
- What failed and what it taught you
- What you would do differently with another month
"""
Titles should promise something checkable. "Reducing inference latency from four hundred to forty milliseconds with ONNX quantisation" earns more trust than "Making models faster." If the title makes a claim, the article must show the measurement behind it.
Notebook storytelling
Notebooks are read linearly by humans and executed top to bottom by tools, so structure them as a narrative with interleaved markdown. Each code cell should do one thing, and each markdown cell should explain why that thing happened and what to look at in the output.
notebook_skeleton = {
"cell_1_markdown": """
# Predicting churn with gradient boosting
**Goal:** flag at-risk customers thirty days ahead for retention outreach
**Data:** 50K accounts, six months of usage and billing history
**Result:** 0.89 AUC versus a 0.82 logistic baseline; estimated $2.3M annual impact
""",
"cell_2_code": """
import pandas as pd
import numpy as np
df = pd.read_csv("data/customers.csv")
df.head()
""",
"cell_3_markdown": """
## What the tenure distribution tells us
The histogram below is bimodal: a large cohort churns in the first quarter,
and a second cohort stays for years. That split will drive our feature design,
so we bucket tenure rather than treating it as a smooth numeric.
""",
"cell_4_code": """
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
ax.hist(df["tenure_months"], bins=40, edgecolor="black")
ax.set(xlabel="Tenure (months)", ylabel="Accounts", title="Tenure distribution")
plt.show()
""",
"checklist": {
"do": [
"Restart and run all before publishing",
"Use relative paths and a requirements file",
"Add a table of contents for notebooks longer than fifteen cells",
"Keep outputs small with head, describe, or sample",
],
"avoid": [
"Forty-line cells with no explanation",
"Printed DataFrames that scroll for pages",
"Hardcoded absolute paths",
"Undefined variables that only exist from a previous session",
],
},
}
The most common notebook failure is missing narrative: a reader sees the code but not the reasoning. Write the markdown as if narrating to a colleague who cannot see your screen. State what you expected, what you saw, and what you decided to do next.
Documentation that survives handover
Documentation is a promise to your future self and your teammates. The Google-style docstring below shows the standard shape: one-line summary, extended description of side effects, typed arguments, typed returns, raised exceptions, and a runnable example. That structure is what allows tools to render it and colleagues to trust it.
def train_model(X_train, y_train, config: dict) -> dict:
"""Train a gradient boosting classifier with cross-validation.
Handles preprocessing inside the pipeline, tunes depth and learning rate
with a small grid, logs metrics to the experiment tracker, and persists
the best artefact. No global state is modified.
Args:
X_train: Training features as a DataFrame with numeric and categorical
columns already aligned to the schema in config["schema"].
y_train: Binary labels as an integer array, 0 for negative.
config: Dictionary with keys n_estimators (default 200), max_depth
(default 6), learning_rate (default 0.1), and cv_folds (default 5).
Returns:
Dictionary with keys model (fitted estimator), metrics (cross-validation
AUC mean and standard deviation), and feature_importance (Series ranked
by gain).
Raises:
ValueError: If X_train and y_train differ in length or if the label
array contains values outside {0, 1}.
Example:
>>> config = {"n_estimators": 300, "max_depth": 5, "cv_folds": 3}
>>> results = train_model(X_train, y_train, config)
>>> round(results["metrics"]["auc_mean"], 3)
0.891
"""
A README should answer five questions without requiring the reader to open code: what the project does, how to install it, how to run it, what the inputs and outputs look like, and what the current performance is. Tables work well for dataset schemas and model comparisons; keep them short and honest about weaknesses as well as strengths.
Communication patterns that reduce ambiguity
Three patterns do most of the work in clear technical prose. Lead with the answer rather than narrating your search process. Use concrete numbers instead of vague intensifiers. Explain trade-offs explicitly so the reader can judge whether your choice fits their context.
patterns = {
"lead_with_answer": {
"weak": "We experimented with several architectures before settling on one.",
"strong": "Use the quantised ONNX export: latency dropped 89 percent with a "
"0.4 point AUC cost. Here is the measurement and the failure cases.",
},
"concrete_numbers": {
"weak": "The model is significantly better than the baseline.",
"strong": "AUC improved from 0.82 to 0.89 on a stratified 20 percent holdout "
"(n equals 10,000; bootstrap 95 percent CI spans 0.87 to 0.91).",
},
"explicit_tradeoff": {
"weak": "We chose LightGBM because it is fast.",
"strong": "LightGBM trained 4x faster than the transformer and matched it "
"within 0.6 AUC points on 40K rows, so we accepted the small "
"accuracy gap to keep CPU-only serving.",
},
}
Numbers need their context attached: which split, which metric definition, which time window. A bare "0.89 AUC" invites the question you do not want to answer live in a review: compared to what?
Visualisation discipline
Charts in written work have one job: make a claim easy to verify. Give every chart a title that states the claim, axis labels with units, and a source or time range. Use colour-blind-safe palettes and annotate the point that matters rather than leaving the reader to hunt for it.
import matplotlib.pyplot as plt
import numpy as np
def plot_model_comparison(results: dict, output_path: str = "model_comparison.png"):
models = list(results.keys())
aucs = [r["auc"] for r in results.values()]
latencies = [r["latency_ms"] for r in results.values()]
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
colors = ["#2ecc71" if a > 0.85 else "#3498db" for a in aucs]
axes[0].barh(models, aucs, color=colors)
axes[0].axvline(0.85, color="red", linestyle="--", label="Target 0.85")
axes[0].set(xlabel="AUC", title="Accuracy against the 0.85 launch gate")
axes[0].legend()
axes[1].scatter(latencies, aucs, s=100)
for model, x, y in zip(models, latencies, aucs):
axes[1].annotate(model, (x, y), textcoords="offset points", xytext=(5, 5))
axes[1].set(xlabel="P90 latency (ms)", ylabel="AUC",
title="Latency versus accuracy trade-off")
fig.tight_layout()
fig.savefig(output_path, dpi=150, bbox_inches="tight")
plt.close(fig)
return output_path
results = {
"logistic": {"auc": 0.82, "latency_ms": 5},
"lightgbm": {"auc": 0.89, "latency_ms": 15},
"transformer": {"auc": 0.91, "latency_ms": 90},
}
print(plot_model_comparison(results))
Save figures as files at a stable path and reference them by relative path in the article, so the piece renders correctly when the repository moves.
Review and editing
First drafts are for thinking; revisions are for the reader. Read the piece once for structure: does the conclusion appear early, do the sections build on each other, is anything repeated? Then read once for sentences: cut hedging, replace passive voice where the actor matters, and split anything over twenty-five words. Finally read once for numbers: every figure should match the table, the code, and the text.
Ask a colleague who does not know the project to read only the headings and the conclusion. If they cannot restate the finding and the recommendation, rewrite the headings until they can.
Beyond the review cycle, build habits that make writing faster and more consistent. Maintain a personal snippet library for recurring patterns—docstring formats, README sections, methodology explanations—so you are not reinventing structure every time. Keep a list of your most common reviewer comments and address them proactively in future drafts. Over time, this reduces the number of revision cycles and makes your writing more predictable for collaborators.
When writing for external audiences, consider the publication venue. A technical blog post benefits from code blocks and a narrative flow, while a documentation page should favour reference tables and direct instructions. A conference talk or webinar abstract needs a hook and a clear takeaway in the first two sentences, because reviewers skim dozens of submissions. Tailor the same underlying content to the format rather than forcing one structure everywhere.
Collaboration introduces its own challenges. When co-authoring with engineers or product managers, establish a single source of truth for numbers and terminology early. Use shared documents with clear ownership of sections, and resolve disagreements about framing before the piece goes to a broader review. Mixed-authorship documents often suffer from inconsistent voice, so assign one editor to unify tone and structure in the final pass.
Finally, measure the impact of your writing when possible. Track which posts or documentation pages generate questions, pull requests, or adoption. Feedback loops tell you what resonates with your audience and where the communication broke down, allowing you to refine your approach over time.
Common Mistakes
Narrating the search process instead of leading with the conclusion
Fix: Open with the result and the recommendation, then support it with method and evidence.
Reporting metrics without a baseline or split definition
Fix: Name the baseline, the split, and the metric definition next to every headline number.
Publishing notebooks that only run in the author's interactive session
Fix: Restart and run all, pin dependencies, and use relative paths before sharing.
Best Practices
- Write for one primary audience per document and point others to a summary
- Put the conclusion and the business translation in the first paragraph
- Use headings that state takeaways, not vague labels like Results
- Attach context to every number: baseline, split, time window
- Ask a non-expert to restate the finding from the headings alone
Key Takeaways
- Audience, goal, and structure decide whether technical writing lands
- The inverted pyramid puts conclusions first and methodological detail last
- Notebooks need narrative cells that explain reasoning, not just code dumps
- Docstrings and READMEs are contracts; typed arguments and runnable examples are the standard
- Concrete numbers with baselines beat vague claims, and trade-offs stated explicitly build trust