DEV Community

Kapil Singhal
Kapil Singhal

Posted on

Which Saplings Die Next? A Mortality Model from Your Own Resurvey Data

After the second or third resurvey of a plantation, you are sitting on something more useful than a survival percentage. You have a history: which trees were alive, stressed or dead at each visit, in which block, of which species, in which season. That history can tell you where the next losses are likely to happen, so the field team walks those blocks first and the watering or gap-filling money goes where it is needed.

This post builds a small, explainable model for that in about 50 lines of pandas and scikit-learn. It is deliberately boring: logistic regression, a handful of features, a time-based split. The hard parts are in the data shape and in not fooling yourself, so that is where most of the words go.

The question, stated precisely

"Will this tree die?" is too vague to model. A better question is:

Given a tree that was alive (or stressed) at visit k, what is the probability it is recorded dead at visit k + 1?

That turns the history into one row per tree per interval between two visits. Survival analysts call this a discrete-time setup. It handles uneven visit gaps, trees planted at different times, and trees that drop out of the record, without any special library.

It also forces two rules that matter later:

  1. A row only starts from a living tree. Dead trees do not get to "die again".
  2. A replaced tree is a new tree. If gap-filling put a new sapling in the same pit, the old ID ended in death and the new sapling needs its own ID and planting date. If your records reuse the ID, the model learns that dead trees come back to life, and your survival numbers are inflated as well. (I wrote about the record structure behind this in an earlier post on a data model for geo-tagged plantation records.)

The input

One row per tree per visit:

tree_id block_id species planted_on visit_on status block_decline_flag
1041 B08 teak 2025-07-01 2026-01-15 stressed 1

status is one of alive, stressed, dead, replaced. block_decline_flag is a per-block signal from satellite trend monitoring at the time of the visit (1 if the block's vegetation trend has been falling). If you do not have it, drop the column; the rest still works.

The code

import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

obs = pd.read_csv("observations.csv", parse_dates=["planted_on", "visit_on"])
obs = obs.sort_values(["tree_id", "visit_on"])

# 1. One row per tree per interval between two visits, starting from a living tree.
nxt = obs.groupby("tree_id")[["visit_on", "status"]].shift(-1)
iv = obs.assign(next_visit=nxt["visit_on"], next_status=nxt["status"])
iv = iv[iv["status"].isin(["alive", "stressed"]) & iv["next_status"].notna()]
iv = iv[iv["next_status"] != "replaced"]          # a replaced tree is a new tree, not a survivor
iv["died"] = (iv["next_status"] == "dead").astype(int)

# 2. Features known at the start of the interval only.
iv["age_days"] = (iv["visit_on"] - iv["planted_on"]).dt.days
iv["stressed"] = (iv["status"] == "stressed").astype(int)
iv["dry_season_next"] = iv["next_visit"].dt.month.isin([3, 4, 5]).astype(int)
prev = (iv.groupby(["block_id", "visit_on"])["died"].mean()
          .groupby(level=0).shift(1).rename("block_prev_mortality"))
iv = iv.join(prev, on=["block_id", "visit_on"])
iv["block_prev_mortality"] = iv["block_prev_mortality"].fillna(0)

features = ["species", "age_days", "stressed", "dry_season_next",
            "block_prev_mortality", "block_decline_flag"]
pre = ColumnTransformer([
    ("cat", OneHotEncoder(handle_unknown="ignore"), ["species"]),
    ("num", StandardScaler(), features[1:]),
])
model = make_pipeline(pre, LogisticRegression(max_iter=1000))

# 3. Split by time, never at random: train on old rounds, test on the latest one.
cutoff = iv["visit_on"].max()
train, test = iv[iv["visit_on"] < cutoff], iv[iv["visit_on"] == cutoff]
model.fit(train[features], train["died"])
test = test.assign(p_death=model.predict_proba(test[features])[:, 1])

print("base rate:", round(test["died"].mean(), 3))
print("average precision:", round(average_precision_score(test["died"], test["p_death"]), 3))
top = test.nlargest(int(len(test) * 0.2), "p_death")
print("deaths caught in top 20% of trees:", round(top["died"].sum() / test["died"].sum(), 2))

# 4. The output field crews use: blocks ranked by expected losses next round.
visit_list = (test.groupby("block_id")["p_death"].sum()
                  .sort_values(ascending=False).round(1).head(10))
print(visit_list)
Enter fullscreen mode Exit fullscreen mode

Why each step is there

Interval rows (step 1). shift(-1) within each tree pairs every visit with the next one. Filtering on status keeps only intervals that start alive or stressed. Dropping next_status == "replaced" stops gap-filled pits from counting as survivors.

Features known at the start (step 2). Every feature must be something you would have known on the day of visit k. Age, current stress, the season the interval runs through, and the block's death rate in the previous interval all qualify. The groupby-then-shift(1) on block mortality is the line people get wrong: without the shift, each row sees its own interval's deaths, and the model looks brilliant in testing and useless in the field.

A time-based split (step 3). A random train/test split lets the model learn from the future. Tree 1041's neighbour dying in April is in training while tree 1041's April death is in testing. Train on older rounds and test on the latest round only, the same way the model will be used. scikit-learn's cross-validation guide covers time-series splits if you want more than one fold.

The metrics. Deaths are rare, so accuracy is meaningless: when fewer than one tree in ten dies per round, predicting "nobody dies" scores above 90 per cent. Look at average precision against the base rate, and at the share of next-round deaths that fall in the top 20 per cent of trees by predicted risk. If the top fifth of trees holds well over a fifth of the deaths, the ranking is useful. If it does not, the model is not ready, and you keep walking blocks in your usual order.

The visit list (step 4). Summing probabilities per block gives expected losses per block. This is the output a field supervisor can act on: walk B08 first, then the next nine.

Calibration, briefly

Logistic regression tends to give reasonable probabilities, but check. Bucket the test rows into deciles of p_death and compare the mean prediction with the observed death rate in each bucket. If the model says 10 per cent and 25 per cent of those trees died, the ranking may still be fine, but the block totals in step 4 will be too low. The calibration chapter in the scikit-learn docs shows how to fix that.

What this model is not

  • It is not a survival figure. Predicted deaths are an estimate. The survival rate you report comes from counting trees on the ground. Keep predictions in a separate column with a label that says so.
  • It is not transferable by default. A model trained on one site's history says little about a different climate, species mix or watering regime. Retrain per project, or at least per region.
  • It is not a reason to skip visits. Use it to order visits, not to cancel them. The blocks at the bottom of the list still need their scheduled round, or the next model will be trained on stale data.
  • It will be wrong after a shock. A failed borewell, a fire or an unusual heatwave is not in the history. Field notes about such events should override the ranking.

Where to go from here

Add features only when you can collect them every round: watering logs per block, soil type, distance to the nearest water point. Try a gradient-boosted model once the simple one is stable, and keep the logistic version as a baseline you can explain to a CSR committee or an EHS manager.

The broader workflow, where a field record, satellite trend flags and health checks decide which trees get attention between full surveys, is what we describe as tree health monitoring for plantations. At Aranyix we run custom predictions from a project's own historical data alongside satellite and trend monitoring and tree health monitoring. The code above is a minimal open version of the idea, not our production model.

If you try this on your own resurvey data, I would like to hear what the top-20-per-cent number looked like.


Aranyix: https://aranyix.tech

Axentis Technologies: https://axentis.tech

Aranyix on LinkedIn: https://www.linkedin.com/showcase/aranyix/

Axentis Technologies on LinkedIn: https://www.linkedin.com/company/axentis-technologies

Kapil Singhal, Director, Axentis Technologies

Top comments (0)