-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab4-ExposingTheStructureOfDataUsingDataTransforms.R
More file actions
1318 lines (1084 loc) · 56.2 KB
/
Lab4-ExposingTheStructureOfDataUsingDataTransforms.R
File metadata and controls
1318 lines (1084 loc) · 56.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# *****************************************************************************
# Lab 4: Exposing the Structure of Data using Data Transforms ----
#
# Course Code: BBT4206
# Course Name: Business Intelligence II
# Semester Duration: 21st August 2023 to 28th November 2023
#
# Lecturer: Allan Omondi
# Contact: aomondi [at] strathmore.edu
#
# Note: The lecture contains both theory and practice. This file forms part of
# the practice. It has required lab work submissions that are graded for
# coursework marks.
#
# License: GNU GPL-3.0-or-later
# See LICENSE file for licensing information.
# *****************************************************************************
# **[OPTIONAL] Initialization: Install and use renv ----
# The R Environment ("renv") package helps you create reproducible environments
# for your R projects. This is helpful when working in teams because it makes
# your R projects more isolated, portable and reproducible.
# Further reading:
# Summary: https://rstudio.github.io/renv/
# More detailed article: https://rstudio.github.io/renv/articles/renv.html
# "renv" It can be installed as follows:
# if (!is.element("renv", installed.packages()[, 1])) {
# install.packages("renv", dependencies = TRUE,
# repos = "https://cloud.r-project.org") # nolint
# }
# require("renv") # nolint
# Once installed, you can then use renv::init() to initialize renv in a new
# project.
# The prompt received after executing renv::init() is as shown below:
# This project already has a lockfile. What would you like to do?
# 1: Restore the project from the lockfile.
# 2: Discard the lockfile and re-initialize the project.
# 3: Activate the project without snapshotting or installing any packages.
# 4: Abort project initialization.
# Select option 1 to restore the project from the lockfile
# renv::init() # nolint
# This will set up a project library, containing all the packages you are
# currently using. The packages (and all the metadata needed to reinstall
# them) are recorded into a lockfile, renv.lock, and a .Rprofile ensures that
# the library is used every time you open the project.
# Consider a library as the location where packages are stored.
# Execute the following command to list all the libraries available in your
# computer:
.libPaths()
# One of the libraries should be a folder inside the project if you are using
# renv
# Then execute the following command to see which packages are available in
# each library:
lapply(.libPaths(), list.files)
# This can also be configured using the RStudio GUI when you click the project
# file, e.g., "BBT4206-R.Rproj" in the case of this project. Then
# navigate to the "Environments" tab and select "Use renv with this project".
# As you continue to work on your project, you can install and upgrade
# packages, using either:
# install.packages() and update.packages or
# renv::install() and renv::update()
# You can also clean up a project by removing unused packages using the
# following command: renv::clean()
# After you have confirmed that your code works as expected, use
# renv::snapshot(), AT THE END, to record the packages and their
# sources in the lockfile.
# Later, if you need to share your code with someone else or run your code on
# a new machine, your collaborator (or you) can call renv::restore() to
# reinstall the specific package versions recorded in the lockfile.
# [OPTIONAL]
# Execute the following code to reinstall the specific package versions
# recorded in the lockfile (restart R after executing the command):
# renv::restore() # nolint
# [OPTIONAL]
# If you get several errors setting up renv and you prefer not to use it, then
# you can deactivate it using the following command (restart R after executing
# the command):
# renv::deactivate() # nolint
# If renv::restore() did not install the "languageserver" package (required to
# use R for VS Code), then it can be installed manually as follows (restart R
# after executing the command):
if (require("languageserver")) {
require("languageserver")
} else {
install.packages("languageserver", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
# Introduction ----
# Data transforms can improve the accuracy of your final model when applied as
# part of the pre-processing stage. It is standard practice to apply multiple
# transforms with a suite of different machine learning algorithms. Data
# transforms can be grouped into the following 3 categories:
# (i) Basic data transforms:
# a. Scaling: Divides each value by the standard deviation
# b. Centering: Subtracts the mean from each value
# c. Standardization: Ensures that each numeric attribute has a
# mean value of 0 and a standard deviation of 1. This is done
# by combining the scale data transform and the centre data
# transform.
# d. Normalization: Ensures the numerical data are between [0, 1]
# (inclusive).
# (ii) Power transforms:
# a. Box-Cox: reduces the skewness by shifting the distribution of
# an attribute and making the attribute have a more
# Gaussian-like distribution.
# b. Yeo-Johnson: like Box-Cox, Yeo-Johnson reduces the skewness
# by shifting the distribution of an attribute and making the
# attribute have a more Gaussian-like distribution.
# The difference is that Yeo-Johnson can handle zero and
# negative values.
# (iii) Linear algebra transforms: Principal Component Analysis (PCA) and
# Independent Component Analysis (ICA)
# The first step is to design a model of the transform using the training data.
# This results in a model of the transform that can be applied to multiple
# datasets. The preparation of the model of the transform is done using the
# preProcess() function. The model of the transform can then be applied to a
# dataset in either of the following two ways:
# (i) Standalone: The model of the transform is passed to the predict()
# function
# (ii) Training: The model of the transform is passed to the train()
# function via the preProcess argument. This is done during the model
# evaluation stage.
# Note that the preProcess() function ignores non-numeric attributes.
# STEP 1. Install and Load the Required Packages ----
## mlbench ----
if (require("mlbench")) {
require("mlbench")
} else {
install.packages("mlbench", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
## readr ----
if (require("readr")) {
require("readr")
} else {
install.packages("readr", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
## caret ----
if (require("caret")) {
require("caret")
} else {
install.packages("caret", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
## e1071 ----
if (require("e1071")) {
require("e1071")
} else {
install.packages("e1071", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
## factoextra ----
if (require("factoextra")) {
require("factoextra")
} else {
install.packages("factoextra", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
## FactoMineR ----
if (require("FactoMineR")) {
require("FactoMineR")
} else {
install.packages("FactoMineR", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
## STEP 2. Load the Datasets ----
### The Boston Housing Dataset ----
# Execute the following to load the “BostonHousing” dataset which is offered
# in the "mlbench" package:
data("BostonHousing")
### Crop Dataset ----
# Execute the following to load the downloaded Crop dataset:
crop_dataset <- read_csv("data/crop.data.csv",
col_types = cols(
density = col_factor(levels = c("1", "2")),
block = col_factor(levels = c("1", "2", "3", "4")),
fertilizer = col_factor(levels = c("1", "2", "3"))
)
)
### Iris Dataset ----
# Execute the following to load the downloaded Iris dataset:
iris_dataset <- read.csv("data/iris.data", header = FALSE,
stringsAsFactors = TRUE)
# This time, we name the attributes of the Iris Dataset as follows:
names(iris_dataset) <- c("sepal length in cm", "sepal width in cm",
"petal length in cm", "petal width in cm", "class")
### The Pima Indians Diabetes Dataset ----
# Execute the following to load the "Pima Indians Diabetes" dataset from the
# mlbench package:
data("PimaIndiansDiabetes")
# Scale Data Transform ----
## STEP 3. Apply a Scale Data Transform ----
# The scale data transform is useful for scaling data that has a Gaussian
# distribution. The scale data transform works by calculating the standard
# deviation of an attribute and then divides each value by the standard
# deviation.
### Benefits of Scaling ----
#### 1. Facilitating Algorithm Convergence ----
# Many machine learning algorithms, such as gradient descent-based methods and
# support vector machines, work more efficiently and converge faster when the
# input features are on similar scales. Rescaling the data helps prevent some
# features from dominating the learning process.
#### 2. Improving Interpretability ----
# Scaling makes it easier to compare the importance of different features in a
# model. When features have different scales, it can be challenging to
# interpret their relative contributions.
#### 3. Enhancing Model Performance ----
# Some machine learning algorithms, like k-nearest neighbors and principal
# component analysis, are sensitive to the scale of the data. Scaling can lead
# to better model performance and more reliable results.
#### 4. Handling Outliers ----
# Standardizing data can help mitigate the impact of outliers. Outliers are
# data points that are significantly different from the majority of the data.
# If not properly handled, outliers can distort model predictions.
#### 5. Comparing Variables ----
# Scaling allows you to compare variables that have different units or
# measurement scales. For example, you can compare variables like age and
# income on the same scale after scaling.
# We use the "preProcess()" function in the caret package
### The Scale Basic Transform on the Boston Housing Dataset ----
# BEFORE
summary(BostonHousing)
hist(BostonHousing[, 1], main = names(BostonHousing)[1])
hist(BostonHousing[, 2], main = names(BostonHousing)[2])
hist(BostonHousing[, 3], main = names(BostonHousing)[3])
hist(BostonHousing[, 5], main = names(BostonHousing)[5])
hist(BostonHousing[, 6], main = names(BostonHousing)[6])
hist(BostonHousing[, 7], main = names(BostonHousing)[7])
hist(BostonHousing[, 8], main = names(BostonHousing)[8])
hist(BostonHousing[, 9], main = names(BostonHousing)[9])
hist(BostonHousing[, 10], main = names(BostonHousing)[10])
hist(BostonHousing[, 11], main = names(BostonHousing)[11])
hist(BostonHousing[, 12], main = names(BostonHousing)[12])
hist(BostonHousing[, 13], main = names(BostonHousing)[13])
hist(BostonHousing[, 14], main = names(BostonHousing)[14])
model_of_the_transform <- preProcess(BostonHousing, method = c("scale"))
print(model_of_the_transform)
boston_housing_scale_transform <- predict(model_of_the_transform,
BostonHousing)
# AFTER
summary(boston_housing_scale_transform)
hist(boston_housing_scale_transform[, 1],
main = names(boston_housing_scale_transform)[1])
hist(boston_housing_scale_transform[, 2],
main = names(boston_housing_scale_transform)[2])
hist(boston_housing_scale_transform[, 3],
main = names(boston_housing_scale_transform)[3])
hist(boston_housing_scale_transform[, 5],
main = names(boston_housing_scale_transform)[5])
hist(boston_housing_scale_transform[, 6],
main = names(boston_housing_scale_transform)[6])
hist(boston_housing_scale_transform[, 7],
main = names(boston_housing_scale_transform)[7])
hist(boston_housing_scale_transform[, 8],
main = names(boston_housing_scale_transform)[8])
hist(boston_housing_scale_transform[, 9],
main = names(boston_housing_scale_transform)[9])
hist(boston_housing_scale_transform[, 10],
main = names(boston_housing_scale_transform)[10])
hist(boston_housing_scale_transform[, 11],
main = names(boston_housing_scale_transform)[11])
hist(boston_housing_scale_transform[, 12],
main = names(boston_housing_scale_transform)[12])
hist(boston_housing_scale_transform[, 13],
main = names(boston_housing_scale_transform)[13])
hist(boston_housing_scale_transform[, 14],
main = names(boston_housing_scale_transform)[14])
### The Scale Basic Transform on the Crop Dataset ----
# BEFORE
summary(crop_dataset)
# The code below converts column number 4 into unlisted and numeric data first
# so that a histogram can be plotted. Further reading:
crop_dataset_yield <- as.numeric(unlist(crop_dataset[, 4]))
hist(crop_dataset_yield, main = names(crop_dataset)[4])
model_of_the_transform <- preProcess(crop_dataset, method = c("scale"))
print(model_of_the_transform)
crop_data_scale_transform <- predict(model_of_the_transform, crop_dataset)
# AFTER
summary(crop_data_scale_transform)
crop_dataset_yield <- as.numeric(unlist(crop_data_scale_transform[, 4]))
hist(crop_dataset_yield, main = names(crop_data_scale_transform)[4])
# Center Data Transform ----
## STEP 4. Apply a Centre Data Transform ----
# The centre data transform calculates the mean of an attribute and subtracts
# it from each value.
### Benefits of Centering ----
#### 1. Removes the Effect of the Mean ----
# Centering makes the data's mean equal to zero. By subtracting the mean from
# each data point, you effectively remove any systematic bias or shift in the
# data. This is particularly useful when you want to focus on variations or
# deviations from the mean.
#### 2. Interpretability ----
# Centering enhances the interpretability of data. When data is centered, the
# coefficients or parameters in statistical models become more interpretable.
# For example, in linear regression, the intercept (constant term) represents
# the predicted value when all predictor variables are at their means, making
# it easier to understand the effect of the predictors.
#### 3. Stabilizes Numerical Computations ----
# In some numerical algorithms, centering data can improve the numerical
# stability of computations. Centering often reduces large numerical values and
# can prevent issues like numerical instability or overflow in certain
# calculations.
#### 4. Facilitates Comparison ----
# When working with multiple variables or features with different units or
# measurement scales, centering helps standardize these variables for
# meaningful comparisons. It makes it easier to assess the relative impact or
# importance of different features in a model.
#### 5. Eases Visual Interpretation ----
# Centering can simplify the interpretation of data visualizations, such as
# scatter plots. By centering the data, you can focus on the shape of the
# distribution around the center (mean) rather than being influenced by the
# location of the data in the plot.
#### 6. Improves Model Convergence ----
# Some optimization algorithms used in statistical modeling and machine
# learning may converge more quickly and stably when data is centered.
# This is particularly relevant when dealing with iterative optimization
# procedures.
#### 7. Handling Interaction Terms ----
# When creating interaction terms in regression models, centering the variables
# involved in the interaction can help in reducing multicollinearity and
# improve the interpretation of interaction effects.
### The Centre Basic Transform on the Boston Housing Dataset ----
# BEFORE
summary(BostonHousing)
boxplot(BostonHousing[, 1], main = names(BostonHousing)[1])
boxplot(BostonHousing[, 2], main = names(BostonHousing)[2])
boxplot(BostonHousing[, 3], main = names(BostonHousing)[3])
boxplot(BostonHousing[, 5], main = names(BostonHousing)[5])
boxplot(BostonHousing[, 6], main = names(BostonHousing)[6])
boxplot(BostonHousing[, 7], main = names(BostonHousing)[7])
boxplot(BostonHousing[, 8], main = names(BostonHousing)[8])
boxplot(BostonHousing[, 9], main = names(BostonHousing)[9])
boxplot(BostonHousing[, 10], main = names(BostonHousing)[10])
boxplot(BostonHousing[, 11], main = names(BostonHousing)[11])
boxplot(BostonHousing[, 12], main = names(BostonHousing)[12])
boxplot(BostonHousing[, 13], main = names(BostonHousing)[13])
boxplot(BostonHousing[, 14], main = names(BostonHousing)[14])
model_of_the_transform <- preProcess(BostonHousing, method = c("center"))
print(model_of_the_transform)
boston_housing_center_transform <- predict(model_of_the_transform, # nolint
BostonHousing)
# AFTER
summary(boston_housing_center_transform)
boxplot(boston_housing_center_transform[, 1],
main = names(boston_housing_center_transform)[1])
boxplot(boston_housing_center_transform[, 2],
main = names(boston_housing_center_transform)[2])
boxplot(boston_housing_center_transform[, 3],
main = names(boston_housing_center_transform)[3])
boxplot(boston_housing_center_transform[, 5],
main = names(boston_housing_center_transform)[5])
boxplot(boston_housing_center_transform[, 6],
main = names(boston_housing_center_transform)[6])
boxplot(boston_housing_center_transform[, 7],
main = names(boston_housing_center_transform)[7])
boxplot(boston_housing_center_transform[, 8],
main = names(boston_housing_center_transform)[8])
boxplot(boston_housing_center_transform[, 9],
main = names(boston_housing_center_transform)[9])
boxplot(boston_housing_center_transform[, 10],
main = names(boston_housing_center_transform)[10])
boxplot(boston_housing_center_transform[, 11],
main = names(boston_housing_center_transform)[11])
boxplot(boston_housing_center_transform[, 12],
main = names(boston_housing_center_transform)[12])
boxplot(boston_housing_center_transform[, 13],
main = names(boston_housing_center_transform)[13])
boxplot(boston_housing_center_transform[, 14],
main = names(boston_housing_center_transform)[14])
### The Centre Basic Transform on the Crop Dataset ----
summary(crop_dataset)
model_of_the_transform <- preProcess(crop_dataset, method = c("center"))
print(model_of_the_transform)
crop_data_center_transform <- predict(model_of_the_transform, crop_dataset)
summary(crop_data_center_transform)
### The Centre Basic Transform on the Iris Dataset ----
summary(iris_dataset)
model_of_the_transform <- preProcess(iris_dataset, method = c("center"))
print(model_of_the_transform)
iris_dataset_center_transform <- predict(model_of_the_transform, iris_dataset)
summary(iris_dataset_center_transform)
### The Centre Basic Transform on the Pima Indians Diabetes Dataset ----
summary(PimaIndiansDiabetes)
model_of_the_transform <- preProcess(PimaIndiansDiabetes, method = c("center"))
print(model_of_the_transform)
pima_indians_diabetes_center_transform <- predict(model_of_the_transform, # nolint
PimaIndiansDiabetes)
summary(pima_indians_diabetes_center_transform)
# Standardize Data Transform ----
## STEP 5. Apply a Standardize Data Transform ----
# The standardize data transform ensures that each numeric attribute has a mean
# value of 0 and a standard deviation of 1. This is done by combining the scale
# data transform and the centre data transform.
### Benefits of Standardizing ----
#### 1. Enhances Model Performance ----
# Many machine learning algorithms, such as support vector machines, k-nearest
# neighbors, and principal component analysis, perform better when the input
# features are on the same scale. Standardizing data can lead to improved model
# performance and more reliable results.
#### 2. Promotes Fair Comparison ----
# Standardizing data allows for a fair and meaningful comparison of the
# importance of different features. When features have different units or
# measurement scales, it can be challenging to compare their contributions to a
# model. Standardizing puts all features on the same scale, making these
# comparisons more straightforward.
#### 3. Facilitates Gradient Descent ----
# In optimization algorithms like gradient descent, the scale of the features
# can affect convergence. Features with large scales can dominate the learning
# process and slow down convergence. Standardization can help mitigate this
# problem by ensuring that all features have similar scales.
#### 4. Simplifies Interpretation ----
# Standardized coefficients in linear models are directly interpretable.
# In linear regression, the coefficients represent the change in the dependent
# variable associated with a one-standard-deviation change in the predictor
# variable. This makes the interpretation of the model more intuitive.
#### 5. Robust to Outliers ----
# Standardization is less affected by outliers than some other scaling methods
# like min-max scaling. Outliers have a limited impact on the mean and standard
# deviation, so standardization can be a robust choice when dealing with data
# containing outliers.
#### 6. Improves Clustering and Dimensionality Reduction ----
# In clustering and dimensionality reduction techniques like k-means clustering
# and principal component analysis (PCA), the scale of the data can influence
# the results. Standardizing data helps these techniques produce more
# meaningful and stable results.
#### 7. Easier Feature Engineering ----
# When creating new features or interaction terms in models, standardizing the
# variables involved can simplify the process and improve model
# interpretability.
# Standardizing data does not change the fundamental relationships in the data;
# it merely transforms the scale. The choice to
# standardize depends on the specific characteristics of the data and the
# requirements of the analysis or model. In some cases, standardization is
# necessary for the model to perform effectively, while in others, it may not be
# required. The decision should be made based on the context and the nature of
# the data.
### The Standardize Basic Transform on the Boston Housing Dataset ----
# BEFORE
summary(BostonHousing)
sapply(BostonHousing[, -4], sd)
model_of_the_transform <- preProcess(BostonHousing,
method = c("scale", "center"))
print(model_of_the_transform)
boston_housing_standardize_transform <- predict(model_of_the_transform, # nolint
BostonHousing)
# AFTER
summary(boston_housing_standardize_transform)
sapply(boston_housing_standardize_transform[, -4], sd)
### The Standardize Basic Transform on the Crop Dataset ----
# BEFORE
summary(crop_dataset)
sapply(crop_dataset[, 4], sd)
model_of_the_transform <- preProcess(crop_dataset,
method = c("scale", "center"))
print(model_of_the_transform)
crop_data_standardize_transform <- predict(model_of_the_transform, crop_dataset) # nolint
# AFTER
summary(crop_data_standardize_transform)
sapply(crop_data_standardize_transform[, 4], sd)
### The Standardize Basic Transform on the Iris Dataset ----
# BEFORE
summary(iris_dataset)
sapply(iris_dataset[, 1:4], sd)
model_of_the_transform <- preProcess(iris_dataset,
method = c("scale", "center"))
print(model_of_the_transform)
iris_dataset_standardize_transform <- predict(model_of_the_transform, # nolint
iris_dataset)
# AFTER
summary(iris_dataset_standardize_transform)
sapply(iris_dataset_standardize_transform[, 1:4], sd)
### The Standardize Basic Transform on the Pima Indians Diabetes Dataset ----
# BEFORE
summary(PimaIndiansDiabetes)
sapply(PimaIndiansDiabetes[, 1:8], sd)
model_of_the_transform <- preProcess(PimaIndiansDiabetes,
method = c("scale", "center"))
print(model_of_the_transform)
pima_indians_diabetes_standardize_transform <- predict(model_of_the_transform, # nolint
PimaIndiansDiabetes)
# AFTER
summary(pima_indians_diabetes_standardize_transform)
sapply(pima_indians_diabetes_standardize_transform[, 1:8], sd)
# Normalize Data Transform ----
## STEP 6. Apply a Normalize Data Transform ----
# Normalizing a dataset implies ensuring the numerical data are
# between [0, 1] (inclusive).
### Benefits of the Normalize Data Transform ----
#### 1. Comparability ----
# Normalization allows for the comparison of variables with different units
# and measurement scales. By transforming all features to the same scale, you
# can evaluate their relative contributions more easily.
#### 2. Improved Model Performance ----
# Some machine learning algorithms, like neural networks, can benefit from
# having input features within a certain range. Normalizing the data ensures
# that the input features are within a consistent range, which can lead to
# improved model performance.
#### 3. Sensitivity to Magnitude ----
# Certain algorithms are sensitive to the magnitude
# of data, and this can lead to issues during training. Normalization reduces
# the sensitivity to the scale of the input features, making the optimization
# process more stable.
#### 4. Facilitates Convergence ----
# In optimization algorithms such as gradient descent,
# having all input features within a similar scale can help algorithms converge
# faster and reach a global minimum more efficiently.
#### 5. Dimension Reduction Techniques ----
# Normalization is often used in dimensionality
# reduction techniques like PCA (Principal Component Analysis). Scaling the data
# ensures that each dimension contributes equally to the computation of
# principal components.
#### 6. Handling Distance-Based Algorithms ----
# Algorithms that rely on distance metrics, such as k-means clustering, are
# sensitive to the scale of features. Normalizing the data helps prevent
# features with larger scales from dominating the distance calculations.
#### 7. Visualization ----
# Normalized data can lead to more meaningful and interpretable visualizations,
# especially when comparing different variables on the same plot.
#### 8. Facilitates Feature Engineering ----
# When creating interaction terms or composite features, normalizing the
# variables involved can simplify the process and enhance the interpretability
# of the model.
#### 9. Prevents Overfitting ----
# In some models, features with larger scales may be more prone to overfitting.
# Normalizing data can help mitigate this issue.
#### 10. Handling Multicollinearity ----
# Normalizing can reduce multicollinearity, a situation where two or more
# features are highly correlated. Reducing multicollinearity can make models
# more interpretable.
# Even though normalization is beneficial in many cases, it may not always be
# necessary, especially when the data is already on a compatible scale for the
# intended analysis.
### The Normalize Transform on the Boston Housing Dataset ----
summary(BostonHousing)
model_of_the_transform <- preProcess(BostonHousing, method = c("range"))
print(model_of_the_transform)
boston_housing_normalize_transform <- predict(model_of_the_transform, # nolint
BostonHousing)
summary(boston_housing_normalize_transform)
### The Normalize Transform on the Crop Dataset ----
summary(crop_dataset)
model_of_the_transform <- preProcess(crop_dataset, method = c("range"))
print(model_of_the_transform)
crop_data_normalize_transform <- predict(model_of_the_transform, crop_dataset)
summary(crop_data_normalize_transform)
### The Normalize Transform on the Iris Dataset ----
summary(iris_dataset)
model_of_the_transform <- preProcess(iris_dataset, method = c("range"))
print(model_of_the_transform)
iris_dataset_normalize_transform <- predict(model_of_the_transform, # nolint
iris_dataset)
summary(iris_dataset_normalize_transform)
### The Normalize Transform on the Pima Indians Diabetes Dataset ----
summary(PimaIndiansDiabetes)
model_of_the_transform <- preProcess(PimaIndiansDiabetes, method = c("range"))
print(model_of_the_transform)
pima_indians_diabetes_normalize_transform <- predict(model_of_the_transform, # nolint
PimaIndiansDiabetes)
summary(pima_indians_diabetes_normalize_transform)
# Box-Cox Power Transform ----
## STEP 7. Apply a Box-Cox Power Transform ----
# The skewness informs you of the asymmetry of the distribution of results.
# Similar to kurtosis, there are several ways of computing the skewness. Using
# “type = 2” (discussed in a previous Lab) can be interpreted as:
# 1. Skewness between -0.4 and 0.4 (inclusive) implies that there is no
# skew in the distribution of results; the distribution of results is
# symmetrical; it is a normal distribution.
# 2. Skewness above 0.4 implies a positive skew; a right-skewed distribution.
# 3. Skewness below -0.4 implies a negative skew; a left-skewed distribution.
# Skewness occurs when an attribute has a Gaussian-like distribution but it is
# shifted. The Box-Cox transform reduces the skewness by shifting the
# distribution of an attribute and making the attribute have a more
# Gaussian-like distribution.
### Box-Cox Power Transform on the Boston Housing Dataset ----
# BEFORE
summary(BostonHousing)
#Calculate the skewness before the Box-Cox transform
sapply(BostonHousing[, -4], skewness, type = 2)
#Plot a histogram to view the skewness before the Box-Cox transform
hist(BostonHousing[, 1], main = names(BostonHousing)[1])
hist(BostonHousing[, 2], main = names(BostonHousing)[2])
hist(BostonHousing[, 3], main = names(BostonHousing)[3])
hist(BostonHousing[, 5], main = names(BostonHousing)[5])
hist(BostonHousing[, 6], main = names(BostonHousing)[6])
hist(BostonHousing[, 7], main = names(BostonHousing)[7])
hist(BostonHousing[, 8], main = names(BostonHousing)[8])
hist(BostonHousing[, 9], main = names(BostonHousing)[9])
hist(BostonHousing[, 10], main = names(BostonHousing)[10])
hist(BostonHousing[, 11], main = names(BostonHousing)[11])
hist(BostonHousing[, 12], main = names(BostonHousing)[12])
hist(BostonHousing[, 13], main = names(BostonHousing)[13])
hist(BostonHousing[, 14], main = names(BostonHousing)[14])
model_of_the_transform <- preProcess(BostonHousing, method = c("BoxCox"))
print(model_of_the_transform)
boston_housing_box_cox_transform <- predict(model_of_the_transform, # nolint
BostonHousing)
# AFTER
summary(boston_housing_box_cox_transform)
# Calculate the skewness after the Box-Cox transform
sapply(boston_housing_box_cox_transform[, -4], skewness, type = 2)
#Plot a histogram to view the skewness after the Box-Cox transform
hist(boston_housing_box_cox_transform[, 1],
main = names(boston_housing_box_cox_transform)[1])
hist(boston_housing_box_cox_transform[, 2],
main = names(boston_housing_box_cox_transform)[2])
hist(boston_housing_box_cox_transform[, 3],
main = names(boston_housing_box_cox_transform)[3])
hist(boston_housing_box_cox_transform[, 5],
main = names(boston_housing_box_cox_transform)[5])
hist(boston_housing_box_cox_transform[, 6],
main = names(boston_housing_box_cox_transform)[6])
hist(boston_housing_box_cox_transform[, 7],
main = names(boston_housing_box_cox_transform)[7])
hist(boston_housing_box_cox_transform[, 8],
main = names(boston_housing_box_cox_transform)[8])
hist(boston_housing_box_cox_transform[, 9],
main = names(boston_housing_box_cox_transform)[9])
hist(boston_housing_box_cox_transform[, 10],
main = names(boston_housing_box_cox_transform)[10])
hist(boston_housing_box_cox_transform[, 11],
main = names(boston_housing_box_cox_transform)[11])
hist(boston_housing_box_cox_transform[, 12],
main = names(boston_housing_box_cox_transform)[12])
hist(boston_housing_box_cox_transform[, 13],
main = names(boston_housing_box_cox_transform)[13])
hist(boston_housing_box_cox_transform[, 14],
main = names(boston_housing_box_cox_transform)[14])
### Box-Cox Power Transform on the Crop Dataset ----
# BEFORE
summary(crop_data_standardize_transform)
# Calculate the skewness before the Box-Cox transform
sapply(crop_data_standardize_transform[, 4], skewness, type = 2)
sapply(crop_data_standardize_transform[, 4], sd)
model_of_the_transform <- preProcess(crop_data_standardize_transform,
method = c("BoxCox"))
print(model_of_the_transform)
crop_data_box_cox_transform <- predict(model_of_the_transform,
crop_data_standardize_transform)
# AFTER
summary(crop_data_box_cox_transform)
sapply(crop_data_box_cox_transform[, 4], skewness, type = 2)
sapply(crop_data_box_cox_transform[, 4], sd)
# Calculate the skewness after the Box-Cox transform
sapply(crop_data_box_cox_transform[, 4], skewness, type = 2)
sapply(crop_data_box_cox_transform[, 4], sd)
# Notice that none of the attributes in the crop dataset qualify to be
# transformed using the Box Cox data transform. Yield has negative values
# after standardization.
### Box-Cox Power Transform on the Iris Dataset ----
# BEFORE
summary(iris_dataset)
# Calculate the skewness before the Box-Cox transform
sapply(iris_dataset[, 1:4], skewness, type = 2)
# Plot a histogram to view the skewness before the Box-Cox transform
par(mfrow = c(1, 4))
for (i in 1:4) {
hist(iris_dataset[, i], main = names(iris_dataset)[i])
}
model_of_the_transform <- preProcess(iris_dataset, method = c("BoxCox"))
print(model_of_the_transform)
iris_dataset_box_cox_transform <- predict(model_of_the_transform,
iris_dataset)
# AFTER
summary(iris_dataset_box_cox_transform)
# Calculate the skewness after the Box-Cox transform
sapply(iris_dataset_box_cox_transform[, 1:4], skewness, type = 2)
# Plot a histogram to view the skewness after the Box-Cox transform
par(mfrow = c(1, 4))
for (i in 1:4) {
hist(iris_dataset_box_cox_transform[, i],
main = names(iris_dataset_box_cox_transform)[i])
}
### Box-Cox Power Transform on the Pima Indians Diabetes Dataset ----
# BEFORE
summary(PimaIndiansDiabetes)
# Calculate the skewness before the Box-Cox transform
sapply(PimaIndiansDiabetes[, 1:8], skewness, type = 2)
# Plot a histogram to view the skewness before the Box-Cox transform
par(mfrow = c(1, 8))
for (i in 1:8) {
hist(PimaIndiansDiabetes[, i], main = names(PimaIndiansDiabetes)[i])
}
model_of_the_transform <- preProcess(PimaIndiansDiabetes, method = c("BoxCox"))
print(model_of_the_transform)
pima_indians_diabetes_box_cox_transform <- predict(model_of_the_transform, # nolint
PimaIndiansDiabetes)
# AFTER
summary(pima_indians_diabetes_box_cox_transform)
# Calculate the skewness after the Box-Cox transform
sapply(pima_indians_diabetes_box_cox_transform[, 1:8], skewness, type = 2)
# Plot a histogram to view the skewness after the Box-Cox transform
par(mfrow = c(1, 8))
for (i in 1:8) {
hist(pima_indians_diabetes_box_cox_transform[, i],
main = names(pima_indians_diabetes_box_cox_transform)[i])
}
# Yeo-Johnson Power Transform ----
## STEP 8. Apply a Yeo-Johnson Power Transform ----
# Similar to the Box-Cox transform, the Yeo-Johnson transform reduces the
# skewness by shifting the distribution of an attribute and making the
# attribute have a more Gaussian-like distribution. The difference is that the
# Yeo-Johnson transform can handle zero and negative values, unlike the Box-Cox
# transform.
### Yeo-Johnson Power Transform on the Boston Housing Dataset ----
# BEFORE
summary(BostonHousing)
# Calculate the skewness before the Yeo-Johnson transform
sapply(BostonHousing[, -4], skewness, type = 2)
# Plot a histogram to view the skewness before the Box-Cox transform
hist(BostonHousing[, 1], main = names(BostonHousing)[1])
hist(BostonHousing[, 2], main = names(BostonHousing)[2])
hist(BostonHousing[, 3], main = names(BostonHousing)[3])
hist(BostonHousing[, 5], main = names(BostonHousing)[5])
hist(BostonHousing[, 6], main = names(BostonHousing)[6])
hist(BostonHousing[, 7], main = names(BostonHousing)[7])
hist(BostonHousing[, 8], main = names(BostonHousing)[8])
hist(BostonHousing[, 9], main = names(BostonHousing)[9])
hist(BostonHousing[, 10], main = names(BostonHousing)[10])
hist(BostonHousing[, 11], main = names(BostonHousing)[11])
hist(BostonHousing[, 12], main = names(BostonHousing)[12])
hist(BostonHousing[, 13], main = names(BostonHousing)[13])
hist(BostonHousing[, 14], main = names(BostonHousing)[14])
model_of_the_transform <- preProcess(BostonHousing, method = c("YeoJohnson"))
print(model_of_the_transform)
boston_housing_yeo_johnson_transform <- predict(model_of_the_transform, # nolint
BostonHousing)
# AFTER
summary(boston_housing_yeo_johnson_transform)
# Calculate the skewness after the Yeo-Johnson transform
sapply(boston_housing_yeo_johnson_transform[, -4], skewness, type = 2)
# Plot a histogram to view the skewness after the Box-Cox transform
hist(boston_housing_yeo_johnson_transform[, 1],
main = names(boston_housing_yeo_johnson_transform)[1])
hist(boston_housing_yeo_johnson_transform[, 2],
main = names(boston_housing_yeo_johnson_transform)[2])
hist(boston_housing_yeo_johnson_transform[, 3],
main = names(boston_housing_yeo_johnson_transform)[3])
hist(boston_housing_yeo_johnson_transform[, 5],
main = names(boston_housing_yeo_johnson_transform)[5])
hist(boston_housing_yeo_johnson_transform[, 6],
main = names(boston_housing_yeo_johnson_transform)[6])
hist(boston_housing_yeo_johnson_transform[, 7],
main = names(boston_housing_yeo_johnson_transform)[7])
hist(boston_housing_yeo_johnson_transform[, 8],
main = names(boston_housing_yeo_johnson_transform)[8])
hist(boston_housing_yeo_johnson_transform[, 9],
main = names(boston_housing_yeo_johnson_transform)[9])
hist(boston_housing_yeo_johnson_transform[, 10],
main = names(boston_housing_yeo_johnson_transform)[10])
hist(boston_housing_yeo_johnson_transform[, 11],
main = names(boston_housing_yeo_johnson_transform)[11])
hist(boston_housing_yeo_johnson_transform[, 12],
main = names(boston_housing_yeo_johnson_transform)[12])
hist(boston_housing_yeo_johnson_transform[, 13],
main = names(boston_housing_yeo_johnson_transform)[13])
hist(boston_housing_yeo_johnson_transform[, 14],
main = names(boston_housing_yeo_johnson_transform)[14])
### Yeo-Johnson Power Transform on the Crop Dataset ----
# BEFORE
summary(crop_data_standardize_transform)
# Calculate the skewness before the Yeo-Johnson transform
sapply(crop_data_standardize_transform[, 4], skewness, type = 2)
sapply(crop_data_standardize_transform[, 4], sd)
model_of_the_transform <- preProcess(crop_data_standardize_transform,
method = c("YeoJohnson"))
print(model_of_the_transform)
crop_data_yeo_johnson_transform <- predict(model_of_the_transform, # nolint
crop_data_standardize_transform)
# AFTER
summary(crop_data_yeo_johnson_transform)
# Calculate the skewness after the Yeo-Johnson transform
sapply(crop_data_yeo_johnson_transform[, 4], skewness, type = 2)
sapply(crop_data_yeo_johnson_transform[, 4], sd)
# Notice that unlike the Box-Cox data transform, the Yeo-Johnson data
# transform considers 1 of the attributes (yield) as qualified to be
# transformed using the Yeo-Johnson transform. This is despite Yield
# having negative values after standardization.
### Yeo-Johnson Power Transform on the Iris Dataset ----
# BEFORE
summary(iris_dataset)
# Calculate the skewness before the Yeo-Johnson transform
sapply(iris_dataset[, 1:4], skewness, type = 2)
# Plot a histogram to view the skewness before the Yeo-Johnson transform
par(mfrow = c(1, 4))
for (i in 1:4) {
hist(iris_dataset[, i], main = names(iris_dataset)[i])
}
model_of_the_transform <- preProcess(iris_dataset, method = c("YeoJohnson"))
print(model_of_the_transform)
iris_dataset_yeo_johnson_transform <- predict(model_of_the_transform, iris_dataset) # nolint
# AFTER
summary(iris_dataset_yeo_johnson_transform)
# Calculate the skewness after the Yeo-Johnson transform
sapply(iris_dataset_yeo_johnson_transform[, 1:4], skewness, type = 2)
# Plot a histogram to view the skewness after the Yeo-Johnson transform
par(mfrow = c(1, 4))
for (i in 1:4) {
hist(iris_dataset_yeo_johnson_transform[, i],
main = names(iris_dataset_yeo_johnson_transform)[i])
}
### Yeo-Johnson Power Transform on the Pima Indians Diabetes Dataset ----
# BEFORE
summary(PimaIndiansDiabetes)
# Calculate the skewness before the Yeo-Johnson transform
sapply(PimaIndiansDiabetes[, 1:8], skewness, type = 2)
# Plot a histogram to view the skewness before the Yeo-Johnson transform
par(mfrow = c(1, 8))
for (i in 1:8) {
hist(PimaIndiansDiabetes[, i], main = names(PimaIndiansDiabetes)[i])
}
model_of_the_transform <- preProcess(PimaIndiansDiabetes,
method = c("YeoJohnson"))
print(model_of_the_transform)
pima_indians_diabetes_yeo_johnson_transform <- predict(model_of_the_transform, # nolint
PimaIndiansDiabetes)
# AFTER
summary(pima_indians_diabetes_yeo_johnson_transform)
# Calculate the skewness after the Yeo-Johnson transform
sapply(pima_indians_diabetes_yeo_johnson_transform[, 1:8], skewness, type = 2)
# Plot a histogram to view the skewness after the Yeo-Johnson transform
par(mfrow = c(1, 8))
for (i in 1:8) {
hist(pima_indians_diabetes_yeo_johnson_transform[, i],
main = names(pima_indians_diabetes_yeo_johnson_transform)[i])
}
# Principal Component Analysis (PCA) Linear Algebra Transform ----
## Dimensionality Reduction versus Feature Selection ----
# PCA and ICA are primarily dimensionality reduction techniques used to
# transform high-dimensional data into a lower-dimensional space while
# retaining as much variance as possible. However, they can indirectly assist
# in feature selection by identifying the most important features or components.
# Feature selection and dimensionality reduction are both techniques used to
# reduce the number of features (variables) in a dataset, but they serve
# different purposes and operate in slightly different ways:
# 1. **Feature Selection**:
# - **Purpose**: The primary goal of feature selection is to choose a subset
# of the most relevant and informative features from the