if (FALSE) {
library(prospectr)
data(NIRsoil)
# Preprocess spectra
NIRsoil$spc_pr <- savitzkyGolay(
detrend(NIRsoil$spc, wav = as.numeric(colnames(NIRsoil$spc))),
m = 1, p = 1, w = 7
)
# Missing values in the response are allowed
train_x <- NIRsoil$spc_pr[NIRsoil$train == 1, ]
train_y <- NIRsoil$Ciso[NIRsoil$train == 1]
test_x <- NIRsoil$spc_pr[NIRsoil$train == 0, ]
test_y <- NIRsoil$Ciso[NIRsoil$train == 0]
# Build library
model_library <- liblex(
Xr = train_x,
Yr = train_y,
neighbors = neighbors_k(c(30, 40)),
diss_method = diss_correlation(ws = 27, scale = TRUE),
fit_method = fit_wapls(
min_ncomp = 4,
max_ncomp = 17,
scale = FALSE,
method = "mpls"
),
control = liblex_control(tune = TRUE)
)
# Visualise neighborhood centroids and samples to predict
matplot(
as.numeric(colnames(model_library$scaling$local_x_center)),
t(test_x),
col = rgb(1, 0, 0, 0.3),
lty = 1,
type = "l",
xlab = "Wavelength (nm)",
ylab = "First derivative detrended absorbance"
)
matlines(
as.numeric(colnames(model_library$scaling$local_x_center)),
t(model_library$scaling$local_x_center),
col = rgb(0, 0, 1, 0.3),
lty = 1,
type = "l"
)
grid(lty = 1)
legend(
"topright",
legend = c("Samples to predict", "Neighborhood centroids"),
col = c(rgb(1, 0, 0, 0.8), rgb(0, 0, 1, 0.8)),
lty = 1,
lwd = 2,
bty = "n"
)
# Predict new observations
y_hat_liblex <- predict(model_library, test_x)
# Predicted versus observed values
lims <- range(y_hat_liblex$predictions$pred, test_y, na.rm = TRUE)
plot(
y_hat_liblex$predictions$pred,
test_y,
pch = 16,
col = rgb(0, 0, 0, 0.5),
xlab = "Predicted",
ylab = "Observed",
xlim = lims,
ylim = lims
)
abline(a = 0, b = 1, col = "red")
grid(lty = 1)
## run liblex in parallel (requires a parallel backend, e.g., doParallel)
library(doParallel)
n_cores <- min(2, parallel::detectCores() - 1)
clust <- makeCluster(n_cores)
registerDoParallel(clust)
model_library2 <- liblex(
Xr = train_x,
Yr = train_y,
neighbors = neighbors_k(c(30, 40)),
fit_method = fit_wapls(min_ncomp = 4, max_ncomp = 17, method = "simpls")
)
y_hat_liblex2 <- predict(model_library2, test_x)
registerDoSEQ()
try(stopCluster(clust))
}
Run the code above in your browser using DataLab