-
Notifications
You must be signed in to change notification settings - Fork 0
/
code in R
152 lines (123 loc) · 3.41 KB
/
code in 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
## Task 1: Project Overview & Import Libraries ##
library(keras)
```
```{r}
## Task 2: Import the Fashion MNIST Dataset ##
fashion_mnist <- dataset_fashion_mnist()
c(train_images, train_labels) %<-% fashion_mnist$train
c(test_images, test_labels) %<-% fashion_mnist$test
class_names = c('T-shirt/top',
'Trouser',
'Pullover',
'Dress',
'Coat',
'Sandal',
'Shirt',
'Sneaker',
'Bag',
'Ankle boot')
```
```{r}
## Task 3: Data Exploration ##
dim(train_images)
dim(train_labels)
train_labels[1:20]
dim(test_images)
dim(test_labels)
```
```{r}
## Task 4: Preprocess the Data ##
library(tidyr)
library(ggplot2)
image_1 <- as.data.frame(train_images[1, , ])
colnames(image_1) <- seq_len(ncol(image_1))
image_1$y <- seq_len(nrow(image_1))
image_1 <- gather(image_1, "x", "value", -y)
image_1$x <- as.integer(image_1$x)
ggplot(image_1, aes(x = x, y = y, fill = value)) +
geom_tile() +
scale_fill_gradient(low = "white", high = "black", na.value = NA) +
scale_y_reverse() +
theme_minimal() +
theme(panel.grid = element_blank()) +
theme(aspect.ratio = 1) +
xlab("") +
ylab("")
train_images <- train_images / 255
test_images <- test_images / 255
par(mfcol=c(5,5))
par(mar=c(0, 0, 1.5, 0), xaxs='i', yaxs='i')
for (i in 1:25) {
img <- train_images[i, , ]
img <- t(apply(img, 2, rev))
image(1:28, 1:28, img, col = gray((0:255)/255), xaxt = 'n', yaxt = 'n',
main = paste(class_names[train_labels[i] + 1]))
}
```
```{r}
## Task 5: Build the Model ##
model <- keras_model_sequential()
model %>%
layer_flatten(input_shape = c(28, 28)) %>%
layer_dense(units = 128, activation = 'relu') %>%
layer_dense(units = 10, activation = 'softmax')
```
```{r}
## Task 6: Compile the Model ##
model %>% compile(
optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = c('accuracy')
)
summary(model)
```
```{r}
## Task 7: Train and Evaluate the Model ##
model %>% fit(
train_images, train_labels,
epochs = 10, validation_split=0.2)
score <- model %>% evaluate(test_images, test_labels)
cat('Test loss:', score$loss, "\n")
cat('Test accuracy:', score$acc, "\n")
```
```{r}
## Task 8: Make Predictions on Test Data ##
predictions <- model %>% predict(test_images)
predictions[1, ]
which.max(predictions[1, ])
class_pred <- model %>% predict_classes(test_images)
class_pred[1:20]
test_labels[1]
# Grab an image from the test dataset
# take care to keep the batch dimension, as this is expected by the model
img <- test_images[1, , , drop = FALSE]
dim(img)
predictions <- model %>% predict(img)
predictions
# subtract 1 as labels are 0-based
prediction <- predictions[1, ] - 1
which.max(prediction)
class_pred <- model %>% predict_classes(img)
class_pred
```
```{r}
## Plot Images with Predictions ##
par(mfcol=c(5,5))
par(mar=c(0, 0, 1.5, 0), xaxs='i', yaxs='i')
for (i in 1:25) {
img <- test_images[i, , ]
img <- t(apply(img, 2, rev))
# subtract 1 as labels go from 0 to 9
predicted_label <- which.max(predictions[i, ]) - 1
true_label <- test_labels[i]
if (predicted_label == true_label) {
color <- '#008800'
} else {
color <- '#bb0000'
}
image(1:28, 1:28, img, col = gray((0:255)/255), xaxt = 'n', yaxt = 'n',
main = paste0(class_names[predicted_label + 1], " (",
class_names[true_label + 1], ")"),
col.main = color)
}
```