-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsolidated code_12092018.R
1829 lines (1216 loc) · 63.8 KB
/
consolidated code_12092018.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
library(dplyr)
library(glmnet)
library(caret)
forest_cover <- read.table("C:/Users/ems97/OneDrive/Documents/MSPA/454/Forest_Cover/covtype.data.gz",
header = FALSE, sep =",")
dim(forest_cover)
names(forest_cover) <- c("Elevation","Aspect","Slope","Horizontal_Distance_To_Hydrology","Vertical_Distance_To_Hydrology",
"Horizontal_Distance_To_Roadways","Hillshade_9am","Hillshade_Noon","Hillshade_3pm",
"Horizontal_Distance_To_Fire_Points","Wilderness_Area1",
"Wilderness_Area2","Wilderness_Area3","Wilderness_Area4",
"soil_Type1","soil_Type2","soil_Type3"
,"soil_Type4","soil_Type5","soil_Type6","soil_Type7","soil_Type8","soil_Type9","soil_Type10","soil_Type11"
,"soil_Type12","soil_Type13","soil_Type14","soil_Type15","soil_Type16","soil_Type17","soil_Type18","soil_Type19"
,"soil_Type20","soil_Type21","soil_Type22","soil_Type23","soil_Type24","soil_Type25","soil_Type26","soil_Type27"
,"soil_Type28","soil_Type29","soil_Type30","soil_Type31","soil_Type32","soil_Type33","soil_Type34","soil_Type35"
,"soil_Type36","soil_Type37","soil_Type38","soil_Type39","soil_Type40","Cover_Type")
str(forest_cover)
########################Replace wilderness areas with actual names############
forest_cover<-dplyr::rename(forest_cover, Rawah_Wild_Area = Wilderness_Area1,
Neota_Wild_Area = Wilderness_Area2,
Comanche_Peak_Wild_Area = Wilderness_Area3,
Cache_la_Poudre_Wild_Area = Wilderness_Area4)
forest_cover<-setNames(forest_cover, tolower(names(forest_cover)))
## Assign df=forest_cover
df=forest_cover
df_gbm=forest_cover
## Derive binned variables
df$soil_type1_6 <- 0
df$soil_type38_39_40 <- 0
df$soil_type23_30_12_32_33_29 <- 0
for (i in 1:length(df)) {
if (df$soil_type1[i]==1 | df$soil_type2[i]==1 | df$soil_type3[i]==1 | df$soil_type4[i]==1 | df$soil_type5[i]==1 | df$soil_type6[i]==1) {
df$soil_type1_6[i] <- 1
}
if (df$soil_type38[i]==1 | df$soil_type39[i]==1 | df$soil_type40[i]==1) {
df$soil_type38_39_40[i] <- 1
}
if (df$soil_type23[i]==1 | df$soil_type30[i]==1 | df$soil_type12[i]==1 | df$soil_type32[i]==1 |
df$soil_type33[i]==1 | df$soil_type29[i]==1) {
df$soil_type23_30_12_32_33_29 <- 1
}
}
## make copy of cover_type. This is needed for minority class classifier
df$cover_type1=df$cover_type
## reset any class apart from spruce and lodgepole to others.Thus
## we will have three classes namely spruce, lodgepole and others
df=df %>% mutate(cover_type = ifelse(cover_type == 1 ,'Spruce/Fir',
ifelse(cover_type == 2 ,'Lodgepole Pine',ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz',NA))))))))
set.seed(1234)
library(glmnet)
trainIndex <- createDataPartition(df$cover_type, p = .7,
list = FALSE,
times = 1)
df_train <- df[ trainIndex,]
df_test <- df[-trainIndex,]
## create df_train_others and df_test others to create a classifier only for
## Aspen ,Cottonwood/Willow, Douglas-fir, Krummholz & Ponderosa Pine
df_train_others <-df[ trainIndex,]
df_test_others <-df[-trainIndex,]
df_test_all <-df[-trainIndex,]
## so we two classifiers
## one on df_train containing Lodgepole Pine,Spruce/Fir and others
## second classifier on df_train_others classifying among Aspen ,Cottonwood/Willow, Douglas-fir, Krummholz & Ponderosa Pine
##remove cover_type1
df_train <-subset(df_train, select=-c(cover_type1))
df_test <-subset(df_test, select=-c(cover_type1))
####others
df_train_others$cover_type=df_train_others$cover_type1
df_test_others$cover_type=df_test_others$cover_type1
#df_train_others ==> only Aspen ,Cottonwood/Willow, Douglas-fir, Krummholz & Ponderosa Pine
df_train_others=df_train_others %>% filter(cover_type !=1 & cover_type != 2 )
dim(df_train_others)
dim(df_test_others)
table(df_train_others$cover_type)
table(df_test_others$cover_type)
df_train_others= df_train_others %>%
mutate(cover_type = ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz','na'))))))
df_test_others= df_test_others %>%
mutate(cover_type = ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz','na'))))))
table(df_train_others$cover_type)
table(df_test_others$cover_type)
df_train_others <-df_train_others[-56]
df_test_others <-df_test_others[-56]
df_test_all$cover_type=df_test_all$cover_type1
df_test_all = df_test_all %>% mutate(cover_type = ifelse(cover_type == 1 ,'Spruce/Fir',
ifelse(cover_type == 2 ,'Lodgepole Pine',ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz',NA))))))))
table(df_test_all$cover_type)
df_test_all <-df_test_all[-56]
df_train$cover_type = as.factor(df_train$cover_type)
df_train_others$cover_type = as.factor(df_train_others$cover_type)
df_test$cover_type = as.factor(df_test$cover_type)
df_test_others$cover_type = as.factor(df_test_others$cover_type)
df_test_all$cover_type = as.factor(df_test_all$cover_type)
x.train_others <- model.matrix(~.*.-1, df_train_others[,-55])
y.train_others<-df_train_others$cover_type
x.test_others <- model.matrix(~.*.-1, df_test_others[,-55])
y.test_others<-df_test_others$cover_type
## random forest model
library(randomForest)
set.seed(1234)
model.rf <- randomForest(cover_type ~.,
df_train, importance=T ,ntree = 100, do.trace=T)
confusionMatrix(predict(model.rf), df_train$cover_type)
plot(model.rf)
summary(model.rf)
importance(model.rf)
varImpPlot(model.rf,sort = T,main="Variable Importance",n.var=50)
######Multinomial Logistic Regression
library(nnet)
#Main Types
set.seed(1234)
mlr <- multinom(cover_type ~ hillshade_3pm + log(hillshade_9am+1) + elevation + horizontal_distance_to_fire_points
+ horizontal_distance_to_roadways + log(vertical_distance_to_hydrology+174) + hillshade_noon
+ soil_type33 + sqrt(horizontal_distance_to_hydrology+1) + soil_type20 + aspect
+ soil_type31 + soil_type22 + hillshade_9am:hillshade_noon, data=df_train)
set.seed(1234)
mlr <- multinom(cover_type ~ hillshade_3pm + log(hillshade_9am+1) + elevation + horizontal_distance_to_fire_points
+ horizontal_distance_to_roadways + log(vertical_distance_to_hydrology+174) + hillshade_noon
+ sqrt(horizontal_distance_to_hydrology+1) + soil_type1_6 + aspect + soil_type38_39_40
+ soil_type23_30_12_32_33_29 + soil_type10 + comanche_peak_wild_area, data=df_train)
mlr_predict <- predict(mlr,newdata=df_train,type='class')
confusionMatrix(as.factor(mlr_predict),as.factor(df_train$cover_type))
library(pROC)
mr <- multiclass.roc(as.numeric(df_test$cover_type),as.numeric(mlr_predict), percent = TRUE)
mlr_predict <- predict(mlr,newdata=df_test,type='class')
confusionMatrix(as.factor(mlr_predict),as.factor(df_test$cover_type))
library(pROC)
mr <- multiclass.roc(as.numeric(df_train$cover_type),as.numeric(mlr_predict), percent = TRUE)
mlr_prediction <- predict(mlr,newdata=test.df,type="class")
#############code for gbm,lasso,ridge,elasticnet and ann using keras
## code for gbm, lasso,ridge ,elastic net and ann
###########################gbm#####gbm#####gbm######################################
mapping_df <- read.csv("D:/Data/Project_Folders/mtg_coverdata/mapping.csv",
sep =",")
forest_cover<-setNames(forest_cover, tolower(names(forest_cover)))
df=forest_cover
df$cover_type1=df$cover_type
df_mod<-df
df_mod$wld_area <- names(df_mod[11:14])[max.col(df_mod[11:14])]
table(df_mod$wld_area)
df_mod$soil_type <- names(df_mod[15:54])[max.col(df_mod[15:54])]
table(df_mod$soil_type)
df_mod$wld_area<-as.factor(df_mod$wld_area)
df_mod$soil_type<-as.factor(df_mod$soil_type)
library(sqldf)
#sqldf(" select climate,
# case
# when climate like '%1%' then 'lower montane dry'
# when climate like '%2%' then 'lower montane'
# when climate like '%3%' then 'montane dry'
# when climate like '%4%' then 'montane'
# when climate like '%5%' then 'montane dry and montane'
# when climate like '%6%' then 'montane and subalpine'
# when climate like '%7%' then 'subalpine'
# when climate like '%8%' then 'alpine'
# else 'unknown'
## end exd
# from df_mod"
#)
##new features
df_final<-sqldf('select df_mod.*, mapping_df.soil_desc,
mapping_df.climate,
mapping_df.geology
from df_mod left outer join mapping_df on
df_mod.soil_type = mapping_df.soil_type')
#drop column 59 which is soil_type from outer join
#euclidian distance
#Euclidean_Distance_To_Hydrology Square root of the sum of the squared horizontal & vertical distances to water
df_final$distance_eucld<-sqrt(df_final$horizontal_distance_to_hydrology**2+df_final$vertical_distance_to_hydrology**2)
df_final<-df_final[-(56:57)]
##transformation to sqrt and log
transform <- function(x,method) {
#Square-root:
if(method == "sqrt") {print("Applying Square-root transformation:"); y=sqrt(x+1)}
#Log:
if(method == "log") {print("Applying Log transformation:"); y=log(x+ 1 - min(x))}
return(y)
}
df_final$slope=transform(df_final$slope,method="sqrt")
df_final[,4]=transform(df_final[,4],method="sqrt")
df_final[,6]=transform(df_final[,6],method="sqrt")
df_final[,10]=transform(df_final[,10],method="sqrt")
df_final[,60]=transform(df_final[,60],method="sqrt")
df_final[,5]=transform(df_final[,5],method="log")
##delete the redudant columns
#3 ==> slope sqrt
#4 ==> horizontal_distance_to_hydrology sqrt
#5 ==> vertical_distance_to_hydrology log
#6 ==> horizontal_distance_to_roadways sqrt
#10 ==> horizontal_distance_to_fire_points sqrt
#60 ==> distance_eucld sqrt
#### Interactions
df_final$aspectelevation = df_final$aspect *df_final$elevation
df_final$aspecthillshade_3pm = df_final$aspect *df_final$hillshade_3pm
df_final$aspecthillshade_9am = df_final$aspect *df_final$hillshade_9am
df_final$aspecthillshade_noon = df_final$aspect *df_final$hillshade_noon
df_final$aspecthorizontal_distance_to_fire_points = df_final$aspect *df_final$horizontal_distance_to_fire_points
df_final$aspecthorizontal_distance_to_hydrology = df_final$aspect *df_final$horizontal_distance_to_hydrology
df_final$aspecthorizontal_distance_to_roadways = df_final$aspect *df_final$horizontal_distance_to_roadways
df_final$aspectslope = df_final$aspect *df_final$slope
df_final$aspectvertical_distance_to_hydrology = df_final$aspect *df_final$vertical_distance_to_hydrology
df_final$elevationaspect = df_final$elevation *df_final$aspect
df_final$elevationhillshade_3pm = df_final$elevation *df_final$hillshade_3pm
df_final$elevationhillshade_9am = df_final$elevation *df_final$hillshade_9am
df_final$elevationhillshade_noon = df_final$elevation *df_final$hillshade_noon
df_final$elevationhorizontal_distance_to_fire_points = df_final$elevation *df_final$horizontal_distance_to_fire_points
df_final$elevationhorizontal_distance_to_hydrology = df_final$elevation *df_final$horizontal_distance_to_hydrology
df_final$elevationhorizontal_distance_to_roadways = df_final$elevation *df_final$horizontal_distance_to_roadways
df_final$elevationslope = df_final$elevation *df_final$slope
df_final$elevationvertical_distance_to_hydrology = df_final$elevation *df_final$vertical_distance_to_hydrology
df_final$slopeaspect = df_final$slope *df_final$aspect
df_final$slopeelevation = df_final$slope *df_final$elevation
df_final$slopehillshade_3pm = df_final$slope *df_final$hillshade_3pm
df_final$slopehillshade_9am = df_final$slope *df_final$hillshade_9am
df_final$slopehillshade_noon = df_final$slope *df_final$hillshade_noon
df_final$slopehorizontal_distance_to_fire_points = df_final$slope *df_final$horizontal_distance_to_fire_points
df_final$slopehorizontal_distance_to_hydrology = df_final$slope *df_final$horizontal_distance_to_hydrology
df_final$slopehorizontal_distance_to_roadways = df_final$slope *df_final$horizontal_distance_to_roadways
df_final$slopevertical_distance_to_hydrology = df_final$slope *df_final$vertical_distance_to_hydrology
set.seed(1234)
df_final=df_final %>% mutate(cover_type = ifelse(cover_type == 1 ,'Spruce/Fir',
ifelse(cover_type == 2 ,'Lodgepole Pine','others')))
df_final<-df_final[,-which(names(df_final) %in% c("soil_type15"))]
library(glmnet)
trainIndex <- createDataPartition(df_final$cover_type, p = .7,
list = FALSE,
times = 1)
df_train <- df_final[ trainIndex,]
df_test <- df_final[-trainIndex,]
df_plot_train<-df_final[ trainIndex,]
df_plot_train$cover_type=df_train$cover_type1
df_plot_train <-df_plot_train[-55]
df_plot_test<-df_final[ -trainIndex,]
df_plot_test$cover_type=df_test$cover_type1
df_plot_test <-df_plot_test[-55]
df_plot_train=df_plot_train %>%
mutate(cover_type = ifelse(cover_type == 1 ,'Spruce',
ifelse(cover_type == 2 ,'Lodgepole',
ifelse(cover_type == 3 ,'Ponderosa',
ifelse(cover_type == 4 ,'Cottonwood',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas',
ifelse(cover_type == 7 ,'Krummholz','na'))))))))
df_plot_test=df_plot_test %>%
mutate(cover_type = ifelse(cover_type == 1 ,'Spruce',
ifelse(cover_type == 2 ,'Lodgepole',
ifelse(cover_type == 3 ,'Ponderosa',
ifelse(cover_type == 4 ,'Cottonwood',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas',
ifelse(cover_type == 7 ,'Krummholz','na'))))))))
true_label_train <- dummies::dummy(df_plot_train$cover_type)
true_label_train <- data.frame(true_label_train)
true_label_test <- dummies::dummy(df_plot_test$cover_type)
true_label_test <- data.frame(true_label_test)
####################################################
df_train_others <-df_final[ trainIndex,]
df_test_others <-df_final[-trainIndex,]
df_train_all <-df_final[ trainIndex,]
df_test_all <-df_final[-trainIndex,]
##remove cover_type1
df_train <-df_train[-55]
df_test <-df_test[-55]
####others
df_train_others$cover_type=df_train_others$cover_type1
df_test_others$cover_type=df_test_others$cover_type1
df_train_others <-df_train_others[-55]
df_test_others <-df_test_others[-55]
df_train_all$cover_type=df_train_all$cover_type1
df_test_all$cover_type=df_test_all$cover_type1
df_train_all <-df_train_all[-55]
df_test_all <-df_test_all[-55]
df_train_others=df_train_others %>% filter(cover_type !=1 & cover_type != 2 )
dim(df_train_others)
df_test_others=df_test_others %>% filter(cover_type !=1 & cover_type != 2)
dim(df_test_others)
df_train_others$cover_type=droplevels(as.factor(df_train_others$cover_type))
df_test_others$cover_type=droplevels(as.factor(df_test_others$cover_type))
df_test_all=df_test_all %>%
mutate(cover_type = ifelse(cover_type == 1 ,'Spruce/Fir',
ifelse(cover_type == 2 ,'Lodgepole Pine',
ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz','na'))))))))
df_train_all=df_train_all %>%
mutate(cover_type = ifelse(cover_type == 1 ,'Spruce/Fir',
ifelse(cover_type == 2 ,'Lodgepole Pine',
ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz','na'))))))))
df_train_others= df_train_others %>%
mutate(cover_type = ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz','na'))))))
df_test_others= df_test_others %>%
mutate(cover_type = ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz','na'))))))
dim(df_train)
dim(df_test)
dim(df_train_others)
dim(df_test_others)
dim(df_train_all)
dim(df_test_all)
system.time(gbmModel <- gbm(cover_type ~ .,
data= df_train ,
interaction.depth=3,
n.trees = 750 ,
n.minobsinnode=400,
cv.folds=3,
shrinkage=.03,
verbose=TRUE,
n.cores = 6 ,
distribution = "multinomial"))
bestreee = gbm.perf(gbmModel)
gbm_pred<-predict(gbmModel,
newdata = df_test,
n.trees = bestreee,
type = "response")
gbm_pred<-predict(gbmModel,
newdata = df_train,
n.trees = gbm.perf(gbmModel),
type = "response")
predict_gbm <- apply(gbm_pred, 1, which.max)
predict_gbm<-as.factor(colnames(gbm_pred)[predict_gbm])
#confusionMatrix(as.factor(predict_gbm),as.factor(df_test$cover_type))
bestreee = gbm.perf(gbmModel)
#save(gbmModel , file="D:/Data/Project_Folders/mtg_coverdata/gbmModel_final.Rdata")
gbmModel <- get(load('D:/Data/Project_Folders/mtg_coverdata/gbmModel_final.Rdata'))
gbmModel1 <- get(load('D:/Data/Project_Folders/mtg_coverdata/gbmModel1_final.Rdata'))
varimp_cols<-c(as.character(droplevels(summary(gbmModel)$var[1:30])),'cover_type')
##78.76
system.time(gbmModel1 <- gbm(cover_type ~ .,
data= df_train[varimp_cols] ,
interaction.depth=3,
n.trees = 750 ,
n.minobsinnode=400,
cv.folds=3,
shrinkage=.03,
verbose=TRUE,
n.cores = 6 ,
distribution = "multinomial"))
plot(gbmModel)
bestreee1 = gbm.perf(gbmModel1)
gbm_pred1<-predict(gbmModel1,
newdata = df_test[varimp_cols],
n.trees = bestreee1,
type = "response")
predict_gbm1 <- apply(gbm_pred1, 1, which.max)
predict_gbm1<-as.factor(colnames(gbm_pred1)[predict_gbm1])
confusionMatrix(as.factor(predict_gbm1),as.factor(df_test$cover_type))
save(gbmModel1 , file="D:/Data/Project_Folders/mtg_coverdata/gbmModel1_final.Rdata")
#gbmModel1 <- get(load('D:/forestcover/Forest_Cover/gbm_model1.Rdata')
##
df_predict_others=df_test[which(as.character(predict_gbm1)=='others'),]
df_predict_others_train=df_train[which(as.character(predict_gbm)=='others'),]
#############3others
system.time(gbmModel_others <- gbm(cover_type ~ .,
data= df_train_others ,
interaction.depth=3,
n.trees = 750 ,
n.minobsinnode=400,
cv.folds=3,
shrinkage=.03,
verbose=TRUE,
n.cores = 6 ,
distribution = "multinomial"))
bestreee = gbm.perf(gbmModel_others)
gbm_pred_others<-predict(gbmModel_others,
newdata = df_train_others,
n.trees = gbm.perf(gbmModel_others),
type = "response")
predict_gbm_others <- apply(gbm_pred_others, 1, which.max)
predict_gbm_others <-as.factor(colnames(gbm_pred_others)[predict_gbm_others])
confusionMatrix(as.factor(predict_gbm_others),as.factor(df_test_others$cover_type))
#save(gbmModel_others , file="D:/Data/Project_Folders/mtg_coverdata/gbmModel_others.Rdata")
#gbmModel_others <- get(load('D:/forestcover/Forest_Cover/gbmmodel_others.Rdata')
varimp_cols_others<-c(as.character(droplevels(summary(gbmModel_others)$var[1:30])),'cover_type')
system.time(gbmModel1_others <- gbm(cover_type ~ .,
data= df_train_others[varimp_cols_others] ,
interaction.depth=3,
n.trees = 750 ,
n.minobsinnode=400,
cv.folds=3,
shrinkage=.03,
verbose=TRUE,
n.cores = 6 ,
distribution = "multinomial"))
bestreee1 = gbm.perf(gbmModel1_others)
gbm_pred1_others<-predict(gbmModel1_others,
newdata = df_test_others[varimp_cols_others],
n.trees = bestreee1,
type = "response")
predict_gbm1_others <- apply(gbm_pred1_others, 1, which.max)
predict_gbm1_others<-as.factor(colnames(gbm_pred1_others)[predict_gbm1_others])
confusionMatrix(as.factor(predict_gbm1_others),as.factor(df_test_others$cover_type))
save(gbmModel1_others , file="D:/Data/Project_Folders/mtg_coverdata/gbmModel1_others.Rdata")
#gbmModel1_others <- get(load('D:/forestcover/Forest_Cover/gbmmodel1_others.Rdata')
#87.74
table(as.factor(predict_gbm1_others),as.factor(df_test_others$cover_type))
##final prediction on minority classes ..predict all others absed on model from others
gbm_pred2_others<-predict(gbmModel_others,
newdata = df_predict_others_train,
n.trees = gbm.perf(gbmModel_others),
type = "response")
gbm_pred2_others<-predict(gbmModel1_others,
newdata = df_predict_others[varimp_cols_others],
n.trees = bestreee1,
type = "response")
predict_gbm2_others <- apply(gbm_pred2_others, 1, which.max)
predict_gbm2_others<-as.factor(colnames(gbm_pred2_others)[predict_gbm2_others])
#confusionMatrix(as.factor(predict_gbm2_others),as.factor(df_predict_others$cover_type))
df1= as.character(predict_gbm)
df2=as.character(predict_gbm2_others)
idx=which(as.character(predict_gbm)=='others')
df1[idx]=df2[1:length(df2)]
table(df1)
confusionMatrix(as.factor(df1),as.factor(df_train_all$cover_type))
##77.38
###probability for auc
#gbm_pred1_prob
df_nb_train<-df_train[varimp_cols]
df_nb_test<-df_test[varimp_cols]
y.train<-as.factor(df_nb_train$cover_type)
y.test<-as.factor(df_nb_test$cover_type)
nb1<-naiveBayes(y.train~.,data=df_nb_train[,-31])
pred_nb1<-predict(nb1,df_nb_test[,-31],type="raw")
pred_nb2<-(apply(pred_nb1,1,which.max))
pred_nb2<-colnames(pred_nb1)[pred_nb2]
confusionMatrix(as.factor(pred_nb2),as.factor(y.test))
pred_nb1<-predict(nb1,df_nb_test[,-54])
#pred_nb2<-(apply(pred_nb1,1,which.max))
#pred_nb2<-colnames(pred_nb1)[pred_nb2]
confusionMatrix(as.factor(pred_nb1),as.factor(y.test))
gbmModel<-get(load('D:/Data/Project_Folders/mtg_coverdata/gbmModel_final.Rdata'))
gbmModel_others<-get(load('D:/Data/Project_Folders/mtg_coverdata/gbmModel_others.Rdata'))
bestreee = gbm.perf(gbmModel)
gbm_pred<-predict(gbmModel,
newdata = df_test,
n.trees = bestreee,
type = "response")
#predict_gbm <- apply(gbm_pred, 1, which.max)
#predict_gbm<-as.factor(colnames(gbm_pred)[predict_gbm])
gbm_pred <- data.frame(gbm_pred)
colnames(gbm_pred) <- paste(colnames(gbm_pred), "_gbm")
bestreee = gbm.perf(gbmModel_others)
gbm_pred1<-predict(gbmModel_others,
newdata = df_test,
n.trees = gbm.perf(gbmModel_others),
type = "response")
#predict_gbm1 <- apply(gbm_pred1, 1, which.max)
#predict_gbm1<-as.factor(colnames(gbm_pred)[predict_gbm1])
gbm_pred1 <- data.frame(gbm_pred1)
colnames(gbm_pred1) <- paste(colnames(gbm_pred1), "_gbm")
gbm_pred<-cbind(gbm_pred[,-2],gbm_pred1)
colnames(gbm_pred)
true_label<-true_label_test
pred<-gbm_pred
colnames(true_label) <- gsub(".*?\\.", "", colnames(true_label))
colnames(true_label) <- paste(colnames(true_label), "_true")
colnames(true_label) <- gsub("cover_type", "", colnames(true_label))
colnames(true_label) <- gsub(" ", "", colnames(true_label))
final_df <- cbind(true_label, pred)
colnames(final_df)
cols<-c("Lodgepole_pred_gbm",
"Spruce_pred_gbm",
"Aspen_pred_gbm",
"Cottonwood_pred_gbm",
"Douglas_pred_gbm",
"Krummholz_pred_gbm",
"Ponderosa_pred_gbm")
names(final_df)[8:14] <-cols
colnames(final_df)
final_df<-final_df[,c(1,2,3,4,5,6,7,10,11,12,13,8,14,9)]
colnames(final_df)
require(multiROC)
roc_res <- multi_roc(final_df,force_diag=T)
pr_res <- multi_pr(final_df, force_diag=T)
plot_roc_df <- plot_roc_data(roc_res)
plot_pr_df <- plot_pr_data(pr_res)
unlist(roc_res$AUC)
write.csv(unlist(roc_res$AUC), file = "D:/Data/Project_Folders/mtg_coverdata/gbm_test_auc.csv")
#write.csv(unlist(roc_res$AUC), file = "D:/Data/Project_Folders/mtg_coverdata/gbm_train_auc.csv")
require(ggplot2)
gbm_roc<-ggplot(plot_roc_df, aes(x = 1-Specificity, y=Sensitivity)) +
geom_path(aes(color = Group, linetype=Method), size=1.5) +
geom_segment(aes(x = 0, y = 0, xend = 1, yend = 1),
colour='grey', linetype = 'dotdash') +
theme_bw() +
theme(plot.title = element_text(hjust = 0.5),
legend.justification=c(1, 0), legend.position=c(.95, .05),
legend.title=element_blank(),
legend.background = element_rect(fill=NULL, size=0.5,
linetype="solid", colour ="black"))
png(filename="D:/Data/Project_Folders/mtg_coverdata/gbm_roc.png")
plot(gbm_roc)
dev.off()
############################end of gbm #####################################3
#########lasso,ridge,elastic net#########lasso , ridge,elasticnet ###########
df_train <- df_final[ trainIndex,]
df_test <- df_final[-trainIndex,]
df_train_others <-df_final[ trainIndex,]
df_test_others <-df_final[-trainIndex,]
#####################
#########################################
df_plot_train<-df_final[ trainIndex,]
df_plot_train$cover_type=df_train$cover_type1
df_plot_train <-df_plot_train[-55]
df_plot_test<-df_final[ -trainIndex,]
df_plot_test$cover_type=df_test$cover_type1
df_plot_test <-df_plot_test[-55]
df_plot_train=df_plot_train %>%
mutate(cover_type = ifelse(cover_type == 1 ,'Spruce',
ifelse(cover_type == 2 ,'Lodgepole',
ifelse(cover_type == 3 ,'Ponderosa',
ifelse(cover_type == 4 ,'Cottonwood',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas',
ifelse(cover_type == 7 ,'Krummholz','na'))))))))
df_plot_test=df_plot_test %>%
mutate(cover_type = ifelse(cover_type == 1 ,'Spruce',
ifelse(cover_type == 2 ,'Lodgepole',
ifelse(cover_type == 3 ,'Ponderosa',
ifelse(cover_type == 4 ,'Cottonwood',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas',
ifelse(cover_type == 7 ,'Krummholz','na'))))))))
true_label_train <- dummies::dummy(df_plot_train$cover_type)
true_label_train <- data.frame(true_label_train)
true_label_test <- dummies::dummy(df_plot_test$cover_type)
true_label_test <- data.frame(true_label_test)
##################################################
#######################
##remove cover_type1
df_train <-df_train[-55]
df_test <-df_test[-55]
dim(df_train)
dim(df_test)
df_train_others$cover_type=df_train_others$cover_type1
df_test_others$cover_type=df_test_others$cover_type1
df_train_others <-df_train_others[-55]
df_test_others <-df_test_others[-55]
dim(df_train_others)
dim(df_test_others)
x.train <- model.matrix(~.-1, df_train[,-54])
y.train<-df_train$cover_type
x.test <- model.matrix(~.-1, df_test[,-54])
y.test<-df_test$cover_type
dim(x.train)
dim(x.test)
####others
df_train_others=df_train_others %>% filter(cover_type !=1 & cover_type != 2 )
dim(df_train_others)
df_test_others=df_test_others %>% filter(cover_type !=1 & cover_type != 2)
dim(df_test_others)
table(df_train_others$cover_type)
table(df_test_others$cover_type)
df_train_others= df_train_others %>%
mutate(cover_type = ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz','na'))))))
dim(df_train_others)
df_test_others= df_test_others %>%
mutate(cover_type = ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz','na'))))))
dim(df_test_others)
x.train_others <- model.matrix(~.-1, df_train_others[,-54])
y.train_others<-df_train_others$cover_type
x.test_others <- model.matrix(~.-1, df_test_others[,-54])
y.test_others<-df_test_others$cover_type
dim(x.train_others)
dim(x.test_others)
library(doParallel)
library(doSNOW)
library(foreach)
t2 = Sys.time()
cl = makeCluster(9)
registerDoSNOW(cl)
set.seed(seed)
fit_lasso<-cv.glmnet(x.train,
y.train,
family="multinomial",
type.measure = "class",
alpha=1,
parallel = TRUE)
save(fit_lasso , file="D:/Data/Project_Folders/mtg_coverdata/fit_lasso1.Rdata")
predict_lasso<-predict(fit_lasso,newx=x.test,s=fit_lasso$lambda.min, type = "class")
confusionMatrix(as.factor(predict_lasso),as.factor(y.test))
#tmp_coeffs_lasso <- coef(fit_lasso, s = "lambda.min")
stopCluster(cl)
predict_lasso<-predict(fit_lasso,newx=x.train,s=fit_lasso$lambda.min, type = "class")
confusionMatrix(as.factor(predict_lasso),as.factor(y.test))
message("...Start to train glmnet...")
print((Sys.time() - t2))
coef(fit_lasso, s = "lambda.min")
plot(fit_lasso, xvar = "lambda", label = TRUE)
t2 = Sys.time()
cl = makeCluster(9)
registerDoSNOW(cl)
set.seed(seed)
fit_lasso_others<-cv.glmnet(x.train_others,
y.train_others,
family="multinomial",
type.measure = "class",
alpha=1,
parallel = TRUE)
save(fit_lasso_others , file="D:/Data/Project_Folders/mtg_coverdata/fit_lasso_others1.Rdata")
predict_lasso_others<-predict(fit_lasso_others,newx=x.test_others,s=fit_lasso_others$lambda.min, type = "class")
predict_lasso_others<-predict(fit_lasso_others,newx=x.train_others,s=fit_lasso_others$lambda.min, type = "class")
confusionMatrix(as.factor(predict_lasso_others),as.factor(y.test_others))
#tmp_coeffs_lasso_others <- coef(fit_lasso_others, s = "lambda.min")
stopCluster(cl)
message("...Start to train glmnet...")
print((Sys.time() - t2))
coef(fit_lasso_others, s = "lambda.min")
plot(fit_lasso_others, xvar = "lambda", label = TRUE)
df_predict_others=df_test[which(as.character(predict_lasso)=='others'),]
df_predict_others=df_train[which(as.character(predict_lasso)=='others'),]
##for these columns need to be modified
dim(df_predict_others)
df_train_all <- df_final[ trainIndex,]
df_test_all <- df_final[-trainIndex,]
df_train_all$cover_type=df_train_all$cover_type1
df_test_all$cover_type=df_test_all$cover_type1
df_test_all=df_test_all %>%
mutate(cover_type = ifelse(cover_type == 1 ,'Spruce/Fir',
ifelse(cover_type == 2 ,'Lodgepole Pine',
ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz','na'))))))))
df_train_all=df_train_all %>%
mutate(cover_type = ifelse(cover_type == 1 ,'Spruce/Fir',
ifelse(cover_type == 2 ,'Lodgepole Pine',
ifelse(cover_type == 3 ,'Ponderosa Pine',
ifelse(cover_type == 4 ,'Cottonwood/Willow',
ifelse(cover_type == 5 ,'Aspen',
ifelse(cover_type == 6 ,'Douglas-fir',
ifelse(cover_type == 7 ,'Krummholz','na'))))))))
x.lasso_others <- model.matrix(~.-1, df_predict_others[,-54])