Project Background We will learn to use the best regression model using concrete dataset. We want to know the relationship among variables, especially between the strenth with other variables. We also want to predict the strength based on the test data. This problem was originally proposed by Prof. I-Cheng Yeh, Department of Information Management Chung-Hua University, Hsin Chu, Taiwan in 2007. It is related to his research in 1998 about how to predict compression strength in a concrete structure. Concrete is the most important material in civil engineering.
DATA PREPARATION
Load the requirement library packages
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats 1.0.0 ✔ readr 2.1.4
## ✔ ggplot2 3.4.3 ✔ stringr 1.5.0
## ✔ lubridate 1.9.3 ✔ tibble 3.2.1
## ✔ purrr 1.0.2 ✔ tidyr 1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
library(naniar) #Check Missing value using visual interpretation
# Modeling and Evaluation
library(car)## Loading required package: carData
##
## Attaching package: 'car'
##
## The following object is masked from 'package:purrr':
##
## some
##
## The following object is masked from 'package:dplyr':
##
## recode
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
##
## Attaching package: 'randomForest'
##
## The following object is masked from 'package:ggplot2':
##
## margin
##
## The following object is masked from 'package:dplyr':
##
## combine
## Warning: package 'yardstick' was built under R version 4.3.2
##
## Attaching package: 'yardstick'
##
## The following object is masked from 'package:readr':
##
## spec
## Loading required package: zoo
##
## Attaching package: 'zoo'
##
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
## Loading required package: lattice
##
## Attaching package: 'caret'
##
## The following objects are masked from 'package:yardstick':
##
## precision, recall, sensitivity, specificity
##
## The following object is masked from 'package:purrr':
##
## lift
## Warning: package 'lime' was built under R version 4.3.2
##
## Attaching package: 'lime'
##
## The following object is masked from 'package:dplyr':
##
## explain
# Set theme for visualization
theme_set(theme_minimal())
options(scipen = 999)
#The scipen value is an indicator of the integer's prompt for exponential notation
options(scipen = 100, max.print = 1e+06)
# chunk options
knitr::opts_chunk$set(
message = FALSE,
warning = FALSE
)Load Data Concrete compression strength is determined not
just only by water-cement mixture but also by other ingredients, and how
we treat the mixture. Using this dataset, we are going to find “the
perfect recipe” to predict the concrete’s compression strength, and how
to explain the relationship between
the ingredients concentration and the age of
testing to the compression strength.
#DATA WRANGLING & CLEANSING DATA Data wrangling is the process of converting raw data into a usable form
#Reading training dataset
concrete <- read.csv('data-train.csv')
#Removing the column "id" due to unnecessary row numbering data
concrete <- concrete %>% select(-id) ##Cleansing unnecessary data
concrete$strength <- sqrt(concrete$strength)
concrete$coarse_agg <- sqrt(concrete$coarse_agg)
concrete$fine_agg <- sqrt(concrete$fine_agg)
concrete$cement <- sqrt(concrete$cement)
concrete$slag <- sqrt(concrete$slag)
concrete$flyash <- sqrt(concrete$flyash)
concrete$water <- sqrt(concrete$water)
concrete$age <- sqrt(concrete$age)
concrete$super_plast <- sqrt(concrete$super_plast)
head(concrete) The observation data consists of the following variables:
id: Id of each cement mixture,cement: The amount of cement (Kg) in a m3 mixture,slag: The amount of blast furnace slag (Kg) in a m3
mixture,flyash: The amount of fly ash (Kg) in a m3
mixture,water: The amount of water (Kg) in a m3 mixture,super_plast: The amount of Superplasticizer (Kg) in a
m3 mixture,coarse_agg: The amount of Coarse Aggreagate (Kg) in a
m3 mixture,fine_agg: The amount of Fine Aggreagate (Kg) in a m3
mixture,age: the number of resting days before the compressive
strength measurement,strength: Concrete compressive strength measurement in
MPa unit.#EXPLORATORY DATA ANALYSIS (EDA) 💡 One of the first steps of any data analysis project is exploratory data analysis. This involves exploring a dataset in three ways: 1. Summarizing a dataset using statistics. 2. Visualizing a dataset using charts or box plot 3. Identifying missing values.
##Checking the data type #1summary
## cement slag flyash water
## Min. :10.10 Min. : 0.000 Min. : 0.000 Min. :11.04
## 1st Qu.:13.95 1st Qu.: 0.000 1st Qu.: 0.000 1st Qu.:12.84
## Median :16.59 Median : 4.472 Median : 0.000 Median :13.56
## Mean :16.47 Mean : 5.983 Mean : 4.881 Mean :13.43
## 3rd Qu.:18.71 3rd Qu.:11.887 3rd Qu.:10.872 3rd Qu.:13.86
## Max. :23.24 Max. :18.958 Max. :14.146 Max. :15.72
## super_plast coarse_agg fine_agg age
## Min. :0.000 Min. :28.30 Min. :24.37 Min. : 1.000
## 1st Qu.:0.000 1st Qu.:30.53 1st Qu.:27.09 1st Qu.: 2.646
## Median :2.550 Median :31.11 Median :27.93 Median : 5.292
## Mean :1.950 Mean :31.17 Mean :27.81 Mean : 5.743
## 3rd Qu.:3.178 3rd Qu.:32.07 3rd Qu.:28.75 3rd Qu.: 7.483
## Max. :5.675 Max. :33.84 Max. :31.51 Max. :19.105
## strength
## Min. :1.526
## 1st Qu.:4.862
## Median :5.880
## Mean :5.804
## 3rd Qu.:6.778
## Max. :9.088
##Checking the data type #2 glimpse to detect dimension
of our dataset and data type of each columns.
## Rows: 825
## Columns: 9
## $ cement <dbl> 23.23790, 23.23790, 18.23458, 18.23458, 14.09255, 19.49359…
## $ slag <dbl> 0.000000, 0.000000, 11.937336, 11.937336, 11.506520, 9.746…
## $ flyash <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ water <dbl> 12.72792, 12.72792, 15.09967, 15.09967, 13.85641, 15.09967…
## $ super_plast <dbl> 1.581139, 1.581139, 0.000000, 0.000000, 0.000000, 0.000000…
## $ coarse_agg <dbl> 32.24903, 32.48076, 30.52868, 30.52868, 31.27939, 30.52868…
## $ fine_agg <dbl> 26.00000, 26.00000, 24.37212, 24.37212, 28.73152, 24.37212…
## $ age <dbl> 5.291503, 5.291503, 16.431677, 19.104973, 18.973666, 19.10…
## $ strength <dbl> 8.943713, 7.867020, 6.345865, 6.407027, 6.655825, 6.610598…
##Visualizing data using boxplot
boxplot(concrete, las = 2, col = c('red','sienna','palevioletred1','royalblue2','yellow','green','green','royalblue1','orange'),
main="Concrete Data Regression-Training Data")##Identifying missing value We will check whether there are any missing values in the data.
## cement slag flyash water super_plast coarse_agg
## 0 0 0 0 0 0
## fine_agg age strength
## 0 0 0
💡 Summary Insight: Our training dataset consists of 825
rows and 9 columns after [id] column has been removed in the first step.
There are 8 columns as summary result above, it is
shown that both of coarse_agg and fine_agg are
suspected to be scaled down while super_plast have to be
scaled up. Outlier data can be traced using box plot representation
above, slag; water; super_plast;
fine_agg ; age; strength columns
have some outlier data in this dataset. We do not have missing value
data. Then, we will try to continue build this regression model with
still using the outlier data to seek the sensitivity of outlier data to
the final prediction result.
#CORRELATION BETWEEN VARIABLES We will try to find the correlation between numeric variables.
#Create a heat map correlation of each variable
ggcorr(concrete, label = T, label_size = 2.9, hjust = 1, layout.exp = 3)
💡 Insight: The
strength target variable has
strong correlation with cement, super_plast
and age. This is not surprising, since as said by
Prof. I-Cheng Yeh, concrete compression strength is determined not just
only by water-cement mixture but also by other ingredients. We will try
to prove this point. Explore the relation between the target and
the features BY INTERPRETING THE HEAT MAP - Is strength
positively correlated with age? YES - Is strength and cement
has strong correlation? YES ==> POSITIVE CORR - Is
super_plast has a linear correlation with the strength? YES
==> POSITIVE CORR
#CROSS VALIDATION FOR DATA PRE-PROCESSING Now that we’ve explore some insight from our data, we will start to split the data into training set and testing set, with 80% of the data will be the training set.
set.seed(123)
samplesize <- round(0.8 * nrow(concrete), 0)
index <- sample(seq_len(nrow(concrete)), size = samplesize)
data_train <- concrete[index, ] #defined as training data
data_test <- concrete[-index, ] #defined as test data#MODEL FITTING AND EVALUATION
LINEAR REGRESSION As a common practice, we will build the basic linear regression model to fit the data.
#Build linear model using all columns
concrete_lm_all <- lm(formula = strength~. , data = data_train)
summary(concrete_lm_all)##
## Call:
## lm(formula = strength ~ ., data = data_train)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.55635 -0.43660 0.06431 0.50426 2.08681
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -4.067616 3.352408 -1.213 0.22544
## cement 0.318817 0.018849 16.914 < 0.0000000000000002 ***
## slag 0.108155 0.009776 11.063 < 0.0000000000000002 ***
## flyash 0.059357 0.010686 5.555 0.0000000406 ***
## water -0.235681 0.074740 -3.153 0.00169 **
## super_plast 0.186964 0.032795 5.701 0.0000000181 ***
## coarse_agg 0.126291 0.040900 3.088 0.00210 **
## fine_agg 0.042524 0.038797 1.096 0.27346
## age 0.240421 0.008432 28.512 < 0.0000000000000002 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.7135 on 651 degrees of freedom
## Multiple R-squared: 0.753, Adjusted R-squared: 0.75
## F-statistic: 248.1 on 8 and 651 DF, p-value: < 0.00000000000000022
From the summary above, We got the updated P-value 0.00000000000000022 < 0,05, while the adjusted R-squared is only 0.75, still below the best practice standard. Hence, we need to conduct stepwise regresion evaluation (backward, forward, and both)
##Feature Selection Using Step-wise Regression
Step-wise regression assists us in selecting suitable predictors by searching for the optimal model based on the AIC value.
There are three techniques to step-wise regression: 1. Backward 2. Forward 3. Both
#stepwise regression: backward elimination method
model_backward <- step(object = concrete_lm_all, direction = "backward")## Start: AIC=-436.62
## strength ~ cement + slag + flyash + water + super_plast + coarse_agg +
## fine_agg + age
##
## Df Sum of Sq RSS AIC
## - fine_agg 1 0.61 332.04 -437.40
## <none> 331.43 -436.62
## - coarse_agg 1 4.85 336.28 -429.03
## - water 1 5.06 336.49 -428.62
## - flyash 1 15.71 347.14 -408.06
## - super_plast 1 16.55 347.98 -406.47
## - slag 1 62.31 393.74 -324.92
## - cement 1 145.65 477.08 -198.21
## - age 1 413.87 745.30 96.22
##
## Step: AIC=-437.4
## strength ~ cement + slag + flyash + water + super_plast + coarse_agg +
## age
##
## Df Sum of Sq RSS AIC
## <none> 332.04 -437.40
## - coarse_agg 1 5.64 337.69 -428.28
## - water 1 16.10 348.14 -408.16
## - super_plast 1 16.35 348.39 -407.68
## - flyash 1 18.94 350.98 -402.79
## - slag 1 127.97 460.02 -224.25
## - cement 1 317.82 649.87 3.79
## - age 1 413.50 745.54 94.43
# model without predictor
concrete_model_none <- lm(strength ~ 1, data = concrete)
concrete_part <- lm(strength ~. -coarse_agg - flyash, data = concrete)
summary(concrete_part)##
## Call:
## lm(formula = strength ~ . - coarse_agg - flyash, data = concrete)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.45957 -0.47682 0.05487 0.54079 1.93002
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 8.524650 1.159378 7.353 0.000000000000472 ***
## cement 0.228363 0.009484 24.078 < 0.0000000000000002 ***
## slag 0.061397 0.004759 12.902 < 0.0000000000000002 ***
## water -0.422078 0.048366 -8.727 < 0.0000000000000002 ***
## super_plast 0.264114 0.021804 12.113 < 0.0000000000000002 ***
## fine_agg -0.109392 0.022106 -4.948 0.000000908664000 ***
## age 0.234718 0.007632 30.756 < 0.0000000000000002 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.7444 on 818 degrees of freedom
## Multiple R-squared: 0.7389, Adjusted R-squared: 0.7369
## F-statistic: 385.7 on 6 and 818 DF, p-value: < 0.00000000000000022
#stepwise regression: forward method
model_forward <- step(object = concrete_model_none,
direction = "forward",
scope = list(lower = concrete_model_none, upper = concrete_lm_all))## Start: AIC=615.6
## strength ~ 1
##
## Df Sum of Sq RSS AIC
## + age 1 421.97 1313.7 387.80
## + cement 1 410.90 1324.8 394.72
## + super_plast 1 207.83 1527.8 512.38
## + water 1 126.55 1609.1 555.14
## + fine_agg 1 71.77 1663.9 582.76
## + slag 1 41.81 1693.8 597.48
## + coarse_agg 1 34.06 1701.6 601.25
## + flyash 1 5.76 1729.9 614.86
## <none> 1735.7 615.60
##
## Step: AIC=387.8
## strength ~ age
##
## Df Sum of Sq RSS AIC
## + cement 1 380.62 933.06 107.55
## + super_plast 1 316.55 997.13 162.34
## + water 1 257.72 1055.96 209.63
## + slag 1 52.00 1261.69 356.48
## + fine_agg 1 36.99 1276.69 366.23
## + coarse_agg 1 35.14 1278.54 367.43
## <none> 1313.68 387.80
## + flyash 1 0.14 1313.55 389.71
##
## Step: AIC=107.55
## strength ~ age + cement
##
## Df Sum of Sq RSS AIC
## + super_plast 1 315.726 617.34 -231.224
## + water 1 199.416 733.65 -88.818
## + slag 1 160.075 772.99 -45.724
## + flyash 1 56.588 876.48 57.933
## + coarse_agg 1 15.786 917.28 95.472
## + fine_agg 1 2.963 930.10 106.925
## <none> 933.06 107.549
##
## Step: AIC=-231.22
## strength ~ age + cement + super_plast
##
## Df Sum of Sq RSS AIC
## + slag 1 120.844 496.49 -408.95
## + fine_agg 1 25.664 591.67 -264.25
## + water 1 14.804 602.53 -249.25
## + flyash 1 11.444 605.89 -244.66
## <none> 617.34 -231.22
## + coarse_agg 1 0.264 617.07 -229.58
##
## Step: AIC=-408.95
## strength ~ age + cement + super_plast + slag
##
## Df Sum of Sq RSS AIC
## + water 1 29.6658 466.83 -457.78
## + coarse_agg 1 21.5267 474.97 -443.52
## + flyash 1 14.7630 481.73 -431.85
## <none> 496.49 -408.95
## + fine_agg 1 1.0357 495.46 -408.67
##
## Step: AIC=-457.78
## strength ~ age + cement + super_plast + slag + water
##
## Df Sum of Sq RSS AIC
## + flyash 1 26.2144 440.61 -503.45
## + fine_agg 1 13.5682 453.26 -480.11
## + coarse_agg 1 6.3867 460.44 -467.14
## <none> 466.83 -457.78
##
## Step: AIC=-503.45
## strength ~ age + cement + super_plast + slag + water + flyash
##
## Df Sum of Sq RSS AIC
## + coarse_agg 1 7.0346 433.58 -514.73
## + fine_agg 1 2.7581 437.85 -506.63
## <none> 440.61 -503.45
##
## Step: AIC=-514.73
## strength ~ age + cement + super_plast + slag + water + flyash +
## coarse_agg
##
## Df Sum of Sq RSS AIC
## <none> 433.58 -514.73
## + fine_agg 1 0.20351 433.37 -513.12
#stepwise regression: both method
model_both <- step(object = concrete_model_none, direction = "both", scope = list(upper = concrete_lm_all))## Start: AIC=615.6
## strength ~ 1
##
## Df Sum of Sq RSS AIC
## + age 1 421.97 1313.7 387.80
## + cement 1 410.90 1324.8 394.72
## + super_plast 1 207.83 1527.8 512.38
## + water 1 126.55 1609.1 555.14
## + fine_agg 1 71.77 1663.9 582.76
## + slag 1 41.81 1693.8 597.48
## + coarse_agg 1 34.06 1701.6 601.25
## + flyash 1 5.76 1729.9 614.86
## <none> 1735.7 615.60
##
## Step: AIC=387.8
## strength ~ age
##
## Df Sum of Sq RSS AIC
## + cement 1 380.62 933.06 107.55
## + super_plast 1 316.55 997.13 162.34
## + water 1 257.72 1055.96 209.63
## + slag 1 52.00 1261.69 356.48
## + fine_agg 1 36.99 1276.69 366.23
## + coarse_agg 1 35.14 1278.54 367.43
## <none> 1313.68 387.80
## + flyash 1 0.14 1313.55 389.71
## - age 1 421.97 1735.66 615.60
##
## Step: AIC=107.55
## strength ~ age + cement
##
## Df Sum of Sq RSS AIC
## + super_plast 1 315.73 617.34 -231.22
## + water 1 199.42 733.65 -88.82
## + slag 1 160.08 772.99 -45.72
## + flyash 1 56.59 876.48 57.93
## + coarse_agg 1 15.79 917.28 95.47
## + fine_agg 1 2.96 930.10 106.92
## <none> 933.06 107.55
## - cement 1 380.62 1313.68 387.80
## - age 1 391.70 1324.76 394.72
##
## Step: AIC=-231.22
## strength ~ age + cement + super_plast
##
## Df Sum of Sq RSS AIC
## + slag 1 120.84 496.49 -408.95
## + fine_agg 1 25.66 591.67 -264.25
## + water 1 14.80 602.53 -249.25
## + flyash 1 11.44 605.89 -244.66
## <none> 617.34 -231.22
## + coarse_agg 1 0.26 617.07 -229.58
## - super_plast 1 315.73 933.06 107.55
## - cement 1 379.80 997.13 162.34
## - age 1 496.87 1114.20 253.92
##
## Step: AIC=-408.95
## strength ~ age + cement + super_plast + slag
##
## Df Sum of Sq RSS AIC
## + water 1 29.67 466.83 -457.78
## + coarse_agg 1 21.53 474.97 -443.52
## + flyash 1 14.76 481.73 -431.85
## <none> 496.49 -408.95
## + fine_agg 1 1.04 495.46 -408.67
## - slag 1 120.84 617.34 -231.22
## - super_plast 1 276.50 772.99 -45.72
## - cement 1 469.44 965.94 138.11
## - age 1 502.77 999.26 166.10
##
## Step: AIC=-457.78
## strength ~ age + cement + super_plast + slag + water
##
## Df Sum of Sq RSS AIC
## + flyash 1 26.21 440.61 -503.45
## + fine_agg 1 13.57 453.26 -480.11
## + coarse_agg 1 6.39 460.44 -467.14
## <none> 466.83 -457.78
## - water 1 29.67 496.49 -408.95
## - super_plast 1 88.38 555.21 -316.74
## - slag 1 135.71 602.53 -249.25
## - cement 1 444.28 911.11 91.90
## - age 1 529.51 996.34 165.68
##
## Step: AIC=-503.45
## strength ~ age + cement + super_plast + slag + water + flyash
##
## Df Sum of Sq RSS AIC
## + coarse_agg 1 7.03 433.58 -514.73
## + fine_agg 1 2.76 437.85 -506.63
## <none> 440.61 -503.45
## - super_plast 1 13.26 453.87 -480.99
## - flyash 1 26.21 466.83 -457.78
## - water 1 41.12 481.73 -431.85
## - slag 1 152.57 593.18 -260.16
## - cement 1 390.71 831.32 18.30
## - age 1 539.51 980.13 154.15
##
## Step: AIC=-514.73
## strength ~ age + cement + super_plast + slag + water + flyash +
## coarse_agg
##
## Df Sum of Sq RSS AIC
## <none> 433.58 -514.73
## + fine_agg 1 0.20 433.37 -513.12
## - coarse_agg 1 7.03 440.61 -503.45
## - super_plast 1 18.77 452.34 -481.77
## - water 1 22.04 455.62 -475.83
## - flyash 1 26.86 460.44 -467.14
## - slag 1 158.90 592.48 -259.13
## - cement 1 394.50 828.08 17.07
## - age 1 534.44 968.01 145.89
#Summarize R-squared adjusted after conducting stepwise regression
round(summary(model_backward)$adj.r.squared,4)## [1] 0.7499
## [1] 0.7369
## [1] 0.7481
## [1] 0.7481
The model has an Adjusted R-Squared of 74,99% for
model_backward, It does not significantly improved to our
R-squared. But, we might also interested in seeing how good the model
once we remove the outlier data in training dataset.
##REMOVING OUTLIER DATA
#Create Outlier function detection
outliers <- function(x) {
Q1 <- quantile(x, probs=.25)
Q3 <- quantile(x, probs=.75)
iqr = Q3-Q1
upper_limit = Q3 + (iqr*1.5)
lower_limit = Q1 - (iqr*1.5)
x > upper_limit | x < lower_limit
}
remove_outliers <- function(concrete, cols = names(concrete)) {
for (col in cols) {
concrete <- concrete[!outliers(concrete[[col]]),]
}
concrete
}
#Assignment remove outlier function
concrete<- remove_outliers(concrete)
dim(concrete) ##Check dimension dataset after removing the outlier data## [1] 764 9
#Visualize data after removing outlier using boxplot
boxplot(concrete, las = 2, col = c('red','sienna','palevioletred1','royalblue2','yellow','green','green','royalblue1','orange'),
main="Concrete Data Regression-Training Data-Remove Outlier")
##RE-DEFINED CROSS VALIDATION DATA
set.seed(123)
samplesize <- round(0.8 * nrow(concrete), 0)
index <- sample(seq_len(nrow(concrete)), size = samplesize)
data_train <- concrete[index, ] #defined as training data1
data_test <- concrete[-index, ] #defined as test data1##RE-BUILD LINEAR REGRESSION
#Build linear model using all columns
concrete_lm_all1 <- lm(formula = strength~. , data = data_train)
summary(concrete_lm_all1)##
## Call:
## lm(formula = strength ~ ., data = data_train)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.92366 -0.35764 -0.01246 0.45542 1.82855
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 5.740371 3.184833 1.802 0.071981 .
## cement 0.287928 0.017117 16.821 < 0.0000000000000002 ***
## slag 0.096229 0.008690 11.073 < 0.0000000000000002 ***
## flyash 0.043377 0.009509 4.562 0.0000061503742 ***
## water -0.512380 0.075673 -6.771 0.0000000000304 ***
## super_plast 0.113823 0.031193 3.649 0.000286 ***
## coarse_agg 0.035810 0.037991 0.943 0.346273
## fine_agg -0.059489 0.036457 -1.632 0.103248
## age 0.315569 0.009185 34.357 < 0.0000000000000002 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.6201 on 602 degrees of freedom
## Multiple R-squared: 0.8181, Adjusted R-squared: 0.8156
## F-statistic: 338.4 on 8 and 602 DF, p-value: < 0.00000000000000022
#stepwise regression: backward elimination method
model_backward1 <- step(object = concrete_lm_all1, direction = "backward")## Start: AIC=-574.97
## strength ~ cement + slag + flyash + water + super_plast + coarse_agg +
## fine_agg + age
##
## Df Sum of Sq RSS AIC
## - coarse_agg 1 0.34 231.85 -576.07
## <none> 231.51 -574.97
## - fine_agg 1 1.02 232.53 -574.27
## - super_plast 1 5.12 236.63 -563.60
## - flyash 1 8.00 239.51 -556.21
## - water 1 17.63 249.14 -532.13
## - slag 1 47.16 278.66 -463.70
## - cement 1 108.81 340.32 -341.56
## - age 1 453.94 685.44 86.25
##
## Step: AIC=-576.07
## strength ~ cement + slag + flyash + water + super_plast + fine_agg +
## age
##
## Df Sum of Sq RSS AIC
## <none> 231.85 -576.07
## - fine_agg 1 4.63 236.47 -566.00
## - super_plast 1 4.79 236.64 -565.57
## - flyash 1 8.16 240.01 -556.93
## - water 1 43.42 275.27 -473.18
## - slag 1 80.21 312.06 -396.54
## - cement 1 183.32 415.17 -222.09
## - age 1 457.10 688.94 87.36
# model without predictor
concrete_model_none1 <- lm(strength ~ 1, data = concrete)
#stepwise regression: forward method
model_forward1 <- step(object = concrete_model_none1,
direction = "forward",
scope = list(lower = concrete_model_none1, upper = concrete_lm_all1))## Start: AIC=586
## strength ~ 1
##
## Df Sum of Sq RSS AIC
## + age 1 488.44 1152.4 318.03
## + cement 1 378.14 1262.7 387.87
## + super_plast 1 253.31 1387.5 459.89
## + water 1 227.62 1413.2 473.91
## + fine_agg 1 66.23 1574.6 556.52
## + slag 1 42.48 1598.4 567.96
## + coarse_agg 1 34.93 1605.9 571.56
## <none> 1640.8 586.00
## + flyash 1 1.02 1639.8 587.52
##
## Step: AIC=318.03
## strength ~ age
##
## Df Sum of Sq RSS AIC
## + cement 1 394.21 758.19 0.17
## + water 1 274.32 878.08 112.33
## + super_plast 1 259.56 892.84 125.06
## + fine_agg 1 68.10 1084.30 273.50
## + slag 1 61.10 1091.30 278.41
## + coarse_agg 1 42.06 1110.34 291.63
## <none> 1152.40 318.03
## + flyash 1 1.33 1151.07 319.15
##
## Step: AIC=0.17
## strength ~ age + cement
##
## Df Sum of Sq RSS AIC
## + super_plast 1 248.443 509.75 -301.153
## + water 1 182.265 575.93 -207.897
## + slag 1 181.025 577.17 -206.255
## + flyash 1 39.848 718.34 -39.078
## + coarse_agg 1 19.507 738.68 -17.745
## + fine_agg 1 18.591 739.60 -16.798
## <none> 758.19 0.169
##
## Step: AIC=-301.15
## strength ~ age + cement + super_plast
##
## Df Sum of Sq RSS AIC
## + slag 1 137.619 372.13 -539.56
## + fine_agg 1 37.116 472.63 -356.91
## + water 1 20.911 488.84 -331.15
## + flyash 1 13.691 496.06 -319.95
## <none> 509.75 -301.15
## + coarse_agg 1 0.009 509.74 -299.17
##
## Step: AIC=-539.56
## strength ~ age + cement + super_plast + slag
##
## Df Sum of Sq RSS AIC
## + water 1 34.562 337.57 -612.04
## + coarse_agg 1 20.644 351.49 -581.17
## + flyash 1 17.221 354.91 -573.76
## + fine_agg 1 4.150 367.98 -546.13
## <none> 372.13 -539.56
##
## Step: AIC=-612.04
## strength ~ age + cement + super_plast + slag + water
##
## Df Sum of Sq RSS AIC
## + flyash 1 28.3112 309.26 -676.96
## + fine_agg 1 20.0744 317.49 -656.88
## + coarse_agg 1 4.9284 332.64 -621.27
## <none> 337.57 -612.04
##
## Step: AIC=-676.96
## strength ~ age + cement + super_plast + slag + water + flyash
##
## Df Sum of Sq RSS AIC
## + fine_agg 1 6.4009 302.86 -690.94
## + coarse_agg 1 5.7937 303.46 -689.41
## <none> 309.26 -676.96
##
## Step: AIC=-690.94
## strength ~ age + cement + super_plast + slag + water + flyash +
## fine_agg
##
## Df Sum of Sq RSS AIC
## <none> 302.86 -690.94
## + coarse_agg 1 0.62617 302.23 -690.52
#stepwise regression: both method
model_both1 <- step(object = concrete_model_none1, direction = "both", scope = list(upper = concrete_lm_all1))## Start: AIC=586
## strength ~ 1
##
## Df Sum of Sq RSS AIC
## + age 1 488.44 1152.4 318.03
## + cement 1 378.14 1262.7 387.87
## + super_plast 1 253.31 1387.5 459.89
## + water 1 227.62 1413.2 473.91
## + fine_agg 1 66.23 1574.6 556.52
## + slag 1 42.48 1598.4 567.96
## + coarse_agg 1 34.93 1605.9 571.56
## <none> 1640.8 586.00
## + flyash 1 1.02 1639.8 587.52
##
## Step: AIC=318.03
## strength ~ age
##
## Df Sum of Sq RSS AIC
## + cement 1 394.21 758.19 0.17
## + water 1 274.32 878.08 112.33
## + super_plast 1 259.56 892.84 125.06
## + fine_agg 1 68.10 1084.30 273.50
## + slag 1 61.10 1091.30 278.41
## + coarse_agg 1 42.06 1110.34 291.63
## <none> 1152.40 318.03
## + flyash 1 1.33 1151.07 319.15
## - age 1 488.44 1640.84 586.00
##
## Step: AIC=0.17
## strength ~ age + cement
##
## Df Sum of Sq RSS AIC
## + super_plast 1 248.44 509.75 -301.15
## + water 1 182.26 575.93 -207.90
## + slag 1 181.03 577.17 -206.25
## + flyash 1 39.85 718.34 -39.08
## + coarse_agg 1 19.51 738.68 -17.74
## + fine_agg 1 18.59 739.60 -16.80
## <none> 758.19 0.17
## - cement 1 394.21 1152.40 318.03
## - age 1 504.51 1262.70 387.87
##
## Step: AIC=-301.15
## strength ~ age + cement + super_plast
##
## Df Sum of Sq RSS AIC
## + slag 1 137.62 372.13 -539.56
## + fine_agg 1 37.12 472.63 -356.91
## + water 1 20.91 488.84 -331.15
## + flyash 1 13.69 496.06 -319.95
## <none> 509.75 -301.15
## + coarse_agg 1 0.01 509.74 -299.17
## - super_plast 1 248.44 758.19 0.17
## - cement 1 383.09 892.84 125.06
## - age 1 510.49 1020.24 226.97
##
## Step: AIC=-539.56
## strength ~ age + cement + super_plast + slag
##
## Df Sum of Sq RSS AIC
## + water 1 34.56 337.57 -612.04
## + coarse_agg 1 20.64 351.49 -581.17
## + flyash 1 17.22 354.91 -573.76
## + fine_agg 1 4.15 367.98 -546.13
## <none> 372.13 -539.56
## - slag 1 137.62 509.75 -301.15
## - super_plast 1 205.04 577.17 -206.25
## - cement 1 482.90 855.03 94.00
## - age 1 543.11 915.24 146.00
##
## Step: AIC=-612.04
## strength ~ age + cement + super_plast + slag + water
##
## Df Sum of Sq RSS AIC
## + flyash 1 28.31 309.26 -676.96
## + fine_agg 1 20.07 317.49 -656.88
## + coarse_agg 1 4.93 332.64 -621.27
## <none> 337.57 -612.04
## - water 1 34.56 372.13 -539.56
## - super_plast 1 53.16 390.73 -502.30
## - slag 1 151.27 488.84 -331.15
## - cement 1 429.73 767.30 13.29
## - age 1 562.01 899.58 134.81
##
## Step: AIC=-676.96
## strength ~ age + cement + super_plast + slag + water + flyash
##
## Df Sum of Sq RSS AIC
## + fine_agg 1 6.40 302.86 -690.94
## + coarse_agg 1 5.79 303.46 -689.41
## <none> 309.26 -676.96
## - super_plast 1 3.52 312.77 -670.32
## - flyash 1 28.31 337.57 -612.04
## - water 1 45.65 354.91 -573.76
## - slag 1 168.43 477.69 -346.78
## - cement 1 390.61 699.87 -54.98
## - age 1 574.51 883.77 123.26
##
## Step: AIC=-690.94
## strength ~ age + cement + super_plast + slag + water + flyash +
## fine_agg
##
## Df Sum of Sq RSS AIC
## <none> 302.86 -690.94
## + coarse_agg 1 0.63 302.23 -690.52
## - super_plast 1 5.50 308.36 -679.19
## - fine_agg 1 6.40 309.26 -676.96
## - flyash 1 14.64 317.49 -656.88
## - water 1 52.00 354.85 -571.88
## - slag 1 97.80 400.66 -479.13
## - cement 1 239.40 542.25 -247.92
## - age 1 572.39 875.24 117.85
#RE-CHECKING R-SQUARED OF LINEAR REGRESSION
#Summarize R-squared adjusted after conducting stepwise regression
round(summary(model_backward1)$adj.r.squared,4)## [1] 0.8157
## [1] 0.8137
## [1] 0.8137
INSIGHT: The model has an Adjusted R-Squared of 85,71% for
backward1 model, It significantly improved to our
R-squared. But, we might also interested in seeing how good the model to
predict the data test.
#EVALUATING MODEL - LINEAR REGRESSION
# Function for evaluating model
eval_recap <- function(truth, estimate){
df_new <- data.frame(truth = truth,
estimate = estimate)
data.frame(RMSE = rmse_vec(truth, estimate),
MAE = mae_vec(truth, estimate),
"R-Square" = rsq_vec(truth, estimate),
check.names = F
) %>%
mutate(MSE = sqrt(RMSE))
}
pred_test_model_backward1 <- predict(model_backward1, data_test)
round(eval_recap(truth = data_test$strength,
estimate = pred_test_model_backward1),2)Shapiro Test Shapiro-Wilk hypothesis test:
##
## Shapiro-Wilk normality test
##
## data: model_backward1$residuals
## W = 0.99396, p-value = 0.0155
Conclusion: P-value (0.2335) > alpha (0,05) => Error slightly distributed normally
Check No Multicollinearity Multicollinearity is a condition that some predictors variable are detected have strong correlation to others.
## cement slag flyash water super_plast fine_agg
## 2.394908 2.371339 3.526715 2.009733 3.306088 1.661461
## age
## 1.023056
Conclusion: From the result above, there is no multicollinearity detected from our model.
SUMMARY INSIGHT OF LINEAR MODEL: Once we use our best model (model_backward1) to our data test, the R-square is only 42%. As per mentioned earlier, model_backward1 is developed using “remove outlier data”. The interested things in our linear regression model is model which built using non-removing outlier data (model_both) is much better when testing to our data test. It can be represented by higher R-squared 62%. So … our model failed to fulfill almost all of assumptions for linear regression model. The interpretation of the estimate coefficient and the significant test would be unreliable. You might be interested in tuning the linear model to fulfill the assumption but for now, we will proceed to use more advanced models: Random Forest and Support Vector Regression (SVR).
#RANDOM FOREST Random Forest implementation come in many packages but for this post I will use randomForest() from randomForest package.
set.seed(123)
model_rf <- randomForest(x = data_train %>% select(-strength),
y = data_train$strength,
importance=TRUE, ntree = 500, mtry = 7) #initialize with ntree = 500 and mtry = 5
model_rf##
## Call:
## randomForest(x = data_train %>% select(-strength), y = data_train$strength, ntree = 500, mtry = 7, importance = TRUE)
## Type of random forest: regression
## Number of trees: 500
## No. of variables tried at each split: 7
##
## Mean of squared residuals: 0.2105174
## % Var explained: 89.89
## %IncMSE IncNodePurity
## cement 1.35330695 380.90726
## slag 0.38595723 83.09553
## flyash 0.09437549 32.16997
## water 0.51034815 149.77846
## super_plast 0.28751156 82.07884
## coarse_agg 0.09015483 38.02524
## fine_agg 0.17068359 58.40327
## age 1.68798436 429.02459
We will evaluate the Random Forest model.
pred_test <- predict(model_rf, data_test, type = "response")
round(eval_recap(truth = data_test$strength,
estimate = pred_test),2)The Random Forest model is significantly better than the linear model.
#SUPPORT VECTOR REGRESSION (SVR) SVR is a variant of Support Vector Machine for regression problem7. If you are interested in SVM, you can the article from algotech8. The SVM implementation can be acquired from the e1071 package.
model_svr <- svm(strength ~ ., data = data_train)
pred_test <- predict(model_svr, data_test)
round(eval_recap(truth = data_test$strength,
estimate = pred_test),2)The SVR model has lower performance compared to Random Forest. However, we will still use both model for further analysis both as comparison and as examples.
#DEEP-DIVE TUNING RANDOM FOREST MODEL
Plotting the model will illustrate the error rate as we average across more trees and shows that our error rate stabalizes with around 500 trees but continues to decrease slowly until around 100 or so trees.
The plotted error rate above is based on the OOB sample error and can be
accessed directly at
model_rf$mse. Thus, we can find which
number of trees providing the lowest error rate, which is 210 trees
providing an average strength error of 0.46.
## [1] 499
## [1] 0.4587704
Random forests are one of the best “out-of-the-box” machine learning algorithms. They typically perform remarkably well with very little tuning required. For example, as we saw above, we were able to get an RMSE of less than 0.015 without any tuning. However, we can still seek improvement by tuning our random forest model.
library(ranger)
# names of features
features <- setdiff(names(data_train), "strength")
# randomForest speed
system.time(
Mod_randomForest <- randomForest(
formula = strength ~ .,
data = data_train,
ntree = 500,
mtry = floor(length(features) / 3)
)
)## user system elapsed
## 0.17 0.00 0.44
pred_test <- predict(Mod_randomForest, data_test, type = "response")
round(eval_recap(truth = data_test$strength,
estimate = pred_test),2)set.seed(123)
m2 <- tuneRF(
x = data_train[features],
y = data_train$strength,
ntreeTry = 500,
mtryStart = 5,
stepFactor = 1.5,
improve = 0.01,
trace = FALSE # to not show real-time progress
)## -0.01403877 0.01
## 0.002498524 0.01
Optimizing mtry = 7 based on graph above.
OOB_RMSE <- vector(mode = "numeric", length = 100)
for(i in seq_along(OOB_RMSE)) {
optimal_ranger <- ranger(
formula = strength ~ .,
data = data_train,
num.trees = 500,
mtry = 7,
min.node.size = 5,
sample.fraction = .8,
importance = 'impurity'
)
OOB_RMSE[i] <- sqrt(optimal_ranger$prediction.error)
}
hist(OOB_RMSE, breaks = 20)
Furthermore, you may have noticed we set importance = ‘impurity’ in the
above modeling, which allows us to assess variable importance. Variable
importance is measured by recording the decrease in MSE each time a
variable is used as a node split in a tree. The remaining error left in
predictive accuracy after a node split is known as node impurity and a
variable that reduces this impurity is considered more imporant than
those variables that do not. Consequently, we accumulate the reduction
in MSE for each variable across all the trees and the variable with the
greatest accumulated impact is considered the more important, or
impactful.
library(tibble) #use function rownames_to_column
model_rf$importance %>%
as.data.frame() %>%
arrange(-IncNodePurity) %>%
rownames_to_column("variable") %>%
head(10) %>%
ggplot(aes(IncNodePurity,
reorder(variable, IncNodePurity))
) +
geom_col(fill = "firebrick") +
labs(x = "Importance",
y = NULL,
title = "Random Forest Variable Importance")
However, variable importance measures rarely give insight into the
average direction that a variable affects a response function. They
simply state the magnitude of a variable’s relationship with the
response as compared to other variables used in the model. We can’t know
specifically the influence of each factors for a single observation (no
local-fidelity). That’s why we need LIME to help us understand
individually what influence the performance of each student.
Now we will try to interpret the black box model using lime.
#EXPLAINER The first thing to is to build an explainer. This explainer object will be used as the foundation to interpret the black box model.
EXPLANATION The next thing to do is to build the explanation for each data test. The explanation will give the interpretation of the model toward each observation.
# Select only the first 4 observations
selected_data <- data_test %>%
select(-strength) %>%
slice(1:4)
model_type.randomForest <- function(x){
return("regression") # for regression problem
}
predict_model.randomForest <- function(x, newdata, type = "response") {
# return prediction value
predict(x, newdata) %>% as.data.frame()
}
set.seed(123)
explanation <- explain(x = selected_data,
explainer = explainer,
n_features = 10, # Number of features to explain the model
feature_select = "auto", # Method of feature selection for lime
)#VISUALIZATION AND INTERPRETATION Finally, we will visualize the explanation using the plot_features() function.
The case indicate the index of the data. Case : 1 indicate the first
observation, Case : 2 indicate the second observation, etc. The
prediction value show the predicted value based on the model
interpretation and prediction.
TUNING LIME You can improve the Explanation Fit by tuning the explain function parameter. The following parameter increase the explanation fit up to 90%. You can adjust the value of each parameters until you’ve found the desired explanation fit.
set.seed(123)
explanation <- explain(x = selected_data,
explainer = explainer,
dist_fun = "manhattan",
kernel_width = 2,
n_features = 10, # Number of features to explain the model
feature_select = "auto", # Method of feature selection for lime
)
plot_features(explanation)
Some parameters you can adjust in explanation function:
x = The object you want to explain explainer = the explainer object from lime function n_features = number of features used to explain the data n_permutations = number of permutations for each observation for explanation. THe default is 5000 permutations dist_fun = distance function used to calculate the distance to the permutation. The default is Gower’s distance but can also use euclidean, manhattan, or any other distance function allowed by ?dist() kernel_width = An exponential kernel of a user defined width (defaults to 0.75 times the square root of the number of features) used to
convert the distance measure to a similarity value Now the important features are changed along with the increasing explanation fit. The cement variable is still the most important feature for all observation.
#SUMMARY INSIGHT: The best model to predict is still random
forest model_rf with using tuning parameter on mtry = 7.
The most imporatance variable in this modelling is still cement
variable.
#SUBMISSION Submit to Leader board using random forest model
data_submission <- read.csv("data-test.csv")
data_submission <- data_submission %>% select(-strength)
# predict target using your model
prediction_test <- predict(model_rf, newdata = data_submission, type = "response")
prediction_test <- prediction_test^2
# Create submission data
submission <- data.frame(id = data_submission$id,
strength = prediction_test)
# save data
write.csv(submission, "submission-fajar khamim mustofa.csv", row.names = F)
head(submission)