Warning: package 'AppliedPredictiveModeling' was built under R version 4.5.2
library(caret)
Loading required package: lattice
Attaching package: 'caret'
The following objects are masked from 'package:fabletools':
MAE, RMSE
The following object is masked from 'package:purrr':
lift
permeability
Min. : 0.06
1st Qu.: 1.55
Median : 4.91
Mean :12.24
3rd Qu.:15.47
Max. :55.60
# Count of presence of each molecular substructurefingerprint_counts <-colSums(fingerprints, dims =1)# summary of frequenciessummary(fingerprint_counts)
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.00 1.00 4.00 25.54 30.00 165.00
# predictor that are not present 0sum(fingerprint_counts ==0)
[1] 20
# number of occurance < 5sum(fingerprint_counts <5)
[1] 564
# visualize the fingerprints datafingerprint_df <-tibble(Frequency =as.numeric(fingerprint_counts))ggplot(fingerprint_df, aes(x = Frequency)) +geom_histogram(bins =30,fill ="steelblue",color ="black" ) +labs(title ="Distribution of Molecular Fingerprint Frequencies",x ="Number of Molecules Containing Substructure",y ="Number of Predictors" ) +theme_minimal()
Interpretation
If most predictors have frequencies close to zero, it means many molecular substructures occur in only a small number of molecules. These sparse predictors may provide limited information for regression modeling.
b. The fingerprint predictors indicate the presence or absence of substructures of a molecule and are often sparse meaning that relatively few of the molecules contain each substructure. Filter out the predictors that have low frequencies using the nearZeroVar function from the caret package. How many predictors are left for modeling?
# Identify near-zero variance predictornzv <-nearZeroVar(fingerprints)# number of predictor before filteringncol(fingerprints)
[1] 1107
length(nzv)
[1] 719
# remove near - zero - variance predictorsfingerprints_filtered <- fingerprints[, -nzv, drop =FALSE]# number of predictor remainingncol(fingerprints_filtered)
The fingerprint dataset initially contained 1107 predictors. I applied the nearZeroVar() function from the caret package to identify predictors with little or no variation. After removing 719 predictors, 388 predictors remained for modeling. This preprocessing step reduces the number of uninformative predictors and may improve computational efficiency.
c. Split the data into a training and a test set, pre-process the data, and tune a PLS model. How many latent variables are optimal and what is the corresponding resampled estimate of R2?
# Combine predictors and targetmodel_data <-as.data.frame(fingerprints) |>mutate(Permeability =as.numeric(permeability))# Verify dimensionsdim(model_data)
[1] 165 1108
# Check targetsummary(model_data$Permeability)
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.06 1.55 4.91 12.24 15.47 55.60
Interpretation: Training and Test Data Preparation
The data set contains 165 molecular observations and 1,107 fingerprint predictors. The data were divided into a training set containing 133 observations (approximately 80%) and a testing set containing 32 observations (approximately 20%).
Near-zero-variance filtering was applied to the training predictors to remove variables with little or no variation. Of the original 1,107 predictors, 714 were removed, leaving 393 predictors for model development. The same predictor columns were retained in the testing data set to ensure consistency.
The response variable is molecular permeability, which is continuous. Therefore, Partial Least Squares regression was selected to predict permeability from the molecular fingerprint predictors.
Predict the response for the test set. What is the test set estimate of R2?
# Predict molecular permeability for the test setpls_predictions <-predict( pls_model,newdata = x_test_filtered)# View predictionshead(pls_predictions)
The scatterplot compares the actual permeability values with the values predicted by the Partial Least Squares (PLS) regression model. The red dashed line represents perfect predictions, where the predicted values equal the actual values.
The results show that several observations are far from the reference line, indicating substantial prediction errors. The model tends to underestimate permeability for molecules with high actual values, while overestimating permeability for some molecules with low actual values. Additionally, the model produces a negative prediction for one observation, which is not physically meaningful.
The test-set R² of 0.3561 and RMSE of 13.0724 indicate limited predictive performance. Therefore, the PLS model may provide approximate permeability estimates, but its accuracy is insufficient to reliably replace laboratory measurements.
Try building other models discussed in this chapter. Do any have better predictive performance?
#install.packages("glmnet")library(glmnet)
Warning: package 'glmnet' was built under R version 4.5.2
Loading required package: Matrix
Attaching package: 'Matrix'
The following objects are masked from 'package:tidyr':
expand, pack, unpack
# A tibble: 3 × 4
Model RMSE Rsquared MAE
<chr> <dbl> <dbl> <dbl>
1 PLS 13.1 0.356 10.1
2 Ridge 10.7 0.583 8.14
3 Lasso 13.1 0.324 10.4
ggplot(model_comparison, aes(x = Model, y = Rsquared, fill = Model)) +geom_col(width =0.6) +labs(title ="Comparison of Regression Models",x ="Regression Model",y ="Test Set R-Squared" ) +theme_minimal() +theme(legend.position ="none")
Interpretation: Comparison of Regression Models
Three regression models were evaluated to predict molecular permeability: Partial Least Squares (PLS), Ridge Regression, and Lasso Regression. Their predictive performances were compared using R-squared (R²), Root Mean Squared Error (RMSE), and Mean Absolute Error (MAE).
Ridge Regression achieved the best predictive performance, with an R² of 0.5832, RMSE of 10.6637, and MAE of 8.1449. PLS Regression achieved an R² of 0.3561, while Lasso Regression had the lowest R² of 0.3239.
These results indicate that Ridge Regression performs better than the other two models on the testing data set. Ridge Regression may be more effective because it reduces the influence of individual predictors through regularization while retaining information from all predictors.
Therefore, Ridge Regression is the preferred model among the three approaches evaluated. However, further validation would be necessary to confirm its reliability on new molecular observations.
f. Would you recommend any of your models to replace the permeability laboratory experiment?
Interpretation: Recommendation
Based on the results, I would not recommend replacing the laboratory permeability experiment entirely with any of the regression models.
Although Ridge Regression achieved the highest R² of 0.5832 and the lowest RMSE of 10.6637, its predictions still contain substantial errors. This suggests that the model does not fully capture the relationship between molecular fingerprints and permeability.
Additionally, the data set contains only 165 molecular observations, with 32 observations used for testing. This relatively small testing data set limits our confidence in the model’s ability to generalize to new molecules.
However, Ridge Regression could be useful as a preliminary screening tool to estimate molecular permeability and identify molecules that require further laboratory testing. Additional observations, external validation, and further model improvement would be necessary before considering it a replacement for laboratory experiments.
Part 6.3
a. Start R and use these commands to load the data: > library(AppliedPredictiveModeling) > data(chemicalManufacturingProcess) The matrix processPredictors contains the 57 predictors (12 describing the input biological material and 45 describing the process predictors) for the 176 manufacturing runs. yield contains the percent yield for each run.
Yield BiologicalMaterial01 BiologicalMaterial02 BiologicalMaterial03
Min. :35.25 Min. :4.580 Min. :46.87 Min. :56.97
1st Qu.:38.75 1st Qu.:5.978 1st Qu.:52.68 1st Qu.:64.98
Median :39.97 Median :6.305 Median :55.09 Median :67.22
Mean :40.18 Mean :6.411 Mean :55.69 Mean :67.70
3rd Qu.:41.48 3rd Qu.:6.870 3rd Qu.:58.74 3rd Qu.:70.43
Max. :46.34 Max. :8.810 Max. :64.75 Max. :78.25
BiologicalMaterial04 BiologicalMaterial05 BiologicalMaterial06
Min. : 9.38 Min. :13.24 Min. :40.60
1st Qu.:11.24 1st Qu.:17.23 1st Qu.:46.05
Median :12.10 Median :18.49 Median :48.46
Mean :12.35 Mean :18.60 Mean :48.91
3rd Qu.:13.22 3rd Qu.:19.90 3rd Qu.:51.34
Max. :23.09 Max. :24.85 Max. :59.38
BiologicalMaterial07 BiologicalMaterial08 BiologicalMaterial09
Min. :100.0 Min. :15.88 Min. :11.44
1st Qu.:100.0 1st Qu.:17.06 1st Qu.:12.60
Median :100.0 Median :17.51 Median :12.84
Mean :100.0 Mean :17.49 Mean :12.85
3rd Qu.:100.0 3rd Qu.:17.88 3rd Qu.:13.13
Max. :100.8 Max. :19.14 Max. :14.08
BiologicalMaterial10 BiologicalMaterial11 BiologicalMaterial12
Min. :1.770 Min. :135.8 Min. :18.35
1st Qu.:2.460 1st Qu.:143.8 1st Qu.:19.73
Median :2.710 Median :146.1 Median :20.12
Mean :2.801 Mean :147.0 Mean :20.20
3rd Qu.:2.990 3rd Qu.:149.6 3rd Qu.:20.75
Max. :6.870 Max. :158.7 Max. :22.21
ManufacturingProcess01 ManufacturingProcess02 ManufacturingProcess03
Min. : 0.00 Min. : 0.00 Min. :1.47
1st Qu.:10.80 1st Qu.:19.30 1st Qu.:1.53
Median :11.40 Median :21.00 Median :1.54
Mean :11.21 Mean :16.68 Mean :1.54
3rd Qu.:12.15 3rd Qu.:21.50 3rd Qu.:1.55
Max. :14.10 Max. :22.50 Max. :1.60
NA's :1 NA's :3 NA's :15
ManufacturingProcess04 ManufacturingProcess05 ManufacturingProcess06
Min. :911.0 Min. : 923.0 Min. :203.0
1st Qu.:928.0 1st Qu.: 986.8 1st Qu.:205.7
Median :934.0 Median : 999.2 Median :206.8
Mean :931.9 Mean :1001.7 Mean :207.4
3rd Qu.:936.0 3rd Qu.:1008.9 3rd Qu.:208.7
Max. :946.0 Max. :1175.3 Max. :227.4
NA's :1 NA's :1 NA's :2
ManufacturingProcess07 ManufacturingProcess08 ManufacturingProcess09
Min. :177.0 Min. :177.0 Min. :38.89
1st Qu.:177.0 1st Qu.:177.0 1st Qu.:44.89
Median :177.0 Median :178.0 Median :45.73
Mean :177.5 Mean :177.6 Mean :45.66
3rd Qu.:178.0 3rd Qu.:178.0 3rd Qu.:46.52
Max. :178.0 Max. :178.0 Max. :49.36
NA's :1 NA's :1
ManufacturingProcess10 ManufacturingProcess11 ManufacturingProcess12
Min. : 7.500 Min. : 7.500 Min. : 0.0
1st Qu.: 8.700 1st Qu.: 9.000 1st Qu.: 0.0
Median : 9.100 Median : 9.400 Median : 0.0
Mean : 9.179 Mean : 9.386 Mean : 857.8
3rd Qu.: 9.550 3rd Qu.: 9.900 3rd Qu.: 0.0
Max. :11.600 Max. :11.500 Max. :4549.0
NA's :9 NA's :10 NA's :1
ManufacturingProcess13 ManufacturingProcess14 ManufacturingProcess15
Min. :32.10 Min. :4701 Min. :5904
1st Qu.:33.90 1st Qu.:4828 1st Qu.:6010
Median :34.60 Median :4856 Median :6032
Mean :34.51 Mean :4854 Mean :6039
3rd Qu.:35.20 3rd Qu.:4882 3rd Qu.:6061
Max. :38.60 Max. :5055 Max. :6233
NA's :1
ManufacturingProcess16 ManufacturingProcess17 ManufacturingProcess18
Min. : 0 Min. :31.30 Min. : 0
1st Qu.:4561 1st Qu.:33.50 1st Qu.:4813
Median :4588 Median :34.40 Median :4835
Mean :4566 Mean :34.34 Mean :4810
3rd Qu.:4619 3rd Qu.:35.10 3rd Qu.:4862
Max. :4852 Max. :40.00 Max. :4971
ManufacturingProcess19 ManufacturingProcess20 ManufacturingProcess21
Min. :5890 Min. : 0 Min. :-1.8000
1st Qu.:6001 1st Qu.:4553 1st Qu.:-0.6000
Median :6022 Median :4582 Median :-0.3000
Mean :6028 Mean :4556 Mean :-0.1642
3rd Qu.:6050 3rd Qu.:4610 3rd Qu.: 0.0000
Max. :6146 Max. :4759 Max. : 3.6000
ManufacturingProcess22 ManufacturingProcess23 ManufacturingProcess24
Min. : 0.000 Min. :0.000 Min. : 0.000
1st Qu.: 3.000 1st Qu.:2.000 1st Qu.: 4.000
Median : 5.000 Median :3.000 Median : 8.000
Mean : 5.406 Mean :3.017 Mean : 8.834
3rd Qu.: 8.000 3rd Qu.:4.000 3rd Qu.:14.000
Max. :12.000 Max. :6.000 Max. :23.000
NA's :1 NA's :1 NA's :1
ManufacturingProcess25 ManufacturingProcess26 ManufacturingProcess27
Min. : 0 Min. : 0 Min. : 0
1st Qu.:4832 1st Qu.:6020 1st Qu.:4560
Median :4855 Median :6047 Median :4587
Mean :4828 Mean :6016 Mean :4563
3rd Qu.:4877 3rd Qu.:6070 3rd Qu.:4609
Max. :4990 Max. :6161 Max. :4710
NA's :5 NA's :5 NA's :5
ManufacturingProcess28 ManufacturingProcess29 ManufacturingProcess30
Min. : 0.000 Min. : 0.00 Min. : 0.000
1st Qu.: 0.000 1st Qu.:19.70 1st Qu.: 8.800
Median :10.400 Median :19.90 Median : 9.100
Mean : 6.592 Mean :20.01 Mean : 9.161
3rd Qu.:10.750 3rd Qu.:20.40 3rd Qu.: 9.700
Max. :11.500 Max. :22.00 Max. :11.200
NA's :5 NA's :5 NA's :5
ManufacturingProcess31 ManufacturingProcess32 ManufacturingProcess33
Min. : 0.00 Min. :143.0 Min. :56.00
1st Qu.:70.10 1st Qu.:155.0 1st Qu.:62.00
Median :70.80 Median :158.0 Median :64.00
Mean :70.18 Mean :158.5 Mean :63.54
3rd Qu.:71.40 3rd Qu.:162.0 3rd Qu.:65.00
Max. :72.50 Max. :173.0 Max. :70.00
NA's :5 NA's :5
ManufacturingProcess34 ManufacturingProcess35 ManufacturingProcess36
Min. :2.300 Min. :463.0 Min. :0.01700
1st Qu.:2.500 1st Qu.:490.0 1st Qu.:0.01900
Median :2.500 Median :495.0 Median :0.02000
Mean :2.494 Mean :495.6 Mean :0.01957
3rd Qu.:2.500 3rd Qu.:501.5 3rd Qu.:0.02000
Max. :2.600 Max. :522.0 Max. :0.02200
NA's :5 NA's :5 NA's :5
ManufacturingProcess37 ManufacturingProcess38 ManufacturingProcess39
Min. :0.000 Min. :0.000 Min. :0.000
1st Qu.:0.700 1st Qu.:2.000 1st Qu.:7.100
Median :1.000 Median :3.000 Median :7.200
Mean :1.014 Mean :2.534 Mean :6.851
3rd Qu.:1.300 3rd Qu.:3.000 3rd Qu.:7.300
Max. :2.300 Max. :3.000 Max. :7.500
ManufacturingProcess40 ManufacturingProcess41 ManufacturingProcess42
Min. :0.00000 Min. :0.00000 Min. : 0.00
1st Qu.:0.00000 1st Qu.:0.00000 1st Qu.:11.40
Median :0.00000 Median :0.00000 Median :11.60
Mean :0.01771 Mean :0.02371 Mean :11.21
3rd Qu.:0.00000 3rd Qu.:0.00000 3rd Qu.:11.70
Max. :0.10000 Max. :0.20000 Max. :12.10
NA's :1 NA's :1
ManufacturingProcess43 ManufacturingProcess44 ManufacturingProcess45
Min. : 0.0000 Min. :0.000 Min. :0.000
1st Qu.: 0.6000 1st Qu.:1.800 1st Qu.:2.100
Median : 0.8000 Median :1.900 Median :2.200
Mean : 0.9119 Mean :1.805 Mean :2.138
3rd Qu.: 1.0250 3rd Qu.:1.900 3rd Qu.:2.300
Max. :11.0000 Max. :2.100 Max. :2.600
b. A small percentage of cells in the predictor set contain missing values. Use an imputation function to fill in these missing values (e.g., see Sect. 3.8).
## Separate predictors and responseprocess_predictors <- ChemicalManufacturingProcess |>select(-Yield)yield <-as.numeric(ChemicalManufacturingProcess$Yield)# Missing values in predictorssum(is.na(process_predictors))
[1] 106
# Number of missing values per predictormissing_counts <-colSums(is.na(process_predictors))# Display only predictors with missing valuesmissing_counts[missing_counts >0]
c. Split the data into a training and a test set, pre-process the data, and tune a model of your choice from this chapter. What is the optimal value of the performance metric?
# Define preprocessing using training data onlypreprocess_model <-preProcess( x_train,method =c("medianImpute", "nzv", "center", "scale"))# Apply the same preprocessing to both datasetsx_train_processed <-predict(preprocess_model, x_train)x_test_processed <-predict(preprocess_model, x_test)# Verify missing valuessum(is.na(x_train_processed))
# Verify imputationcat("Missing values before imputation:",sum(is.na(x_train)), "\n")
Missing values before imputation: 75
cat("Missing values after imputation:",sum(is.na(x_train_processed)), "\n")
Missing values after imputation: 0
cat("Missing values in processed test data:",sum(is.na(x_test_processed)), "\n")
Missing values in processed test data: 0
Interpretation: Ridge Regression Model
The Chemical Manufacturing Process data set contains 176 observations and 57 predictor variables. The response variable is manufacturing yield, expressed as a percentage.
The data set was divided into training and testing sets, and missing predictor values were handled using median imputation. Near-zero-variance filtering, centering, and scaling were applied during model preprocessing.
Ridge Regression was selected to predict manufacturing yield. Repeated 10-fold cross-validation was used to tune the regularization parameter, lambda, with RMSE as the performance metric.
The model achieved a cross-validated RMSE of approximately 1.4073. This indicates that the model’s prediction errors have a root mean squared magnitude of approximately 1.41 percentage points during cross-validation.
d. Predict the response for the test set. What is the value of the performance metric and how does this compare with the resampled performance metric on the training set?
# Predict response for the test setridge_predictions <-predict( ridge_model,newdata = x_test)# Calculate test performanceridge_test_results <-postResample(pred = ridge_predictions,obs = y_test)ridge_test_results
RMSE Rsquared MAE
1.2210206 0.6871973 0.9159219
# Compare training CV and test RMSEperformance_comparison <-tibble(Dataset =c("Cross-validation", "Test"),RMSE =c(min(ridge_model$results$RMSE),unname(ridge_test_results["RMSE"]) ))performance_comparison
# A tibble: 2 × 2
Dataset RMSE
<chr> <dbl>
1 Cross-validation 1.41
2 Test 1.22
The Ridge Regression model was evaluated on the testing data set to determine its predictive performance on unseen observations.
The model achieved a test RMSE of approximately 1.2210, compared with a cross-validated RMSE of 1.4073. The lower test RMSE indicates that the model performed slightly better on the held-out observations than during cross-validation.
The actual-versus-predicted scatterplot shows that several observations are close to the diagonal reference line, indicating reasonably accurate predictions. However, some observations are farther from the line, showing that prediction errors remain.
Overall, the results suggest that Ridge Regression provides useful predictions of manufacturing yield, although additional testing would help establish its reliability on future manufacturing runs.
e. Which predictors are most important in the model you have trained? Do either the biological or process predictors dominate the list?
The variable importance analysis identified the predictors that contributed most strongly to the Ridge Regression model.
The five most important predictors were ManufacturingProcess32, ManufacturingProcess09, ManufacturingProcess36, ManufacturingProcess13, and ManufacturingProcess17. ManufacturingProcess32 had the highest relative importance.
Among the top 15 predictors, 13 were manufacturing process variables, while only two were biological material variables: BiologicalMaterial03 and BiologicalMaterial06.
These findings indicate that manufacturing process variables dominate the list of important predictors. This suggests that process conditions may play an important role in predicting manufacturing yield. However, the importance rankings do not establish a causal relationship between the predictors and yield.
f. Explore the relationships between each of the top predictors and the response. How could this information be helpful in improving yield in future runs of the manufacturing process?
# Prepare the datarelationship_data <- x_train |>mutate(Yield = y_train) |>select(Yield, all_of(top_5_predictors)) |>pivot_longer(cols =-Yield,names_to ="Predictor",values_to ="Value" ) |>filter(!is.na(Value), !is.na(Yield))# Plot the relationshipggplot( relationship_data,aes(x = Value, y = Yield)) +geom_point(color ="steelblue",alpha =0.6 ) +geom_smooth(method ="lm",se =FALSE,color ="red",na.rm =TRUE ) +facet_wrap(~ Predictor,scales ="free_x" ) +labs(title ="Relationships Between Top Predictors and Yield",x ="Predictor Value",y ="Manufacturing Yield (%)" ) +theme_minimal()
`geom_smooth()` using formula = 'y ~ x'
Interpretation: Relationships Between Important Predictors and Manufacturing Yield
The relationships between the five most important predictors and manufacturing yield were examined using scatterplots with fitted linear regression lines.
ManufacturingProcess32 and ManufacturingProcess09 showed positive relationships with yield. This indicates that manufacturing runs with higher values of these predictors generally achieved higher yields.
In contrast, ManufacturingProcess36, ManufacturingProcess13, and ManufacturingProcess17 showed negative relationships with yield. Higher values of these predictors were generally associated with lower manufacturing yields.
These findings suggest that understanding and monitoring important manufacturing process variables may help improve production efficiency. For example, future experiments could investigate whether adjusting process conditions associated with higher yields leads to improved manufacturing performance.
However, these relationships are observational and do not establish causation. Controlled experiments and further analysis would be necessary to determine which process adjustments can reliably increase yield.