data(permeability)
dim(fingerprints)
## [1] 165 1107
summary(as.vector(permeability))
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.06 1.55 4.91 12.24 15.47 55.60
165 compounds, 1,107 binary fingerprint predictors, and one response
(permeability) which is what were trying to predict. The
response is skewed median is about 5 but a few compounds go up past 50
so no data balanace.
nzv_idx <- nearZeroVar(fingerprints)
fp <- fingerprints[, -nzv_idx]
ncol(fp)
## [1] 388
nearZeroVar removed 719 fingerprints that are almost all
zeros, leaving 388 predictors.
perm <- data.frame(fp, permeability = as.vector(permeability))
idx <- createDataPartition(perm$permeability, p = 0.75, list = FALSE)
train <- perm[idx, ]
test <- perm[-idx, ]
ctrl <- trainControl(method = "repeatedcv", number = 10, repeats = 5,
index = createMultiFolds(train$permeability, k = 10, times = 5))
pls_fit <- train(permeability ~ ., data = train, method = "pls", tuneLength = 20,
preProcess = c("center", "scale"), trControl = ctrl)
pls_fit$bestTune
## ncomp
## 8 8
plot(pls_fit)
Best pls model uses a 75/25 split with 10 fold repeated 5 times. All the predictores are centered and scaled. PLS with 8 components gives the lowers error while 1 - 20 was attempted.R² is 0.53 which explains 53% of the up and downs in permeability. RMSE is ~11 so in average predictions area off by 11 permeability units
pls_test <- postResample(predict(pls_fit, test), test$permeability)
pls_test
## RMSE Rsquared MAE
## 12.4751421 0.4089483 9.6282483
R² = 0.41 on data it has never seen before and theh RSME is 12.5 vs the initial 11 so is not that much worst on new data as this is expected, especially with such a small test size. ## (e) Other models
ridge <- train(permeability ~ ., data = train, method = "glmnet",
tuneGrid = expand.grid(alpha = 0, lambda = 10^seq(-2, 2, length = 30)),
preProcess = c("center", "scale"), trControl = ctrl)
lasso <- train(permeability ~ ., data = train, method = "glmnet",
tuneGrid = expand.grid(alpha = 1, lambda = 10^seq(-2, 1.5, length = 30)),
preProcess = c("center", "scale"), trControl = ctrl)
enet <- train(permeability ~ ., data = train, method = "glmnet",
tuneGrid = expand.grid(alpha = seq(0.1, 0.9, by = 0.2),
lambda = 10^seq(-2, 1.5, length = 25)),
preProcess = c("center", "scale"), trControl = ctrl)
models <- list(PLS = pls_fit, Ridge = ridge, Lasso = lasso, ElasticNet = enet)
rs <- resamples(models)
summary(rs)$statistics$Rsquared[, "Mean", drop = FALSE]
## Mean
## PLS 0.5276933
## Ridge 0.4755966
## Lasso 0.5442235
## ElasticNet 0.5541001
bwplot(rs, metric = "RMSE")
round(t(sapply(models, function(m) postResample(predict(m, test), test$permeability))), 2)
## RMSE Rsquared MAE
## PLS 12.48 0.41 9.63
## Ridge 10.57 0.57 7.86
## Lasso 12.71 0.34 9.69
## ElasticNet 12.07 0.40 8.99
No. The best model explains only about 55% of the variance and is off by ~10 units on a response whose median is 5. That’s not accurate enough to replace the assay.The model is good enough to rank them and send the promising ones to the lab.
data(ChemicalManufacturingProcess)
cmp <- ChemicalManufacturingProcess
dim(cmp)
## [1] 176 58
summary(cmp$Yield)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 35.25 38.75 39.97 40.18 41.48 46.34
176 runs. Yield is the response(how much product came out the batch), and there are 57 predictors with 12 of them being biological (raw material, can’t be changed) and 45 of them of manufacturing process (can be adjusted).
sum(is.na(cmp))
## [1] 106
sort(colSums(is.na(cmp)), decreasing = TRUE)[1:5]
## ManufacturingProcess03 ManufacturingProcess11 ManufacturingProcess10
## 15 10 9
## ManufacturingProcess25 ManufacturingProcess26
## 5 5
Some data is missing with 106 empty spots spread across 28 columns, usually just 1 to 5 per column. There’s also another issue in 108, six of its process readings are but every other run has numbers in the thousands for those. That’s for sure a broken sensor, not an actual reading. So I treated those zeros as missing too, along with a few similar ones in runs 22 and 23.
pred_names <- setdiff(names(cmp), "Yield")
for (v in pred_names) {
x <- cmp[[v]]; nz <- x[!is.na(x) & x != 0]
if (sum(x == 0, na.rm = TRUE) == 1 && length(nz) > 2 && mean(nz) / sd(nz) > 5) cmp[[v]][x == 0] <- NA
}
imp <- preProcess(cmp[, pred_names], method = "knnImpute", k = 5)
X <- predict(imp, cmp[, pred_names])
X <- sweep(sweep(X, 2, imp$std, "*"), 2, imp$mean, "+") # back to original units
cmp <- data.frame(Yield = cmp$Yield, X)
sum(is.na(cmp))
## [1] 0
Each missing value is filled from the 5 most similar runs which are the 5 nearest neighbors.
idx <- createDataPartition(cmp$Yield, p = 0.75, list = FALSE)
train <- cmp[idx, ]
test <- cmp[-idx, ]
ctrl <- trainControl(method = "repeatedcv", number = 10, repeats = 5,
index = createMultiFolds(train$Yield, k = 10, times = 5))
pp <- c("nzv", "center", "scale")
pls3 <- train(Yield ~ ., data = train, method = "pls", tuneLength = 20,
preProcess = pp, trControl = ctrl)
enet3 <- train(Yield ~ ., data = train, method = "glmnet",
tuneGrid = expand.grid(alpha = seq(0, 1, by = 0.1),
lambda = 10^seq(-3, 0.5, length = 30)),
preProcess = pp, trControl = ctrl)
rs3 <- resamples(list(PLS = pls3, ElasticNet = enet3))
summary(rs3)$statistics$RMSE[, "Mean", drop = FALSE]
## Mean
## PLS 1.234460
## ElasticNet 1.141096
summary(rs3)$statistics$Rsquared[, "Mean", drop = FALSE]
## Mean
## PLS 0.5481971
## ElasticNet 0.6128160
I used the same setup as the first problem and tried two models whice first one was PLS, which did best with 4 components. The second one being elastic net ended up as a lasso, which means it dropped the columns it didn’t need and kept 31 out of 57 of them. The lasso came out on top. It explains about 61% of the ups and downs in yield, and its predictions are usually off by only about 1 percentage point, which is pretty good since yields run from about 35 to 46.
postResample(predict(best3, test), test$Yield)
## RMSE Rsquared MAE
## 1.0289499 0.7337713 0.8072696
On the 44 batches I held back the model was off by about 1 point of yield and explained about 73% of the variation. That’s actually a little better than cross validation predicted which was about 61%, with such a small test set, that kind of bump is just luck of the draw. The main takeaway is that the model holds up on data it never saw.
vi <- varImp(best3)$importance
vi_df <- data.frame(Predictor = rownames(vi), Importance = vi$Overall) %>%
arrange(desc(Importance)) %>%
mutate(Type = ifelse(grepl("^Bio", Predictor), "Biological", "Process"))
head(vi_df, 10)
## Predictor Importance Type
## 1 ManufacturingProcess32 100.00000 Process
## 2 ManufacturingProcess09 39.41698 Process
## 3 ManufacturingProcess33 27.77676 Process
## 4 ManufacturingProcess28 24.42477 Process
## 5 BiologicalMaterial05 20.64060 Biological
## 6 ManufacturingProcess26 19.97762 Process
## 7 ManufacturingProcess37 16.84844 Process
## 8 ManufacturingProcess04 14.71381 Process
## 9 ManufacturingProcess43 12.75579 Process
## 10 ManufacturingProcess45 11.84418 Process
ggplot(head(vi_df, 15), aes(reorder(Predictor, Importance), Importance, fill = Type)) +
geom_col() + coord_flip() + labs(x = NULL) + theme_minimal()
The most important predictor by alot is ManufacturingProcess32. Nine of the top ten are process variables, and the only biological one is BiologicalMaterial05. That’s actually good news, because it means most of what drives yield is stuff the factory can actually adjust.
top6 <- head(vi_df$Predictor, 6)
round(sapply(top6, function(p) cor(cmp[[p]], cmp$Yield)), 2)
## ManufacturingProcess32 ManufacturingProcess09 ManufacturingProcess33
## 0.61 0.50 0.42
## ManufacturingProcess28 BiologicalMaterial05 ManufacturingProcess26
## 0.27 0.15 0.22
cmp %>% select(Yield, all_of(top6)) %>%
pivot_longer(-Yield, names_to = "Predictor", values_to = "Value") %>%
mutate(Predictor = factor(Predictor, levels = top6)) %>%
ggplot(aes(Value, Yield)) + geom_point(alpha = 0.5) +
geom_smooth(method = "lm", color = "darkorange") +
facet_wrap(~ Predictor, scales = "free_x", ncol = 3) + labs(x = NULL) + theme_minimal()
The top process variables are ManufacturingProcess32, 09, 33, 28, and 26 which all go up with yield, and none of the top predictors clearly pull it down. The relationships look sor of like straight lines, which is why these models work well here.
For the factory that would mean running those settings higher, especially ManufacturingProcess32, could boost yield. But this comes from past batches so it shows a pattern, not necesarily proof. The next step would be a small test where they change the top two or three settings on purpose and see if yield really goes up. The biological measurements can’t be changed but since they’re known before a batch starts they could be used to flag a bad batch of raw material early.