Why soil spectroscopy needs a different kind of regression
Soil organic carbon (SOC) influences soil aggregation, nutrient cycling and water retention. Conventional laboratory measurements provide reference concentrations, but spectroscopy offers a way to estimate carbon in additional samples once a reliable calibration exists. Near-infrared (NIR) reflectance records how much incoming light is reflected at successive wavelengths. Molecular absorption, mineral composition, particle size and scattering all contribute to a soil’s spectral fingerprint. The spectrum is therefore informative, but it is not a direct measurement of carbon alone.
A useful calibration must answer a predictive question: how closely can measured SOC be estimated from an unseen soil spectrum? Ordinary least squares struggles when adjacent wavelengths are nearly redundant, and a model with more predictors than calibration samples cannot estimate a unique unrestricted coefficient vector. Partial least squares regression (PLSR) addresses this by constructing a limited number of latent scores that use the relationship between spectra and the measured response.
The data and a fair test
The Gyeonggi Soil Spectral Library records composite topsoil samples (0–15 cm) collected in South Korea in 2024. Laboratory SOC is available for 712 of 1,500 spectra. This analysis uses the harmonized Open Soil Spectral Library (OSSL v1.3, GPKOR) distribution, whose 551 reflectance bands span 1,400–2,500 nm in 2 nm increments. The original study collected spectra on a finer grid. The harmonized release supplies one spectral block; it is not a verified pair of raw and smoothed spectra. SOC is expressed as mass percent, and reflectance as a fraction.
The sampling population includes forest and agricultural soils. The 788 records without measured SOC are not used as calibration or test labels. The modelling dataset retains all measured concentrations, including unusually high but plausible values. The original study reports a finer 1 nm spectral grid and a ten-component calibration. This tutorial is an independent reanalysis of the harmonized OSSL v1.3 release, with 551 bands at 2 nm spacing and a separately documented train/test partition; its component count and error estimates should therefore not be read as an exact reproduction of the paper’s model.
A fixed partition is supplied in data/split_plan.csv for reproducibility. Samples are ordered by measured SOC, with ties broken by sample identifier, and divided into four equal rank strata. Within each stratum, 53 samples are randomly reserved for testing and 125 assigned to training. The training samples are distributed across ten cross-validation folds within strata. The assignments were generated using NumPy’s seeded random generator (seed 20261130); fixing them allows comparison across software. The split uses SOC to balance the range, not to estimate model coefficients. Only spectral columns enter the model; identifiers, site information and land use remain available for diagnostics. All modelling choices are made using training data; the test set is used only after component selection.
if (!requireNamespace("pls", quietly = TRUE)) {
stop('Install the pls package first: install.packages("pls")')
}
library(pls)
Attaching package: 'pls'
The following object is masked from 'package:stats':
loadings
out <- "outputs/quarto"
dir.create(out, recursive = TRUE, showWarnings = FALSE)
soil <- read.csv("data/gpkor_soc_labelled.csv", stringsAsFactors = FALSE)
plan <- read.csv("data/split_plan.csv", stringsAsFactors = FALSE)
wavelength <- seq(1400, 2500, by = 2)
bands <- paste0("nir_", wavelength)
stopifnot(nrow(soil) == 712, length(bands) == 551,
all(c("sample_id", "soc_pct", "land_use", "region", bands) %in% names(soil)),
!anyNA(soil$sample_id), !anyDuplicated(soil$sample_id),
!anyNA(plan), !anyDuplicated(plan$sample_id),
setequal(soil$sample_id, plan$sample_id))
plan <- plan[match(soil$sample_id, plan$sample_id), ]
stopifnot(identical(soil$sample_id, plan$sample_id),
all(plan$soc_stratum %in% 1:4),
all(plan$partition %in% c("train", "test")),
all(plan$cv_fold[plan$partition == "train"] %in% 1:10),
all(plan$cv_fold[plan$partition == "test"] == 0))
X <- as.matrix(soil[, bands])
stopifnot(is.numeric(X), all(is.finite(X)), all(X >= 0 & X <= 1),
all(apply(X, 2, sd) > 0), is.numeric(soil$soc_pct),
all(is.finite(soil$soc_pct)), all(soil$soc_pct >= 0 & soil$soc_pct <= 100))
train <- soil[plan$partition == "train", ]
test <- soil[plan$partition == "test", ]
train_plan <- plan[plan$partition == "train", ]
stopifnot(nrow(train) == 500, nrow(test) == 212,
length(intersect(train$sample_id, test$sample_id)) == 0)
train_model <- train[, c("soc_pct", bands)]
test_model <- test[, c("soc_pct", bands)]
print(table(plan$soc_stratum, plan$partition))
test train
1 53 125
2 53 125
3 53 125
4 53 125
The resulting training and test partitions contain 500 and 212 samples, respectively. Keeping the split explicit prevents accidental changes between analyses.
Read the spectral fingerprints
Overlaying the training spectra reveals broad absorption and scattering patterns rather than 551 independent pieces of information. The darker curves represent average spectra within SOC rank groups; individual curves reveal within-group variability. Their overlap matters: a single wavelength cannot uniquely identify carbon in a heterogeneous soil population.
X_train <- as.matrix(train[, bands])
adjacent_r <- vapply(seq_len(ncol(X_train) - 1), function(j) {
cor(X_train[, j], X_train[, j + 1])
}, numeric(1))
print(summary(adjacent_r)) Min. 1st Qu. Median Mean 3rd Qu. Max.
0.9987 1.0000 1.0000 1.0000 1.0000 1.0000
colors <- c("#2166AC", "#67A9CF", "#EF8A62", "#B2182B")
draw_spectra <- function() {
plot(range(wavelength), range(X_train), type = "n", xlab = "Wavelength (nm)",
ylab = "Reflectance (fraction)", main = "Spectral fingerprints of training soils")
for (g in 1:4) {
rows <- train_plan$soc_stratum == g
matlines(wavelength, t(X_train[rows, , drop = FALSE]), lty = 1,
col = adjustcolor(colors[g], alpha.f = 0.12), lwd = 0.6)
lines(wavelength, colMeans(X_train[rows, , drop = FALSE]),
col = colors[g], lwd = 2.5)
}
legend("bottomright", legend = paste("SOC rank group", 1:4),
col = colors, lwd = 2, bty = "n", cex = 0.85)
}
if (interactive()) draw_spectra()
The four rank groups run from lower to higher measured SOC. In this training set, their average spectra generally descend from group one to group four across much of the wavelength range, while the transparent individual curves show substantial overlap. This is a useful population-level pattern, not proof that reflectance is controlled by carbon alone. Soil NIR spectra contain broad, overlapping overtone and combination features. Regions around 1,400–1,450 nm and 1,900–1,950 nm are strongly influenced by water and hydroxyl vibrations; features around 2,200–2,300 nm can involve metal–OH and OH combinations, while C–H combinations can contribute farther into the 2,300–2,400 nm region. Mineralogy, particle size, scattering and residual moisture can all affect the same fingerprint.
The median correlation between adjacent bands in the training set is 0.9999896, and the smallest adjacent-band correlation is 0.9987. With 551 highly redundant predictors and only 500 training observations, ordinary least squares would be poorly conditioned and an unrestricted coefficient vector would not be uniquely estimable. Such redundancy is precisely why a low-dimensional calibration is useful. It does not, by itself, guarantee that the spectra predict carbon.
How PLSR constructs predictive components
Let \(X\) be the centered spectral matrix and \(y\) the centered SOC response. A PLS component forms a score \(t=Xw\), choosing a direction \(w\) informed by covariance with \(y\). The algorithm extracts successive directions after removing variation explained by earlier components. The predicted response is a linear combination of the resulting scores. In contrast, principal component analysis chooses directions to explain predictor variance without considering SOC. Neither method turns individual wavelengths into causal effects.
Here all reflectances have common units, so the calibration is centered but not scaled to unit variance. Centering is estimated afresh inside every cross-validation fold. No additional spectral transformation is applied to the harmonized data. This deliberately focused analysis avoids comparing preprocessing methods after seeing test performance.
Choose complexity without touching the test set
For each of ten training folds, fit the calibration on the other nine folds and predict the excluded samples for component counts from one through thirty. Pool the out-of-fold squared errors. The cross-validation RMSE is
\[ \operatorname{RMSE}_{CV}=\sqrt{\frac{1}{n_{train}}\sum_{i=1}^{n_{train}}(y_i-\hat y_{i,-f(i)})^2}. \]
The selected number of components minimizes this training-only criterion. A fold-specific training mean provides a reference. The cap of 30 components is fixed before inspecting test results; if the minimum lies at the cap, that boundary should be reported rather than silently interpreted as an unrestricted optimum.
# All wavelengths share units; center within each fold, without variance scaling.
folds <- lapply(1:10, function(k) which(train_plan$cv_fold == k))
stopifnot(all(lengths(folds) > 0),
identical(sort(unlist(folds)), seq_len(nrow(train))))
max_components <- 30L
stopifnot(nrow(train) - max(lengths(folds)) > max_components)
cv_fit <- plsr(soc_pct ~ ., data = train_model, ncomp = max_components,
method = "oscorespls", scale = FALSE, center = TRUE,
validation = "CV", segments = folds)
cv_pred <- matrix(cv_fit$validation$pred[, 1, ], nrow = nrow(train),
ncol = max_components)
stopifnot(all(is.finite(cv_pred)))
cv_rmse <- sqrt(colMeans((cv_pred - train$soc_pct)^2))
cv_curve <- data.frame(components = seq_len(max_components), cv_rmse = cv_rmse)
best <- which.min(cv_rmse)
cv_baseline <- numeric(nrow(train))
for (i in folds) cv_baseline[i] <- mean(train$soc_pct[-i])
cv_base_rmse <- sqrt(mean((cv_baseline - train$soc_pct)^2))
print(cv_curve[best, ]) components cv_rmse
16 16 0.3608769
if (best == max_components) warning("CV minimum is at the predeclared component cap.")
draw_cv <- function() {
plot(cv_curve, type = "b", pch = 19, cex = 0.7, col = colors[1],
ylim = range(c(cv_rmse, cv_base_rmse)), xlab = "PLS components",
ylab = "CV RMSE (percentage points)", main = "Training-only cross-validation")
abline(h = cv_base_rmse, lty = 2, col = "grey50")
points(best, cv_rmse[best], pch = 19, cex = 1.6, col = colors[4])
legend("topright", c(paste("Minimum:", best, "components"), "Fold mean baseline"),
col = c(colors[4], "grey50"), pch = c(19, NA), lty = c(NA, 2), bty = "n")
}
if (interactive()) draw_cv()
The selected complexity is 16 components, with a cross-validated RMSE of 0.361 percentage points, compared with 1.821 for the fold-mean reference. The minimum lies inside the component search range. The curve drops sharply over the first few components and then flattens. The values at 15, 16 and 17 components are 0.361690, 0.360877 and 0.361086, respectively. The global minimum is therefore at 16, but the immediate neighbours are almost tied. Because this run does not show fold-wise uncertainty or repeat the entire selection over multiple partitions, 16 is the minimum under this stated rule, not a uniquely established physical complexity. Cross-validation estimates error for model selection; it is not an independent final test.
Evaluate the frozen calibration
Fit a final PLS model using the entire training partition and the chosen number of components. Predict the reserved soils once. A simple baseline predicts the mean SOC of the training soils for every test sample. The same test observations are used for both methods.
RMSE penalizes large errors, MAE averages absolute errors, and mean prediction bias is predicted minus measured SOC. These metrics are measured in percentage points, not relative percentages. Test \(R^2\) is defined as \(1-\sum(y-\hat y)^2/\sum(y-\bar y_{test})^2\); it is not the squared correlation, and it may be negative. The training-mean baseline need not have exactly zero test \(R^2\) because it does not know the test mean.
final_fit <- plsr(soc_pct ~ ., data = train_model, ncomp = best,
method = "oscorespls", scale = FALSE, center = TRUE,
validation = "none")
pred <- as.numeric(predict(final_fit, newdata = test_model[, bands], ncomp = best))
obs <- test$soc_pct
baseline <- rep(mean(train$soc_pct), nrow(test))
stopifnot(length(pred) == nrow(test), all(is.finite(pred)), var(obs) > 0)
score <- function(p) {
e <- p - obs
c(rmse = sqrt(mean(e^2)), mae = mean(abs(e)),
r2 = 1 - sum(e^2) / sum((obs - mean(obs))^2), bias = mean(e))
}
test_metrics <- data.frame(model = c("Mean baseline", "PLSR"),
rbind(score(baseline), score(pred)), row.names = NULL)
print(test_metrics, digits = 5) model rmse mae r2 bias
1 Mean baseline 1.75204 1.3372 -0.0019671 0.077630
2 PLSR 0.40723 0.3112 0.9458689 -0.019107
predictions <- data.frame(sample_id = test$sample_id, land_use = test$land_use,
region = test$region, soc_pct = obs,
predicted_soc = pred, baseline_soc = baseline,
residual = obs - pred)
negative_n <- sum(pred < 0)
cat("Negative SOC predictions:", negative_n, "\n")Negative SOC predictions: 6
draw_agreement <- function() {
lim <- range(c(obs, pred)) + c(-0.25, 0.25)
plot(obs, pred, xlim = lim, ylim = lim, asp = 1, pch = 19,
col = adjustcolor(colors[1], 0.6), xlab = "Measured SOC (%)",
ylab = "Predicted SOC (%)", main = "Held-out prediction agreement")
abline(0, 1, lty = 2, col = "grey40")
}
if (interactive()) draw_agreement()| model | rmse | mae | r2 | bias |
|---|---|---|---|---|
| Mean baseline | 1.752 | 1.337 | -0.002 | 0.078 |
| PLSR | 0.407 | 0.311 | 0.946 | -0.019 |
The held-out PLSR RMSE is 0.407 percentage points, versus 1.752 for the mean baseline. This is a 76.8 percent reduction in RMSE relative to that baseline. The PLSR MAE is 0.311, and its test \(R^2\) is 0.946. Its mean prediction bias is -0.019 percentage points, where negative bias means slight average underprediction because bias is predicted minus measured. Test \(R^2\) here is calculated from the reduction in squared error relative to the test-set mean; it is not the squared correlation and it does not mean the model is 94.6 percent accurate for every sample. A small mean bias can conceal compensating errors, so agreement and residual plots are necessary complements to these scores.
The model produces 6 negative test predictions, with the lowest at -0.481 percent SOC. All six occur among samples with measured SOC between 0.1 and 0.5 percent. Carbon concentration cannot be negative; these are retained as errors of an unconstrained linear model, not treated as plausible measurements. Clipping them to zero after testing would hide a model defect and change the reported error. A transformation or constrained model would need to be selected and validated using training data only.
Diagnose errors and interpret coefficients
Residuals are measured minus predicted SOC. A positive residual indicates underprediction; a negative residual indicates overprediction. In the held-out plot, most points are distributed around zero, but some errors remain substantial: the largest underprediction is about 1.52 percentage points and the largest overprediction is about 0.98 percentage points. The plot is a diagnostic, not a proof of constant error variance; a small number of observations at the high end also limits what can be inferred there.
The land-use summary reports sample count, RMSE and prediction bias by category. Its bias is predicted minus measured, the opposite sign from the residual plotted above. The table shows modest average overprediction in deciduous and coniferous forest soils, and average underprediction in several other groups, including urban parks and upland fields. These are descriptive differences, not evidence of a land-use mechanism. Greenhouse and orchard each have only three test samples, while paddy fields have eight; their estimates are consequently imprecise. Categories absent from the test set cannot be assessed.
The spectral coefficient curve represents the fitted linear combination of reflectances in the original units. The visible peaks and sign changes show how the model weights the spectral profile, but adjacent wavelengths are almost redundant. A coefficient can therefore move or change sign as correlated predictors share information, even when predictions remain similar. Do not interpret the largest spike as a unique chemical fingerprint or a causal effect. More stable chemical interpretation would require additional work such as variable-importance analysis, grouped wavelength assessment, coefficient stability across resamples and carefully nested comparisons of spectral preprocessing.
land_use_errors <- do.call(rbind, lapply(split(predictions, predictions$land_use), function(d) {
data.frame(land_use = d$land_use[1], n = nrow(d),
rmse = sqrt(mean(d$residual^2)), bias = -mean(d$residual))
}))
rownames(land_use_errors) <- NULL
print(land_use_errors, digits = 4, row.names = FALSE) land_use n rmse bias
bare land 14 0.3922 0.06380
coniferous forest 30 0.3510 0.02397
deciduous forest 78 0.4191 0.04599
greenhouse 3 0.5277 -0.03410
mixed forest 45 0.4385 -0.06670
orchard 3 0.4070 -0.07137
paddy field 8 0.2125 -0.14055
riparian zone 12 0.3633 -0.04946
upland field 10 0.4299 -0.19772
urban park 9 0.4514 -0.24860
coefficients <- data.frame(wavelength_nm = wavelength,
coefficient = as.numeric(coef(final_fit, ncomp = best)))
stopifnot(nrow(coefficients) == length(wavelength), all(is.finite(coefficients$coefficient)))
draw_residuals <- function() {
plot(pred, predictions$residual, pch = 19, col = adjustcolor(colors[1], 0.6),
xlab = "Predicted SOC (%)", ylab = "Observed - predicted (percentage points)",
main = "Held-out residuals")
abline(h = 0, lty = 2, col = "grey40")
}
draw_coefficients <- function() {
plot(coefficients, type = "l", col = colors[1], lwd = 1.5,
xlab = "Wavelength (nm)", ylab = "PLSR coefficient",
main = "Spectral coefficient profile")
abline(h = 0, lty = 2, col = "grey40")
}
if (interactive()) draw_residuals()
if (interactive()) draw_coefficients()| land_use | n | rmse | bias |
|---|---|---|---|
| bare land | 14 | 0.392 | 0.064 |
| coniferous forest | 30 | 0.351 | 0.024 |
| deciduous forest | 78 | 0.419 | 0.046 |
| greenhouse | 3 | 0.528 | -0.034 |
| mixed forest | 45 | 0.438 | -0.067 |
| orchard | 3 | 0.407 | -0.071 |
| paddy field | 8 | 0.212 | -0.141 |
| riparian zone | 12 | 0.363 | -0.049 |
| upland field | 10 | 0.430 | -0.198 |
| urban park | 9 | 0.451 | -0.249 |
Reproducible analysis outputs
The same analytical workflow saves the cross-validation curve, held-out predictions, metric table, land-use diagnostics and coefficient profile, together with high-resolution versions of the figures. These tables preserve the information required to examine individual errors and reproduce the aggregate statistics.
run_summary <- data.frame(n_train = nrow(train), n_test = nrow(test),
best_components = best, cv_rmse = cv_rmse[best],
cv_baseline_rmse = cv_base_rmse,
negative_predictions = negative_n,
boundary_selected = best == max_components)
write.csv(run_summary, file.path(out, "summary.csv"), row.names = FALSE)
write.csv(cv_curve, file.path(out, "cv_curve.csv"), row.names = FALSE)
write.csv(test_metrics, file.path(out, "test_metrics.csv"), row.names = FALSE)
write.csv(predictions, file.path(out, "test_predictions.csv"), row.names = FALSE)
write.csv(coefficients, file.path(out, "coefficients.csv"), row.names = FALSE)
write.csv(land_use_errors, file.path(out, "land_use_errors.csv"), row.names = FALSE)
save_plot <- function(name, draw, width = 8, height = 5) {
png(file.path(out, name), width = width, height = height, units = "in", res = 300)
on.exit(dev.off())
par(mar = c(4.5, 4.8, 3.2, 1.2), las = 1)
draw()
invisible(NULL)
}
save_plot("01_spectra.png", draw_spectra)
save_plot("02_cv.png", draw_cv)
save_plot("03_agreement.png", draw_agreement, 6.5, 6)
save_plot("04_residuals.png", draw_residuals)
save_plot("05_coefficients.png", draw_coefficients)
writeLines(capture.output(sessionInfo()), file.path(out, "session_info.txt"))
print(run_summary) n_train n_test best_components cv_rmse cv_baseline_rmse
1 500 212 16 0.3608769 1.820753
negative_predictions boundary_selected
1 6 FALSE
What the calibration can and cannot establish
The original Gyeonggi study reports a 10-component model with a test \(R^2\) near 0.95 and RMSE near 0.39 percentage points. The present results are similar in scale, but they are not a direct reproduction: this analysis uses the harmonized 551-band OSSL v1.3 grid rather than the original 1,101-band, 1 nm data, and it uses its own fixed stratified partition and component-selection procedure.
The holdout assesses prediction of labelled soils within this regional library. Nearby samples may share environmental conditions and soil characteristics; a random split can therefore be optimistic if the intended use is prediction in unsampled districts. For geographic transfer, a stronger next test would hold out whole regions or spatial blocks, with component selection repeated only inside the remaining training data. The most suitable validation design depends on the intended prediction target: random splitting estimates performance for new samples drawn from a similar library, while spatial blocking asks whether the calibration transfers to geographically separated soils.
The data represent topsoil collected in one South Korean province during 2024 and spectra measured under a standardized laboratory protocol with one instrument. Field moisture, different sample preparation, another spectrometer or another soil population can shift the spectral fingerprint. The labelled subset also differs in coverage across land-use groups, and the observed performance is not evidence of accurate prediction in the 788 unlabelled samples, agricultural soils in another country, or spectra from another instrument. Finally, the analysis estimates SOC concentration, not carbon stock; stock estimation additionally requires bulk density, depth and coarse-fragment information.
The essential lesson is that PLSR turns correlated wavelengths into a supervised low-dimensional calibration, but its usefulness must be judged with independent predictions, a meaningful baseline, residual diagnostics and an explicit account of the population to which the calibration applies.
Data and references
- Bae, J., et al. (2026). A spatially rich, temporally coherent soil spectral dataset for soil organic carbon estimation. Scientific Data, 13, 230. DOI.
- Open Soil Spectral Library (OSSL), v1.3, GPKOR. Dataset catalogue; versioned archive; CC BY 4.0. The teaching CSV joins the harmonized tables, renames fields and separates measured and unlabelled samples. Numeric measurements are unchanged.
- Mevik, B.-H., and Wehrens, R. (2007). The pls package: principal component and partial least squares regression in R. Journal of Statistical Software, 18(2), 1–23. DOI; package documentation.
The Open Soil Spectral Library and associated services were developed with funding from USDA NIFA Award #2020-67021-32467.
Comments
Post a Comment