Show contents
Chapter 6 of 7 · 25 min
Project: forecast a harvest
By the end of this chapter, you'll be able to
- Prepare a dataset with several variables and split it into training and test sets
- Fit a multiple linear regression with numpy
- Evaluate the model against a simple baseline
- Interpret the coefficients and use them for a quantified decision
The data
The measurements cover 60 plots. They are simulated from a known relation, plus noise: we will be able to check that the model finds it again. For each plot:
rain: the season's rain, in mm;fertiliser: the fertiliser applied, in kg per hectare;clay: 1 if the soil is clay, 0 if it is sandy;crop_yield: the harvest, in tonnes per hectare (the label).
We turn a coefficient into money to answer the farmers' question.
Text description of the animation
- Each plot is described by three variables and its harvest.
- We set aside 15 plots that the model will never see while learning.
- The model learns one coefficient per variable, plus a constant.
- We check that it does clearly better than always predicting the mean.
- We turn a coefficient into money to answer the farmers' question.
The model
With several variables, regression looks for yield = c0 + c1 × rain + c2 × fertiliser + c3 × clay. We put the variables in a matrix X, with a first column of 1s for the constant c0, and np.linalg.lstsq finds the coefficients that minimise the squared error (the least squares method):
import numpy as np
rng = np.random.default_rng(0)
n = 60
rain = rng.uniform(300, 800, n)
fertiliser = rng.uniform(0, 100, n)
clay = rng.integers(0, 2, n)
crop_yield = 0.2 + 0.0012 * rain + 0.004 * fertiliser + 0.15 * clay + rng.normal(0, 0.08, n)
X = np.column_stack([np.ones(n), rain, fertiliser, clay])
order = rng.permutation(n)
train, test = order[:45], order[45:]
coefs, *_ = np.linalg.lstsq(X[train], crop_yield[train], rcond=None)
print("coefficients:", np.round(coefs, 4))
pred_test = X[test] @ coefs
mae_model = np.abs(pred_test - crop_yield[test]).mean()
mae_baseline = np.abs(crop_yield[train].mean() - crop_yield[test]).mean()
print(f"Model MAE: {mae_model:.3f} t/ha")
print(f"Baseline MAE (always the mean): {mae_baseline:.3f} t/ha")
coefficients: [0.1828 0.0012 0.0039 0.1666]
Model MAE: 0.041 t/ha
Baseline MAE (always the mean): 0.145 t/ha
X[test] @ coefsis a matrix product: for each plot, it multiplies each variable by its coefficient and adds them up. That is the prediction;coefs, *_ = …keeps the first result oflstsqand ignores the others;- the baseline always predicts the mean yield of the training set.
The model divides the error by more than 3 compared with the baseline: it really learned something. And its coefficients are close to the relation used to simulate the data (0.0012 per mm of rain, 0.004 per kg of fertiliser, 0.15 for clay soil). With real data, this relation is unknown: only the evaluation on the test set lets you judge.
Interpret the coefficients
Each coefficient reads “all other things being equal”: with the same rain and soil, each kilogram of fertiliser adds about 0.0039 t/ha, that is 3.9 kg of millet. We can then predict scenarios:
import numpy as np
coefs = np.array([0.1828, 0.0012, 0.0039, 0.1666])
def predict(rain, fertiliser, clay):
return float(coefs @ np.array([1, rain, fertiliser, clay]))
for fertiliser in (0, 50, 100):
print(f"600 mm, sandy soil, {fertiliser:>3} kg of fertiliser: {predict(600, fertiliser, 0):.2f} t/ha")
600 mm, sandy soil, 0 kg of fertiliser: 0.90 t/ha
600 mm, sandy soil, 50 kg of fertiliser: 1.10 t/ha
600 mm, sandy soil, 100 kg of fertiliser: 1.29 t/ha
We reuse here the rounded coefficients learned above, so as not to repeat the whole computation.
Mini-lab: your own scenarioPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: is fertiliser profitable?
Fertiliser costs 450 FCFA per kilogram, and millet sells at 300 FCFA per kilogram. Using the learned coefficient (0.0039 t/ha per kg of fertiliser), compute for 50 kg of fertiliser per hectare: the harvest gain (in kg), its value (in FCFA), the cost of the fertiliser and the net profit. Is fertiliser profitable?
Hint 1
Hint 2
Show the solution and common mistakes
fertiliser_coef = 0.0039
fertiliser_price = 450
millet_price = 300
dose = 50
gain_kg = fertiliser_coef * 1000 * dose
value = gain_kg * millet_price
cost = dose * fertiliser_price
print(f"Gain: {gain_kg:.0f} kg of millet, worth {value:,.0f} FCFA")
print(f"Fertiliser cost: {cost:,.0f} FCFA")
print(f"Net profit: {value - cost:,.0f} FCFA per hectare")
Gain: 195 kg of millet, worth 58,500 FCFA
Fertiliser cost: 22,500 FCFA
Net profit: 36,000 FCFA per hectare
Each kilogram of fertiliser brings about 3.9 kg of millet, that is 1,170 FCFA, for a cost of 450 FCFA: according to this model, fertiliser is profitable. But this figure only holds within the data's range (up to 100 kg per hectare) and assumes the effect stays linear. In practice, a fertiliser's effect eventually levels off: beyond the observed doses, the model knows nothing.
Common mistakes:
- Forgetting to convert tonnes to kilograms: you would find a gain 1,000 times too small.
- Recommending 500 kg of fertiliser per hectare “since it is profitable”: that is an extrapolation far from the data, exactly the pitfall of the previous chapter.
Summary
- 1A multiple regression combines several variables: yield = c0 + c1 × rain + c2 × fertiliser + …
- 2np.linalg.lstsq finds the coefficients by least squares; X @ coefs computes the predictions.
- 3A model is evaluated on a test set, against a simple baseline such as the mean.
- 4A coefficient reads with other variables held equal, in its unit: bring scales together before comparing.
- 5A model helps decide within its range of validity, and does not prove causation on its own.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.