-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathR_DeepLearning_Example
62 lines (52 loc) · 1.44 KB
/
R_DeepLearning_Example
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
# YouTube link: https://youtu.be/XVfn6IpoUPU
#install.packages("keras")
library(keras)
# Data
data <- read.csv('https://raw.githubusercontent.com/bkrai/DeepLearningR/master/Cardiotocographic.csv', header=T)
data$NSP <- data$NSP -1
barplot(prop.table(table(data$NSP)),
col = rainbow(3),
ylim = c(0, 0.8),
ylab = 'Proportion',
xlab = 'NSP',
cex.names = 1.5)
# Matrix
data <- as.matrix(data)
dimnames(data) <- NULL
# Normalize
data[,1:21] <- normalize(data[,1:21])
# Partition
set.seed(1234)
ind <- sample(2, nrow(data), replace = T, prob=c(.7, .3))
training <- data[ind==1, 1:21]
test <- data[ind==2, 1:21]
trainingtarget <- data[ind==1, 22]
testtarget <- data[ind==2, 22]
# One hot encoding
trainLabels <- to_categorical(trainingtarget)
testLabels <- to_categorical(testtarget)
# Creat sequential model and add layers
model <- keras_model_sequential()
model %>% layer_dense(units = 8, activation = 'relu', input_shape = c(21)) %>%
layer_dense(units = 3, activation = 'softmax')
summary(model)
# Compile
model %>% compile(loss = 'categorical_crossentropy',
optimizer = 'adam',
metrics = 'accuracy')
# Fit
fit <- model %>%
fit(training,
trainLabels,
epochs = 25,
batch_size = 8,
validation_split = 0.2)
plot(fit)
# Evaluate
model %>% evaluate(test, testLabels)
# Prediction
pred <- model %>%
predict(test) %>%
k_argmax() %>%
as.integer()
table(Predicted=pred, Actual=testtarget)