Labpractice 2
Labpractice 2
[3]: print('x_train',x_train.shape)
print('y_train',y_train.shape)
print('x_test',x_test.shape)
print('y_test',y_test.shape)
[8]: #save image parameters to the constants that we will use later for data␣
↪re-shaping and for model training
print('IMAGE_WIDTH:', IMAGE_WIDTH)
1
print('IMAGE_HEIGHT:', IMAGE_HEIGHT)
print('IMAGE_CHANNELS:', IMAGE_CHANNELS)
IMAGE_WIDTH: 32
IMAGE_HEIGHT: 32
IMAGE_CHANNELS: 3
[10]: #visualize
plt.imshow(x_train[0],cmap=plt.cm.binary)
plt.show()
[11]: numbers_to_display = 25
num_cells = math.ceil(math.sqrt(numbers_to_display))
plt.figure(figsize=(10,10))
for i in range(numbers_to_display):
plt.subplot(num_cells, num_cells, i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(x_train[i], cmap=plt.cm.binary)
plt.xlabel(y_train[i])
plt.show()
2
/usr/local/lib/python3.10/dist-packages/matplotlib/text.py:1279: FutureWarning:
elementwise comparison failed; returning scalar instead, but in the future will
perform elementwise comparison
if s != self._text:
x_test_with_chanels= x_test.reshape(
3
x_test.shape[0],
IMAGE_WIDTH,
IMAGE_HEIGHT,
IMAGE_CHANNELS
)
[13]: print('x_train_with_chanels:',x_train_with_chanels.shape)
print('x_test_with_chanels:',x_test_with_chanels.shape)
4
[0.49803922, 0.3372549 , 0.0627451 ],
[0.5372549 , 0.41176471, 0.10588235],
[0.59215686, 0.50196078, 0.21176471]])
model.add(tf.keras.layers.Convolution2D(
input_shape = (IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS),
kernel_size = 5,
filters = 8,
strides = 1,
activation= tf.keras.activations.relu,
kernel_initializer = tf.keras.initializers.VarianceScaling()
))
model.add(tf.keras.layers.MaxPooling2D(
pool_size = (2,2),
strides=(2,2)
))
model.add(tf.keras.layers.Convolution2D(
input_shape = (IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS),
kernel_size = 5,
filters = 16,
strides = 1,
activation= tf.keras.activations.relu,
kernel_initializer = tf.keras.initializers.VarianceScaling()
))
model.add(tf.keras.layers.MaxPooling2D(
pool_size = (2,2),
strides=(2,2)
))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(
units = 128, activation = tf.keras.activations.relu
))
model.add(tf.keras.layers.Dropout(0.2))
model.add(tf.keras.layers.Dense(
units = 10,
activation = tf.keras.activations.softmax,
kernel_initializer = tf.keras.initializers.VarianceScaling()
5
))
[17]: model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 28, 28, 8) 608
=================================================================
Total params: 56,442
Trainable params: 56,442
Non-trainable params: 0
_________________________________________________________________
model.compile(
optimizer=adam_optimizer,
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy']
)
6
Epoch 1/3
1563/1563 [==============================] - 21s 7ms/step - loss: 1.6220 -
accuracy: 0.4124 - val_loss: 1.4148 - val_accuracy: 0.4983
Epoch 2/3
1563/1563 [==============================] - 7s 5ms/step - loss: 1.3461 -
accuracy: 0.5196 - val_loss: 1.2512 - val_accuracy: 0.5519
Epoch 3/3
1563/1563 [==============================] - 6s 4ms/step - loss: 1.2458 -
accuracy: 0.5573 - val_loss: 1.2224 - val_accuracy: 0.5548
7
plt.plot(training_history.history['val_accuracy'], label='test set')
plt.legend()
8
#Resnet 18
[24]: import tensorflow as tf
import matplotlib.pyplot as plt
import seaborn as sn
import numpy as np
import pandas as pd
import math
import datetime
import platform
[26]: print('x_train',x_train.shape)
print('y_train',y_train.shape)
print('x_test',x_test.shape)
print('y_test',y_test.shape)
[27]: #save image parameters to the constants that we will use later for data␣
↪re-shaping and for model training
print('IMAGE_WIDTH:', IMAGE_WIDTH)
print('IMAGE_HEIGHT:', IMAGE_HEIGHT)
print('IMAGE_CHANNELS:', IMAGE_CHANNELS)
IMAGE_WIDTH: 32
IMAGE_HEIGHT: 32
IMAGE_CHANNELS: 3
[28]: #visualize
plt.imshow(x_train[0],cmap=plt.cm.binary)
plt.show()
9
[29]: x_train_with_chanels = x_train.reshape(
x_train.shape[0],
IMAGE_WIDTH,
IMAGE_HEIGHT,
IMAGE_CHANNELS
)
x_test_with_chanels= x_test.reshape(
x_test.shape[0],
IMAGE_WIDTH,
IMAGE_HEIGHT,
IMAGE_CHANNELS
)
[30]: print('x_train_with_chanels:',x_train_with_chanels.shape)
print('x_test_with_chanels:',x_test_with_chanels.shape)
10
x_test_normalized = x_test_with_chanels / 255
11
def resnet_block(x, filters, kernel_size=3, stride=1):
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Activation('relu')(x)
return x
input_layer = Input(shape=input_shape)
x = Conv2D(64, kernel_size=7, strides=2, padding='same')(input_layer)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=(3, 3), strides=2, padding='same')(x)
x = resnet_block(x, filters=64)
x = resnet_block(x, filters=64)
x = resnet_block(x, filters=128, stride=2)
x = resnet_block(x, filters=128)
x = resnet_block(x, filters=256, stride=2)
x = resnet_block(x, filters=256)
x = resnet_block(x, filters=512, stride=2)
x = resnet_block(x, filters=512)
x = GlobalAveragePooling2D()(x)
output_layer = Dense(num_classes, activation='softmax')(x)
resnet18_model.summary()
Model: "model_2"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_3 (InputLayer) [(None, 32, 32, 3)] 0
12
conv2d_36 (Conv2D) (None, 16, 16, 64) 9472
13
batch_normalization_40 (Bat (None, 4, 4, 128) 512
chNormalization)
14
batch_normalization_47 (Bat (None, 1, 1, 512) 2048
chNormalization)
=================================================================
Total params: 11,019,530
Trainable params: 11,011,722
Non-trainable params: 7,808
_________________________________________________________________
training_history = resnet18_model.fit(
x_train_normalized,
y_train_encoded,
15
epochs= 3,
validation_data=(x_test_normalized, y_test_encoded)
)
Epoch 1/3
1563/1563 [==============================] - 32s 20ms/step - loss: 1.1081 -
accuracy: 0.6251 - val_loss: 1.2142 - val_accuracy: 0.5884
Epoch 2/3
1563/1563 [==============================] - 32s 21ms/step - loss: 0.9596 -
accuracy: 0.6756 - val_loss: 1.2812 - val_accuracy: 0.5409
Epoch 3/3
1563/1563 [==============================] - 32s 20ms/step - loss: 0.8619 -
accuracy: 0.7112 - val_loss: 1.0369 - val_accuracy: 0.6572
16
[46]: plt.xlabel('Epoch Number')
plt.ylabel('Accuracy')
plt.plot(training_history.history['accuracy'],label='training set')
plt.plot(training_history.history['val_accuracy'], label='test set')
plt.legend()
17
print('Validation loss: ', validation_loss)
print('Validation accuracy: ', validation_accuracy)
[53]: print('x_train',x_train.shape)
print('y_train',y_train.shape)
print('x_test',x_test.shape)
print('y_test',y_test.shape)
[55]: #save image parameters to the constants that we will use later for data␣
↪re-shaping and for model training
print('IMAGE_WIDTH:', IMAGE_WIDTH)
print('IMAGE_HEIGHT:', IMAGE_HEIGHT)
print('IMAGE_CHANNELS:', IMAGE_CHANNELS)
18
IMAGE_WIDTH: 32
IMAGE_HEIGHT: 32
IMAGE_CHANNELS: 3
x_test_with_chanels= x_test.reshape(
x_test.shape[0],
IMAGE_WIDTH,
IMAGE_HEIGHT,
IMAGE_CHANNELS
)
19
[0.9254902 , 0.86666667, 0.77254902],
[0.9254902 , 0.83137255, 0.69019608],
[0.65098039, 0.49019608, 0.24705882],
[0.53333333, 0.33333333, 0.0627451 ],
[0.5254902 , 0.31764706, 0.05098039],
[0.50980392, 0.3254902 , 0.05098039],
[0.49803922, 0.3372549 , 0.0627451 ],
[0.5372549 , 0.41176471, 0.10588235],
[0.59215686, 0.50196078, 0.21176471]])
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Activation('relu')(x)
return x
input_layer = Input(shape=input_shape)
x = Conv2D(64, kernel_size=7, strides=2, padding='same')(input_layer)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=(3, 3), strides=2, padding='same')(x)
x = resnet_block(x, filters=64)
x = resnet_block(x, filters=64)
20
x = resnet_block(x, filters=64) # Additional block compared to ResNet-18
x = resnet_block(x, filters=128, stride=2)
x = resnet_block(x, filters=128)
x = resnet_block(x, filters=128)
x = resnet_block(x, filters=128) # Additional block compared to ResNet-18
x = resnet_block(x, filters=256, stride=2)
x = resnet_block(x, filters=256)
x = resnet_block(x, filters=256)
x = resnet_block(x, filters=256)
x = resnet_block(x, filters=256)
x = resnet_block(x, filters=256) # Additional block compared to ResNet-18
x = resnet_block(x, filters=512, stride=2)
x = resnet_block(x, filters=512)
x = resnet_block(x, filters=512)
x = GlobalAveragePooling2D()(x)
output_layer = Dense(num_classes, activation='softmax')(x)
resnet34_model.summary()
Model: "model_3"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_4 (InputLayer) [(None, 32, 32, 3)] 0
21
batch_normalization_53 (Bat (None, 8, 8, 64) 256
chNormalization)
22
conv2d_62 (Conv2D) (None, 4, 4, 128) 147584
23
conv2d_69 (Conv2D) (None, 2, 2, 256) 590080
24
activation_73 (Activation) (None, 2, 2, 256) 0
25
activation_80 (Activation) (None, 1, 1, 512) 0
=================================================================
Total params: 21,138,826
Trainable params: 21,123,594
Non-trainable params: 15,232
_________________________________________________________________
training_history = resnet34_model.fit(
x_train_normalized,
y_train_encoded,
epochs= 3,
validation_data=(x_test_normalized, y_test_encoded)
)
Epoch 1/3
26
1563/1563 [==============================] - 118s 35ms/step - loss: 2.0182 -
accuracy: 0.2217 - val_loss: 2.2848 - val_accuracy: 0.1103
Epoch 2/3
1563/1563 [==============================] - 55s 35ms/step - loss: 1.8123 -
accuracy: 0.3067 - val_loss: 2.9065 - val_accuracy: 0.2077
Epoch 3/3
1563/1563 [==============================] - 56s 36ms/step - loss: 1.6814 -
accuracy: 0.3672 - val_loss: 1.9971 - val_accuracy: 0.3290
27
plt.legend()
28
accuracy: 0.3290
Validation loss: 1.997099757194519
Validation accuracy: 0.32899999618530273
[ ]:
29