forked from vikasgupta1812/R_Regression
/
RRegrs_Functions.R
3707 lines (3156 loc) · 191 KB
/
RRegrs_Functions.R
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
# ======================================================================
# RRegrs - R Regressions
# ======================================================================
# Get the best regression models for one dataset using R caret methods
# eNanoMapper.net
# -------------------------------------------------------------------------------------------------------------
# AUTHORS:
# -------------------------------------------------------------------------------------------------------------
# Georgia Tsiliki: ChemEng - NTUA, Greece, g_tsiliki@hotmail.com
# Cristian R. Munteanu: RNASA-IMEDIR, University of A Coruna, Spain, muntisa@gmail.com
# Jose A. Seoane: Stanford Cancer Institute, USA, seoane@stanford.edu
# Carlos Fernandez-Lozano: RNASA-IMEDIR, University of A Coruna, Spain, carlos.fernandez@udc.es
# Haralambos Sarimveis: ChemEng - NTUA, Greece, hsarimv@central.ntua.gr
# Egon Willighagen: BiGCaT - Maastricht University, Netherlands, egon.willighagen@gmail.com
# -------------------------------------------------------------------------------------------------------------
#library(caret)
#======================================================================================================================
# General functions
#======================================================================================================================
r2.adj.t.funct<- function(obs,pred,num.pred){
#obs==y, pred=predicted, num.pred=number of idependent variables (predictors)
#t: traditional formula
y.mean<- mean(obs)
x.in<- sum((obs-pred)^2)/sum((obs-y.mean)^2)
x.in<- 1-x.in #r squared
x.in<- (1-x.in)*((length(obs)-1)/(length(obs)-num.pred-1))
x.in<- 1 - x.in
return(x.in)
}
#----------------------------------------------------------------------------------------------------------------------
r2.adj.funct<- function(obs,pred,num.pred){
#obs==y, pred=predicted, num.pred=number of idependent variables (predictors)
x.in<- cor(obs,pred)^2
x.in<- (1-x.in)*((length(obs)-1)/(length(obs)-num.pred-1))
x.in<- 1 - x.in
return(x.in)
}
#----------------------------------------------------------------------------------------------------------------------
rmse.funct<- function(obs,pred){
#obs==y, pred=predicted
return(sqrt(mean((pred - obs)^2)))
}
#----------------------------------------------------------------------------------------------------------------------
r2.funct<- function(obs,pred){
#obs==y, pred=predicted
x.in<- cor(obs,pred)^2
return(x.in)
}
#----------------------------------------------------------------------------------------------------------------------
r2.t.funct<- function(obs,pred){
#obs==y, pred=predicted
y.mean<- mean(obs)
x.in<- sum((obs-pred)^2)/sum((obs-y.mean)^2)
x.in<- 1-x.in #r squared
return(x.in)
}
#----------------------------------------------------------------------------------------------------------------------
AppendList2CSv <- function(l,csvFile) {
#--------------------------------------------------------------------
# Write a LIST to CSV file
#--------------------------------------------------------------------
out_file <- file(csvFile, open="a") #creates a file in append mode
for (i in seq_along(l)){
# writes the name of the list elements ("A", "B", etc.)
write.table(names(l)[i],file=out_file,sep=",",dec=".",quote=F,col.names=F,row.names=F)
write.table(l[[i]], file=out_file,sep=",",dec=".",quote=F,col.names=NA,row.names=T) #writes the data.frames
}
close(out_file) #close connection to file.csv
}
#----------------------------------------------------------------------------------------------------------------------
AppendList2txt <- function(l,csvFile) {
#--------------------------------------------------------------------
# Write a LIST to TXT file
#--------------------------------------------------------------------
out_file <- file(csvFile, open="a") #creates a file in append mode
for (i in seq_along(l)){
#writes the name of the list elements ("A", "B", etc)
write.table(names(l)[i],file=out_file,sep=" ",dec=".",quote=F,col.names=F, row.names=F)
write.table(l[[i]], file=out_file,sep=" ",dec=".",quote=F,col.names=NA,row.names=T) #writes the data.frames
}
close(out_file) #close connection to file.csv
}
# ************************************
# RRegrs Specific functions
# ************************************
RemNear0VarCols <- function(ds,fDet=FALSE,outFile="ds3.No0Var.csv") {
#================================================
# Removal of near zero variance columns (Step 3)
#================================================
# inputs:
# - ds = dataset frame
# - fDet = flag for detais (TRUE/FALSE)
# - outFileName = new file name (it could include the path)
# output = ds.Rem0NearVar (ds without columns with near zero variance)
# if datails = TRUE, output the new ds as a file
# ------------------------------------------
# default parameters are no details, with a CSV file name
#library(caret)
ds.Rem0NearVar <- ds # default output without any modification
ds.var <- nearZeroVar(ds) # get the near zero columns
if (!length(ds.var) == FALSE) { # remove the columns only if nearZeroVar identified; if no columns to remove, ds will be the same
ds.Rem0NearVar <- ds[,-(ds.var)] # get only the columns without this problem
if (fDet == TRUE) { # write as details the corrected ds file
write.csv(ds.Rem0NearVar, outFile,row.names=F, quote=F)
}
}
return(as.data.frame(ds.Rem0NearVar)) # return the new data frame without near zero variance
}
#----------------------------------------------------------------------------------------------------------------------
ScalingDS <- function(ds,s=1,c=1,fDet=FALSE,outFileName="ds4.scaled.csv") {
#===========================
# Scaling dataset (Step 4)
#===========================
# s = { 1,2,3 } - type of scaling: 1 = normalization, 2 = standardization, 3 = other
# c = the number of column into the dataset to start scaling
# - if c = 1: included the dependent variable
# - if c = 2: only the features will be scaled
# fDet = if details need to be printed (TRUE/FALSE)
# outFileName = new file name (it could include the path)
# Default scaling = NORMALIZATION !
# DEFAULT scaled dataset = original
# if other s diffent of 1,2,3 is used => no scaling!
DataSet.scaled <- ds
# if NORMALIZATION
if (s==1) {
# Scale all the features (from column c; column 1 is the predictor output)
DataSet.scaled <- ((ds-min(ds))/(max(ds)-min(ds))) # normalize all the columns
}
# if STADARDIZATION
if (s==2) {
# Scale all the features (from column c; column 1 is the predictor output)
DataSet.scaled <- scale(ds[c:ncol(ds)],center=TRUE,scale=TRUE)
}
# if other scaling
if (s==3) {
# Scale all the features (from feature 2 bacause feature 1 is the predictor output)
# TO ADD THE CODE !
}
# if DETAILS
if (fDet ==TRUE) {
# write the result into a separated file
write.csv(DataSet.scaled, outFileName,row.names=F, quote=F)
}
return (as.data.frame(DataSet.scaled)) # return the scaled data frame
}
#----------------------------------------------------------------------------------------------------------------------
RemCorrs <- function(ds,fDet,cutoff,outFile) {
# ========================================
# Remove the correlated columns (Step 5)
# ========================================
# ds = dataset frame
# fDet = flag fro details (TRUE/FALSE)
# cutoff = correlation cut off (ex: 0.9)
# outFileName = new file name (it could include the path)
# Generates 5 file results:
# - returns a dataset without the correlated columns (1 file)
# - generate initial correlation matrix
# and the one after removing the correlated features (2 files)
# - plots for the before and after correlation removal (2 files)
# ------------------------------------------------------------------------
# another version of this function should be implemented using
# pairwise test between i and j descriptors- if(r2>=0.9){remove the j descriptor}
# using findCorelations() from caret
#library(corrplot) #corrplot: the library to compute correlation matrix.
#library(caret)
DataSet <- ds # input dataset
DataSetFiltered.scale <- ds # default results without any modification
# calculate the correlation matrix for the entire file!
# !!! NEED TO BE CORRECTED to avoid dependent variable (first column) but to report it!
corrMat <- cor(DataSet) # get corralation matrix
if (fDet==TRUE) {
CorrMatFile <- paste(outFile,".corrMAT.csv",sep='')
# write correlation matrix as output file
write.csv(corrMat, CorrMatFile, row.names=F, quote=F)
# Plot the matrix, clustering features by correlation index
# corrplot(corrMat, order = "hclust")
# plot the correlatio plot before correlation removal
CorrPlotFile <- paste(outFile,".corrs.png",sep='')
png(height=1200, width=1200, pointsize=25, filename=CorrPlotFile)
col1 <-rainbow(100, s = 1, v = 1, start = 0, end = 0.9, alpha = 1)
corrplot(corrMat,tl.cex=3,title="Initial feature correlation matrix",
method="circle",is.corr=FALSE,#type="full",
cl.lim=c(-1,1),cl.cex=2,addgrid.col="red",
addshade="positive",col=col1,
addCoef.col = rgb(0,0,0, alpha = 0.6), mar=c(0,0,1,0), diag= FALSE)
dev.off()
}
highlyCor <- findCorrelation(corrMat, cutoff) # find corralated columns
# if no correlation found, return the original dataset
if (length(highlyCor) == 0){
return (ds)
}
# Apply correlation filter with the cutoff only if exists!
# by removing all the variable correlated with more than cutoff
DataSetFiltered.scale <- DataSet[,-highlyCor]
if (fDet==TRUE) {
corrMat <- cor(DataSetFiltered.scale)
# plot again the rest of correlations after removing the correlated columns
#corrplot(corrMat, order = "hclust")
# plot the correlation plot AFTER correlation removal
#CorrPlotFile2 = paste(outFile,".afterRemCorr.png",sep='')
#png(height=1200, width=1200, pointsize=25, file=CorrPlotFile2)
#col1 <-rainbow(100, s = 1, v = 1, start = 0, end = 0.9, alpha = 1)
#corrplot(corrMat,tl.cex=3,title="Correlation matrix after removing correlated features",
# method="circle",is.corr=FALSE,type="full",
# cl.lim=c(-1,1),cl.cex=2,addgrid.col="red",
# addshade="positive",col=col1,
# addCoef.col = rgb(0,0,0, alpha = 0.6), mar=c(0,0,1,0), diag= FALSE)
#dev.off()
# correlation matrix for the rest of the columns after removal
#CorrMatFile2 <- paste(outFile,".corrMAT4Selected.csv",sep='')
# write correlation matrix as output file
#write.csv(corrMat, CorrMatFile2, row.names=F, quote=F)
# write the new dataset without the correlated features
write.csv(DataSetFiltered.scale, outFile, row.names=F, quote=F)
}
return(as.data.frame(DataSetFiltered.scale))
}
#----------------------------------------------------------------------------------------------------------------------
DsSplit <- function(ds,trainFrac=3/4,fDet=FALSE,PathDataSet="",iSeed) {
# ===============================================
# Dataset spliting in Training and Test (Step 6)
# ===============================================
# Inputs
# - ds = frame dataset object
# - fDet = flag for detais (TRUE/FALSE)
# - PathDataSet = pathway for results
# Output = training and test datasets (to be used for regressions in other functions)
# if datails = TRUE, output files will be created
my.datf<- ds
# create TRAIN and TEST sets to build a model
set.seed(iSeed)
inTrain <- createDataPartition(1:dim(my.datf)[1],p = trainFrac,list = FALSE,groups=2)
# groups==2 forces to NOT partition
# based on quantiles of numeric values
my.datf.train<- my.datf[inTrain,] # TRAIN dataset frame
my.datf.test <- my.datf[-inTrain,] # TEST dataset frame
if (fDet == TRUE) {
# write the TRAIN and TEST set files
# the index of each row will in the dataset will not be saved (row.names=F)
outTrain <- file.path(PathDataSet,paste("ds.Train.split",iSeed,".csv")) # the same folder as the input
write.csv(my.datf.train,outTrain,row.names=FALSE)
outTest <- file.path(PathDataSet,paste("ds.Test.split",iSeed,".csv")) # the same folder as the input
write.csv(my.datf.test,outTest,row.names=FALSE)
}
MyList<- list("train"=my.datf.train, "test"=my.datf.test)
return(MyList) # return a list with training and test datasets
}
# *************************************
# REGRESSION METHODS
# *************************************
LMreg <- function(my.datf.train,my.datf.test,sCV,iSplit=1,fDet=F,outFile="") {
#==================
# 8.1. Basic LM
#==================
net.c = my.datf.train[,1] # make available the names of variables from training dataset
RegrMethod <- "lm" # type of regression
# Define the CV conditions
ctrl<- trainControl(method=sCV, number=10,repeats=10,
summaryFunction=defaultSummary)
# Train the model using only training set
set.seed(iSplit)
lm.fit<- train(net.c~.,data=my.datf.train,
method='lm', tuneLength = 10,trControl=ctrl,
metric='RMSE')
#------------------------------
# Training RESULTS
#------------------------------
RMSE.tr <- lm.fit$results[,2]
R2.tr <- lm.fit$results[,3]
if (sCV == "repeatedcv"){ # if 10-fold CV
RMSEsd.tr <- lm.fit$results[,4]
R2sd.tr <- lm.fit$results[,5]
}
if (sCV == "LOOCV"){ # if LOOCV
RMSEsd.tr <- 0 # formulas will be added later!
R2sd.tr <- 0 # formulas will be added later!
}
#------------------------------------------------
# RMSE & R^2, for train/test respectively
#------------------------------------------------
lm.train.res <- getTrainPerf(lm.fit)
lm.test.res <- postResample(predict(lm.fit,my.datf.test),my.datf.test[,1])
#------------------------------------------------
# Adj R2, Pearson correlation
#------------------------------------------------
pred.tr <- predict(lm.fit,my.datf.train) # predicted Y for training
pred.ts <- predict(lm.fit,my.datf.test) # predicted Y for test
noFeats.fit <- length(predictors(lm.fit)) # no. of features from the fitted model
Feats.fit <- paste(predictors(lm.fit),collapse="+") # string with the features included in the fitted model
ds.full <- rbind(my.datf.train,my.datf.test)
pred.both <- predict(lm.fit,ds.full) # predicted Y
adjR2.tr <- r2.adj.funct(my.datf.train[,1],pred.tr,noFeats.fit)
adjR2.ts <- r2.adj.funct(my.datf.test[,1],pred.ts,noFeats.fit)
corP.ts <- cor(my.datf.test[,1],pred.ts)
adjR2.both <- r2.adj.funct(ds.full[,1],pred.both,noFeats.fit)
RMSE.both <- rmse.funct(ds.full[,1],pred.both)
r2.both <- r2.funct(ds.full[,1],pred.both)
# Generate the output list with statistics for each cross-validation type
# -------------------------------------------------------------------------
my.stats <- list("RegrMeth" = RegrMethod,
"Split No" = as.numeric(iSplit), # from function param
"CVtype" = sCV, # from function param
"NoModelFeats" = as.numeric(noFeats.fit),
"ModelFeats" = Feats.fit,
"adjR2.tr" = as.numeric(adjR2.tr),
"RMSE.tr" = as.numeric(RMSE.tr),
"R2.tr" = as.numeric(R2.tr),
"RMSEsd.tr" = as.numeric(RMSEsd.tr),
"R2sd.tr" = as.numeric(R2sd.tr),
"adjR2.ts"= as.numeric(adjR2.ts),
"RMSE.ts" = as.numeric((lm.test.res["RMSE"][[1]])),
"R2.ts" = as.numeric((lm.test.res["Rsquared"][[1]])),
"corP.ts" = as.numeric(corP.ts),
"adjR2.both" = as.numeric(adjR2.both),
"RMSE.both" = as.numeric(RMSE.both),
"R2.both" = as.numeric(r2.both))
#---------------------------------------------------------------------
# Write to file DETAILS for GLM for each cross-validation method
#---------------------------------------------------------------------
if (fDet==T) { # if flag for details if T, print details about any resut
write("RRegr package | eNanoMapper", file=outFile, append=T)
write.table(paste("Regression method: ", RegrMethod), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("Split no.: ", iSplit), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("CV type: ", sCV), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Training Set Summary: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(summary(my.datf.train), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Test Set Summary: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(summary(my.datf.test), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Fitting Summary: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(data.frame(summary(lm.fit)$coefficients), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Predictors: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(predictors(lm.fit), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Trainig Results: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(predictors(lm.train.res),file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Test Results: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(predictors(lm.test.res), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Full Statistics: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(my.stats, file=outFile,append=T,sep=",",col.names=T,quote=F)
# Variable Importance (max top 20)
FeatImp <- varImp(lm.fit, scale = F)
components = length(FeatImp) # default plot all feature importance
if (length(FeatImp)>20){ # if the number of features is greater than 20, use only 20
components = 20
}
# Append feature importance to output details
AppendList2CSv(FeatImp,outFile)
fitModel <- lm.fit$finalModel
# =============================================================================
# Assessment of Applicability Domain (plot leverage)
# =============================================================================
# Residuals
resids <- residuals(fitModel) # residuals
write.table("Residuals of the fitted model: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(data.frame(resids), file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F) # write residuals
# Leverage / Hat values
hat.fit <- hatvalues(fitModel) # hat values
hat.fit.df <- as.data.frame(hat.fit) # hat data frame
hat.mean <- mean(hat.fit) # mean hat values
hat.fit.df$warn <- ifelse(hat.fit.df[, 'hat.fit']>3*hat.mean, 'x3',ifelse(hat.fit.df[, 'hat.fit']>2*hat.mean, 'x2', '-' ))
write.table("Leverage output: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("Mean of hat values: ", hat.mean), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Leverage / Hat values with warnings (X3 & X2 = values 3 & 2 times than hat mean): ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(hat.fit.df, file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F) # write hat values and the levels X3, X2 (of hat mean)
#THRESHOLD values: 3m/n, where m is the number of parameters, and n number of observations
thresh.lever<- (3*(dim(my.datf.train)[2]-1))/dim(my.datf.train)[1] # leverage thresh
hat.problems<- data.frame(hat.fit[hat.fit>thresh.lever]) # points with high leverage
write.table(paste("Leverage Threshold: ", thresh.lever), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Points with leverage > threshold: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(hat.problems, file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F)
# Cook's distance
cook.dists<- cooks.distance(fitModel)
cutoff.Cook <- 4/((nrow(my.datf.train)-length(fitModel$coefficients)-2)) # Cook's distance cutoff
write.table("Cook's distances output: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("Cook's distance cutoff: ", cutoff.Cook), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Cook's distances: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(data.frame(cook.dists), file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F) # write residuals
# Influence
infl <- influence(fitModel)#produces several statistics of the kind
write.table("Point influence output: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Influences: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(data.frame(infl), file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F) # write residuals
# PDF with 12 plots
# --------------------------------------------------------------
pdf(file=paste(outFile,".",sCV,".","split",iSplit,".pdf",sep=""))
# par(mfrow = c(3, 4)) # all plots into one page!
plot(my.datf.train[,1],pred.tr,xlab="Yobs", ylab="Ypred", type="b", main="Train Yobs-Ypred") # plot 1
plot(my.datf.test[,1], pred.ts,xlab="Yobs", ylab="Ypred", type="b", main="Test Yobs-Ypred") # plot 2
if(length(is.na(c(FeatImp$importance$Overall)))<=(length(c(FeatImp$importance$Overall))-3)){
dotchart(as.matrix(FeatImp$importance),main="Feature Importance")} # plot 3
# Fitted vs Residuals - plot 4
plot(fitted(fitModel),residuals(fitModel),
main="Fitted vs. Residuals for Fitted Model",
xlab="Fitted", ylab="Residuals")
abline(h = 0, lty = 2)
# Leverage plots - plot 5
plot(hat.fit, type = "h",
main="Leverage for Fitted Model",
xlab="Index", ylab="Hat")
abline(h = thresh.lever, lty = 2, col="red") # leverage thresh
# Cook's distance - plot 6
if(length(is.na(cook.dists))<=(length(cook.dists)-3)){
plot(cook.dists,
main="Cook's Distance for Fitted Model",
xlab="Index", ylab="Cook Distance")
for (p in 1:6) {
plot(fitModel, which=p, cook.levels=cutoff.Cook) # 6 standard fitting plots
}
}
# plot(FeatImp, top = components,main="Feature Importance") # ERROR !
dev.off()
# --------------------------------------------------------------
}
return(list(stat.values=my.stats, model=lm.fit)) # return a list with statistics and the full model
}
#----------------------------------------------------------------------------------------------------------------------
GLMreg <- function(my.datf.train,my.datf.test,sCV,iSplit=1,fDet=F,outFile="") {
#======================================================
# 8.2- GLM stepwise regression - based on AIC (caret)
#======================================================
# Inputs:
# - my.datf.train,my.datf.test = training and test dataset frames
# - sCV = type of cross-validation such as repeatedcv, LOOCV, etc.
# - iSplit = index of splitalse
# - fDet = flag for detais (True/F)
# - outFile = output file for GLM details
# Output:
# - list of statistics equal with the header introduced in the main script and the full model
# (tr = train, ts = test, both = tr+ts = full dataset)
# -----------------------------------------------------------------------------------------------
#library(caret)
#attach(my.datf.train) # make available the names of variables from training dataset
net.c = my.datf.train[,1] # dependent variable is the first column in Training set
RegrMethod <- "glmStepAIC" # type of regression
# Define the CV conditions
ctrl<- trainControl(method=sCV, number=10,repeats=10,
summaryFunction=defaultSummary)
# Train the model using only training set
set.seed(iSplit)
glm.fit<- train(net.c~.,data=my.datf.train,
method='glmStepAIC', tuneLength=10, trControl=ctrl,
metric='RMSE')
#------------------------------
# Training RESULTS
#------------------------------
RMSE.tr <- glm.fit$results[,2]
R2.tr <- glm.fit$results[,3]
if (sCV == "repeatedcv"){ # if 10-fold CV
RMSEsd.tr <- glm.fit$results[,4]
R2sd.tr <- glm.fit$results[,5]
}
if (sCV == "LOOCV"){ # if LOOCV
RMSEsd.tr <- 0 # formulas will be added later!
R2sd.tr <- 0 # formulas will be added later!
}
#------------------------------------------------
# RMSE & R^2, for train/test respectively
#------------------------------------------------
lm.train.res <- getTrainPerf(glm.fit)
lm.test.res <- postResample(predict(glm.fit,my.datf.test),my.datf.test[,1])
#------------------------------------------------
# Adj R2, Pearson correlation
#------------------------------------------------
pred.tr <- predict(glm.fit,my.datf.train) # predicted Y
pred.ts <- predict(glm.fit,my.datf.test) # predicted Y
noFeats.fit <- length(predictors(glm.fit)) # no. of features from the fitted model
Feats.fit <- paste(predictors(glm.fit),collapse="+") # string with the features included in the fitted model
ds.full <- rbind(my.datf.train,my.datf.test)
pred.both <- predict(glm.fit,ds.full) # predicted Y
adjR2.tr <- r2.adj.funct(my.datf.train[,1],pred.tr,noFeats.fit)
adjR2.ts <- r2.adj.funct(my.datf.test[,1],pred.ts,noFeats.fit)
corP.ts <- cor(my.datf.test[,1],pred.ts)
adjR2.both <- r2.adj.funct(ds.full[,1],pred.both,noFeats.fit)
RMSE.both <- rmse.funct(ds.full[,1],pred.both)
r2.both <- r2.funct(ds.full[,1],pred.both)
# Generate the output list with statistics for each cross-validation type
# -------------------------------------------------------------------------
my.stats <- list("RegrMeth" = RegrMethod,
"Split No" = as.numeric(iSplit), # from function param
"CVtype" = sCV, # from function param
"NoModelFeats" = as.numeric(noFeats.fit),
"ModelFeats" = Feats.fit,
"adjR2.tr" = as.numeric(adjR2.tr),
"RMSE.tr" = as.numeric(RMSE.tr),
"R2.tr" = as.numeric(R2.tr),
"RMSEsd.tr" = as.numeric(RMSEsd.tr),
"R2sd.tr" = as.numeric(R2sd.tr),
"adjR2.ts"= as.numeric(adjR2.ts),
"RMSE.ts" = as.numeric((lm.test.res["RMSE"][[1]])),
"R2.ts" = as.numeric((lm.test.res["Rsquared"][[1]])),
"corP.ts" = as.numeric(corP.ts),
"adjR2.both" = as.numeric(adjR2.both),
"RMSE.both" = as.numeric(RMSE.both),
"R2.both" = as.numeric(r2.both))
#---------------------------------------------------------------------
# Write to file DETAILS for GLM for each cross-validation method
#---------------------------------------------------------------------
if (fDet==T) { # if flag for details if T, print details about any resut
write("RRegr package | eNanoMapper", file=outFile,append=T)
write.table(paste("Regression method: ", RegrMethod), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("Split no.: ", iSplit), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("CV type: ", sCV), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Training Set Summary: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(summary(my.datf.train), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Test Set Summary: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(summary(my.datf.test), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Fitting Summary: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(data.frame(summary(glm.fit)$coefficients), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Predictors: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(predictors(glm.fit), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Trainig Results: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(predictors(lm.train.res), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Test Results: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(predictors(lm.test.res), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Full Statistics: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(my.stats, file=outFile,append=T,sep=",",col.names=T,quote=F)
# Variable Importance (max top 20)
FeatImp <- varImp(glm.fit, scale = F)
components = length(FeatImp) # default plot all feature importance
if (length(FeatImp)>20){ # if the number of features is greater than 20, use only 20
components = 20
}
# Append feature importance to output details
AppendList2CSv(FeatImp,outFile)
fitModel <- glm.fit$finalModel
# =============================================================================
# Assessment of Applicability Domain (plot leverage)
# =============================================================================
# Residuals
resids <- residuals(fitModel) # residuals
write.table("Residuals of the fitted model: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(data.frame(resids), file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F) # write residuals
# Leverage / Hat values
hat.fit <- hatvalues(fitModel) # hat values
hat.fit.df <- as.data.frame(hat.fit) # hat data frame
hat.mean <- mean(hat.fit) # mean hat values
hat.fit.df$warn <- ifelse(hat.fit.df[, 'hat.fit']>3*hat.mean, 'x3',ifelse(hat.fit.df[, 'hat.fit']>2*hat.mean, 'x2', '-' ))
write.table("Leverage output: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("Mean of hat values: ", hat.mean), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Leverage / Hat values with warnings (X3 & X2 = values 3 & 2 times than hat mean): ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(hat.fit.df, file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F) # write hat values and the levels X3, X2 (of hat mean)
#THRESHOLD values: 3m/n, where m is the number of parameters, and n number of observations
thresh.lever<- (3*(dim(my.datf.train)[2]-1))/dim(my.datf.train)[1] # leverage thresh
hat.problems<- data.frame(hat.fit[hat.fit>thresh.lever]) # points with high leverage
write.table(paste("Leverage Threshold: ", thresh.lever), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Points with leverage > threshold: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(hat.problems, file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F)
# Cook's distance
cook.dists<- cooks.distance(fitModel)
cutoff.Cook <- 4/((nrow(my.datf.train)-length(fitModel$coefficients)-2)) # Cook's distance cutoff
write.table("Cook's distances output: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("Cook's distance cutoff: ", cutoff.Cook), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Cook's distances: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(data.frame(cook.dists), file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F) # write residuals
# Influence
infl <- influence(fitModel)#produces several statistics of the kind
write.table("Point influence output: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Influences: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(data.frame(infl), file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F) # write residuals
# PDF with 12 plots
# --------------------------------------------------------------
pdf(file=paste(outFile,".",sCV,".","split",iSplit,".pdf",sep=""))
# par(mfrow = c(3, 4)) # all plots into one page!
plot(my.datf.train[,1],pred.tr,xlab="Yobs", ylab="Ypred", type="b", main="Train Yobs-Ypred") # plot 1
plot(my.datf.test[,1], pred.ts,xlab="Yobs", ylab="Ypred", type="b", main="Test Yobs-Ypred") # plot 2
if(length(is.na(c(FeatImp$importance$Overall)))<=(length(c(FeatImp$importance$Overall))-3)){
dotchart(as.matrix(FeatImp$importance),main="Feature Importance")} # plot 3
# Fitted vs Residuals - plot 4
plot(fitted(fitModel),residuals(fitModel),
main="Fitted vs. Residuals for Fitted Model",
xlab="Fitted", ylab="Residuals")
abline(h = 0, lty = 2)
# Leverage plots - plot 5
plot(hat.fit, type = "h",
main="Leverage for Fitted Model",
xlab="Index", ylab="Hat")
abline(h = thresh.lever, lty = 2, col="red") # leverage thresh
# Cook's distance - plot 6
if(length(is.na(cook.dists))<=(length(cook.dists)-3)){
plot(cook.dists,
main="Cook's Distance for Fitted Model",
xlab="Index", ylab="Cook Distance")
for (p in 1:6) {
plot(fitModel, which=p, cook.levels=cutoff.Cook) # 6 standard fitting plots
}
}
# plot(FeatImp, top = components,main="Feature Importance") # ERROR !
dev.off()
# --------------------------------------------------------------
}
return(list(stat.values= my.stats, model=glm.fit)) # return a list with statistics and the full model
}
#----------------------------------------------------------------------------------------------------------------------
PLSreg <- function(my.datf.train,my.datf.test,sCV,iSplit=1,fDet=F,outFile="") {
#================================
# 8.3. PLS regression (caret)
#================================
#library(caret)
net.c = my.datf.train[,1] # dependent variable is the first column in Training set
RegrMethod <- "pls" # type of regression
# Define the CV conditions
ctrl<- trainControl(method = sCV, number = 10,repeats = 10,
summaryFunction = defaultSummary)
# Train the model using only training set
set.seed(iSplit)
floor.param<- floor((dim(my.datf.train)[2]-1)/5)
if(floor.param<1){floor.param <- 1}
pls.fit<- train(net.c~.,data=my.datf.train,
method = 'pls', tuneLength = 10, trControl = ctrl,
metric = 'RMSE',
tuneGrid=expand.grid(.ncomp=c(1:floor.param)))
#------------------------------
# Training RESULTS
#------------------------------
RMSE.tr <- pls.fit$results[,2]
R2.tr <- pls.fit$results[,3]
if (sCV == "repeatedcv"){ # if 10-fold CV
RMSEsd.tr <- pls.fit$results[,4]
R2sd.tr <- pls.fit$results[,5]
}
if (sCV == "LOOCV"){ # if LOOCV
RMSEsd.tr <- 0 # formulas will be added later!
R2sd.tr <- 0 # formulas will be added later!
}
#------------------------------------------------
# RMSE & R^2, for train/test respectively
#------------------------------------------------
lm.train.res <- getTrainPerf(pls.fit)
lm.test.res <- postResample(predict(pls.fit,my.datf.test),my.datf.test[,1])
#------------------------------------------------
# Adj R2, Pearson correlation
#------------------------------------------------
pred.tr <- predict(pls.fit,my.datf.train) # predicted Y
pred.ts <- predict(pls.fit,my.datf.test) # predicted Y
noFeats.fit <- length(predictors(pls.fit)) # no. of features from the fitted model
Feats.fit <- paste(predictors(pls.fit),collapse="+") # string with the features included in the fitted model
ds.full <- rbind(my.datf.train,my.datf.test)
pred.both <- predict(pls.fit,ds.full) # predicted Y
adjR2.tr <- r2.adj.funct(my.datf.train[,1],pred.tr,noFeats.fit)
adjR2.ts <- r2.adj.funct(my.datf.test[,1],pred.ts,noFeats.fit)
corP.ts <- cor(my.datf.test[,1],pred.ts)
adjR2.both <- r2.adj.funct(ds.full[,1],pred.both,noFeats.fit)
RMSE.both <- rmse.funct(ds.full[,1],pred.both)
r2.both <- r2.funct(ds.full[,1],pred.both)
# Generate the output list with statistics for each cross-validation type
# --------------------------------------------------------------------
my.stats <- list("RegrMeth" = RegrMethod,
"Split No" = as.numeric(iSplit), # from function param
"CVtype" = sCV, # from function param
"NoModelFeats" = as.numeric(noFeats.fit),
"ModelFeats" = Feats.fit,
"adjR2.tr" = as.numeric(adjR2.tr),
"RMSE.tr" = as.numeric(min(RMSE.tr)), # these 4 lines correspond to the min of RMSE.tr !!!
"R2.tr" = as.numeric(R2.tr[which.min(RMSE.tr)]),
"RMSEsd.tr" = as.numeric(RMSEsd.tr[which.min(RMSE.tr)]),
"R2sd.tr" = as.numeric(R2sd.tr[which.min(RMSE.tr)]),
"adjR2.ts"= as.numeric(adjR2.ts),
"RMSE.ts" = as.numeric((lm.test.res["RMSE"][[1]])),
"R2.ts" = as.numeric((lm.test.res["Rsquared"][[1]])),
"corP.ts" = as.numeric(corP.ts),
"adjR2.both" = as.numeric(adjR2.both),
"RMSE.both" = as.numeric(RMSE.both),
"R2.both" = as.numeric(r2.both))
#---------------------------------------------------------------------
# Write to file DETAILS for GLM for each cross-validation method
#---------------------------------------------------------------------
if (fDet==T) { # if flag for details if true, print details about any resut
write("RRegr package | eNanoMapper", file=outFile,append=T)
write.table(paste("Regression method: ", RegrMethod), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("Split no.: ", iSplit), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("CV type: ", sCV), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Training Set Summary: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(summary(my.datf.train), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Test Set Summary: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(summary(my.datf.test), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Predictors: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(predictors(pls.fit), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Trainig Results: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(predictors(lm.train.res), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Test Results: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(predictors(lm.test.res), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Full Statistics: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(my.stats, file=outFile,append=T,sep=",",col.names=T,quote=F)
# Variable Importance (max top 20)
FeatImp <- varImp(pls.fit, scale = F)
components = length(FeatImp) # default plot all feature importance
if (length(FeatImp)>20){ # if the number of features is greater than 20, use only 20
components = 20
}
# Append feature importance to output details
AppendList2CSv(FeatImp,outFile)
fitModel <- pls.fit$finalModel
# =============================================================================
# Assessment of Applicability Domain (plot leverage)
# =============================================================================
# Residuals
resids <- residuals(fitModel) # residuals
write.table("Residuals of the fitted model: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(data.frame(resids), file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F) # write residuals
# ADDED !
predVals.pls.ad <- pred.ts
Traind.pls= as.matrix(my.datf.train)
Testd.pls = as.matrix(my.datf.test)
mat.Traind.pls<- t(Traind.pls) %*%(Traind.pls)
det.Traind.pls<- det(mat.Traind.pls)
if(det.Traind.pls!=0){
Hat.train = diag(Traind.pls %*% solve(t(Traind.pls) %*%(Traind.pls), tol=1e-40) %*% t(Traind.pls))
Hat.test = diag(Testd.pls %*% solve(t(Traind.pls) %*%(Traind.pls), tol=1e-40) %*% t(Testd.pls))
# Leverage / Hat values
hat.fit <- Hat.test # hat values
hat.fit.df <- as.data.frame(hat.fit) # hat data frame
hat.mean <- mean(hat.fit) # mean hat values
hat.fit.df$warn <- ifelse(hat.fit.df[, 'hat.fit']>3*hat.mean, 'x3',ifelse(hat.fit.df[, 'hat.fit']>2*hat.mean, 'x2', '-' ))
write.table("Leverage output: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("Mean of hat values: ", hat.mean), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Leverage / Hat values with warnings (X3 & X2 = values 3 & 2 times than hat mean): ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(hat.fit.df, file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F) # write hat values and the levels X3, X2 (of hat mean)
#THRESHOLD values: 3m/n, where m is the number of parameters, and n number of observations
thresh.lever<- (3*(dim(my.datf.train)[2]-1))/dim(my.datf.train)[1] # leverage thresh
hat.problems<- data.frame(hat.fit[hat.fit>thresh.lever]) # points with high leverage
write.table(paste("Leverage Threshold: ", thresh.lever), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Points with leverage > threshold: ",file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(hat.problems, file=outFile,append=T,sep=",",col.names=T,row.names=T, quote=F)
# Cook's distance ?
}
# Influence ?
# PDF plots
# --------------------------------------------------------------
pdf(file=paste(outFile,".",sCV,".","split",iSplit,".pdf",sep=""))
plot(my.datf.train[,1],pred.tr,xlab="Yobs", ylab="Ypred", type="b", main="Train Yobs-Ypred")
plot(my.datf.test[,1], pred.ts,xlab="Yobs", ylab="Ypred", type="b", main="Test Yobs-Ypred")
dotchart(as.matrix(FeatImp$importance),main="Feature Importance")
# Fitted vs Residuals
plot(fitted(fitModel),residuals(fitModel),
main="Fitted vs. Residuals for Fitted Model",
xlab="Fitted", ylab="Residuals")
abline(h = 0, lty = 2)
# Leverage plots
if(det.Traind.pls!=0){
plot(hat.fit, type = "h",
main="Leverage for Fitted Model",
xlab="Index", ylab="Hat")
abline(h = thresh.lever, lty = 2, col="red") # leverage thresh
}
dev.off()
# --------------------------------------------------------------
}
return(list(stat.values=my.stats, model=pls.fit)) # return a list with statistics and the full model
}
#----------------------------------------------------------------------------------------------------------------------
LASSOreg <- function(my.datf.train,my.datf.test,sCV,iSplit=1,fDet=F,outFile="") {
#================================
# 8.4 Lasso Regression (caret)
#================================
#library(caret)
net.c = my.datf.train[,1] # dependent variable is the first column in Training set
RegrMethod <- "lasso.RMSE" # type of regression
# Define the CV conditions
ctrl<- trainControl(method = sCV, number = 10,repeats = 10,
summaryFunction = defaultSummary)
# Train the model using only training set
set.seed(iSplit)
las.fit<- train(net.c~.,data=my.datf.train,
method='lasso', tuneLength = 10, trControl = ctrl,
metric='RMSE' ) #,tuneGrid=expand.grid(.fraction= seq(0.1,1,by=0.1)))
#------------------------------
# Training RESULTS
#------------------------------
RMSE.tr <- las.fit$results[,2]
R2.tr <- las.fit$results[,3]
if (sCV == "repeatedcv"){ # if 10-fold CV
RMSEsd.tr <- las.fit$results[,4]
R2sd.tr <- las.fit$results[,5]
}
if (sCV == "LOOCV"){ # if LOOCV
RMSEsd.tr <- 0 # formulas will be added later!
R2sd.tr <- 0 # formulas will be added later!
}
#------------------------------------------------
# RMSE & R^2, for train/test respectively
#------------------------------------------------
lm.train.res <- getTrainPerf(las.fit)
lm.test.res <- postResample(predict(las.fit,my.datf.test),my.datf.test[,1])
#------------------------------------------------
# Adj R2, Pearson correlation
#------------------------------------------------
pred.tr <- predict(las.fit,my.datf.train) # predicted Y
pred.ts <- predict(las.fit,my.datf.test) # predicted Y
noFeats.fit <- length(predictors(las.fit)) # no. of features from the fitted model
Feats.fit <- paste(predictors(las.fit),collapse="+") # string with the features included in the fitted model
ds.full <- rbind(my.datf.train,my.datf.test)
pred.both <- predict(las.fit,ds.full) # predicted Y
adjR2.tr <- r2.adj.funct(my.datf.train[,1],pred.tr,noFeats.fit)
adjR2.ts <- r2.adj.funct(my.datf.test[,1],pred.ts,noFeats.fit)
corP.ts <- cor(my.datf.test[,1],pred.ts)
adjR2.both <- r2.adj.funct(ds.full[,1],pred.both,noFeats.fit)
RMSE.both <- rmse.funct(ds.full[,1],pred.both)
r2.both <- r2.funct(ds.full[,1],pred.both)
# Generate the output list with statistics for each cross-validation type
# --------------------------------------------------------------------
my.stats <- list("RegrMeth" = RegrMethod,
"Split No" = as.numeric(iSplit), # from function param
"CVtype" = sCV, # from function param
"NoModelFeats" = as.numeric(noFeats.fit),
"ModelFeats" = Feats.fit,
"adjR2.tr" = as.numeric(adjR2.tr),
"RMSE.tr" = as.numeric(min(RMSE.tr)), # these 4 lines correspond to the min of RMSE.tr !!!
"R2.tr" = as.numeric(R2.tr[which.min(RMSE.tr)]),
"RMSEsd.tr" = as.numeric(RMSEsd.tr[which.min(RMSE.tr)]),
"R2sd.tr" = as.numeric(R2sd.tr[which.min(RMSE.tr)]),
"adjR2.ts"= as.numeric(adjR2.ts),
"RMSE.ts" = as.numeric((lm.test.res["RMSE"][[1]])),
"R2.ts" = as.numeric((lm.test.res["Rsquared"][[1]])),
"corP.ts" = as.numeric(corP.ts),
"adjR2.both" = as.numeric(adjR2.both),
"RMSE.both" = as.numeric(RMSE.both),
"R2.both" = as.numeric(r2.both))
#---------------------------------------------------------------------
# Write to file DETAILS for GLM for each cross-validation method
#---------------------------------------------------------------------
if (fDet==T) { # if flag for details if true, print details about any resut
write("RRegr package | eNanoMapper", file=outFile,append=T)
write.table(paste("Regression method: ", RegrMethod), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("Split no.: ", iSplit), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(paste("CV type: ", sCV), file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table("Training Set Summary: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(summary(my.datf.train), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Test Set Summary: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(summary(my.datf.test), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Predictors: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(predictors(las.fit), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Trainig Results: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
AppendList2CSv(predictors(lm.train.res),outFile)
#write.table(predictors(lm.train.res), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Test Results: ", file=outFile,append=T,sep=",",col.names=F,quote=F)
AppendList2CSv(predictors(lm.test.res),outFile)
#write.table(predictors(lm.test.res), file=outFile,append=T,sep=",",col.names=T,quote=F)
write.table("Full Statistics: ", file=outFile,append=T,sep=",",col.names=F,row.names=F,quote=F)
write.table(my.stats, file=outFile,append=T,sep=",",col.names=T,quote=F)
# Variable Importance (max top 20)
FeatImp <- varImp(las.fit, scale = F)
components = length(FeatImp) # default plot all feature importance
if (length(FeatImp)>20){ # if the number of features is greater than 20, use only 20
components = 20