1
+ # install.packages('ISLR')
2
+ library(ISLR )
3
+
4
+ print(head(College ,2 ))
5
+
6
+ # Data Preprocessing
7
+ # Create Vector of Column Max and Min Values
8
+ maxs <- apply(College [,2 : 18 ], 2 , max )
9
+ mins <- apply(College [,2 : 18 ], 2 , min )
10
+
11
+ # Use scale() and convert the resulting matrix to a data frame
12
+ scaled.data <- as.data.frame(scale(College [,2 : 18 ],center = mins , scale = maxs - mins ))
13
+
14
+ # Check out results
15
+ print(head(scaled.data ,2 ))
16
+
17
+
18
+ # Train and Test Split
19
+ # Convert Private column from Yes/No to 1/0
20
+ Private = as.numeric(College $ Private )- 1
21
+ data = cbind(Private ,scaled.data )
22
+
23
+ library(caTools )
24
+ set.seed(101 )
25
+
26
+ # Create Split (any column is fine)
27
+ split = sample.split(data $ Private , SplitRatio = 0.70 )
28
+
29
+ # Split based off of split Boolean Vector
30
+ train = subset(data , split == TRUE )
31
+ test = subset(data , split == FALSE )
32
+
33
+
34
+ feats <- names(scaled.data )
35
+
36
+ # Concatenate strings
37
+ f <- paste(feats ,collapse = ' + ' )
38
+ f <- paste(' Private ~' ,f )
39
+
40
+ # Convert to formula
41
+ f <- as.formula(f )
42
+
43
+ f
44
+
45
+
46
+ # install.packages('neuralnet')
47
+ library(neuralnet )
48
+ nn <- neuralnet(f ,train ,hidden = c(10 ,10 ,10 ),linear.output = FALSE )
49
+
50
+
51
+ # Compute Predictions off Test Set
52
+ predicted.nn.values <- compute(nn ,test [2 : 18 ])
53
+
54
+ # Check out net.result
55
+ print(head(predicted.nn.values $ net.result ))
56
+
57
+
58
+ predicted.nn.values $ net.result <- sapply(predicted.nn.values $ net.result ,round ,digits = 0 )
59
+
60
+ table(test $ Private ,predicted.nn.values $ net.result )
0 commit comments