-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathA1_Part1_Cifar.py
254 lines (191 loc) · 7.65 KB
/
A1_Part1_Cifar.py
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
# -*- coding: utf-8 -*-
"""CIFAR10.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1w9VIqh9qqxkWrKOwp12_u5_LjfyHJIGL
# Assignment 1, Task 1
---
Authors: Chloe Tap, Evan Meltz, Giulia Rivetti (Group 36)
# MLP on CIFAR-10
"""
# Import libraries
import keras
import tensorflow as tf
import numpy as np
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, BatchNormalization, Dropout
from keras import backend as K
"""Load data, reshape and normalize"""
batch_size = 128
num_classes = 10
epochs = 20
# Load data
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
# Transform label indices to one-hot encoded vectors
y_train = keras.utils.to_categorical(y_train, num_classes=10)
y_test = keras.utils.to_categorical(y_test, num_classes=10)
# Transform images from (32,32,3) to 3072-dimensional vectors (32*32*3)
X_train = np.reshape(X_train,(50000,3072))
X_test = np.reshape(X_test,(10000,3072))
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
# Normalization of pixel values (to [0-1] range)
X_train /= 255
X_test /= 255
"""The following are the three best architectures and configurations that we have found on the Fashion MNIST dataset"""
current_config = 1
model = Sequential()
# First best configuration
if current_config == 1:
model.add(Dense(512, activation='sigmoid', kernel_initializer = 'glorot_uniform',
input_shape=(3072,)))
model.add(Dropout(0.1))
model.add(Dense(512, activation='sigmoid', kernel_initializer = 'glorot_uniform'))
model.add(Dropout(0.1))
model.add(Dense(num_classes, activation='softmax'))
model.summary()
model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.Adamax(learning_rate=0.01),
metrics=['accuracy'])
# Second best configuration
elif current_config == 2:
model.add(Dense(512, activation='sigmoid', kernel_initializer = 'glorot_uniform',
input_shape=(3072,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='sigmoid', kernel_initializer = 'glorot_uniform'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))
model.summary()
model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
metrics=['accuracy'])
# Third best configuration
elif current_config == 3:
model.add(Dense(512, activation='relu', kernel_initializer = 'glorot_uniform',
input_shape=(3072,)))
model.add(Dense(512, activation='relu', kernel_initializer = 'glorot_uniform'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))
model.summary()
model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.AdamW(learning_rate=0.001),
metrics=['accuracy'])
model.summary()
model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.AdamW(learning_rate=0.001),
metrics=['accuracy'])
history = model.fit(X_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(X_test, y_test))
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
"""### Performance of the MLP on CIFAR-10 dataset
Configuration 1 (current_config = 1):
- Test loss: 1.3777376413345337
- Test accuracy: 0.5048999786376953
Configuration 2 (current_config = 2):
- Test loss: 1.4003022909164429
- Test accuracy: 0.5019000172615051
Configuration 3 (current_config = 3):
- Test loss: 1.6033897399902344
- Test accuracy: 0.421999990940094
# CNN on CIFAR-10
Load data, reshape and normalize
"""
batch_size = 128
num_classes = 10
epochs = 12
# input image dimensions
img_rows, img_cols = 32, 32
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# Normalize the data. Before we need to connvert data type to float for computation.
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
# Convert class vectors to binary class matrices. This is called one hot encoding.
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
best_init = 'glorot_uniform'
best_activ = ['tanh', 'relu']
first_best_opt = tf.keras.optimizers.AdamW(learning_rate = 0.001)
second_best_opt = tf.keras.optimizers.Adam(learning_rate = 0.001)
"""The following are the three best configurations that we have found by experimenting on the Fashion MNIST dataset in the case of the CNN"""
model = Sequential()
best_config = 3
input_shape = (1, img_rows, img_cols)
if best_config == 1:
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=x_train.shape[1:]))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu', kernel_initializer = 'glorot_uniform'))
model.add(Dropout(0.2))
model.add(Dense(64, activation='relu', kernel_initializer = 'glorot_uniform'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))
model.summary()
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
metrics=['accuracy'])
elif best_config == 2:
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=x_train.shape[1:]))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu', kernel_initializer = 'glorot_uniform'))
model.add(Dropout(0.2))
model.add(Dense(64, activation='relu', kernel_initializer = 'glorot_uniform'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))
model.summary()
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=tf.keras.optimizers.AdamW(learning_rate=0.001),
metrics=['accuracy'])
elif best_config == 3:
model.add(Conv2D(32, kernel_size=(3, 3),
activation='tanh',
input_shape=x_train.shape[1:]))
model.add(Conv2D(64, (3, 3), activation='tanh'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.1))
model.add(Flatten())
model.add(Dense(128, activation='tanh', kernel_initializer = 'glorot_uniform'))
model.add(Dropout(0.1))
model.add(Dense(64, activation='tanh', kernel_initializer = 'glorot_uniform'))
model.add(Dropout(0.1))
model.add(Dense(num_classes, activation='softmax'))
model.summary()
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=tf.keras.optimizers.AdamW(learning_rate=0.001),
metrics=['accuracy'])
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
"""### Performance on the CIFAR-10 dataset for the CNN model
Configuration 1 (best_config = 1):
- Test loss: 0.9087339043617249
- Test accuracy: 0.7008000016212463
Configuration 2 (best_config = 2):
- Test loss: 0.9267891645431519
- Test accuracy: 0.7006999850273132
Configuration 3 (best_config = 3):
- Test loss: 0.9208132028579712
- Test accuracy: 0.7001000046730042
"""