-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclassifier.py
155 lines (104 loc) · 3.76 KB
/
classifier.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
"""
## Import Libraries
"""
# Common imports
import os
import numpy as np
# Visualization
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
"""
"""
# TensorFlow imports
# may differs from version to versions
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.preprocessing import image
"""
## Splitting images
"""
# import splitfolders # or import split_folders
# Split dengan ratio.
# Untuk hanya membagi menjadi set pelatihan dan validasi, setel tuple menjadi `ratio`, i.e, `(.8, .2)`.
# splitfolders.ratio("dataset", output="face_dataset_test_images", seed=1337, ratio=(.8,.2), group_prefix=None)
# Dataset information
# Test dataset is set explicitly, because the amount of data is very small
train_image_folder = os.path.join('datasets', 'face_dataset_train_aug_images')
test_image_folder = os.path.join('datasets', 'face_dataset_test_images')
img_height, img_width = 250, 250 # size of images
num_classes = 3
# Training settings
validation_ratio = 0.15 # 15% for the validation
batch_size = 16
AUTOTUNE = tf.data.AUTOTUNE
# Train and validation sets
train_ds = keras.preprocessing.image_dataset_from_directory(
train_image_folder,
validation_split=validation_ratio,
subset="training",
seed=42,
image_size=(img_height, img_width),
label_mode='categorical',
batch_size=batch_size,
shuffle=True)
val_ds = keras.preprocessing.image_dataset_from_directory(
train_image_folder,
validation_split=validation_ratio,
subset="validation",
seed=42,
image_size=(img_height, img_width),
batch_size=batch_size,
label_mode='categorical',
shuffle=True)
# Test set
test_ds = keras.preprocessing.image_dataset_from_directory(
test_image_folder,
image_size=(img_height, img_width),
label_mode='categorical',
shuffle=False)
class_names = test_ds.class_names
class_names
"""
## Modelling with ResNet50
"""
base_model = keras.applications.ResNet50(weights='imagenet',
include_top=False, # without dense part of the network
input_shape=(img_height, img_width, 3))
# Set layers to non-trainable
for layer in base_model.layers:
layer.trainable = False
# Add custom layers on top of ResNet
global_avg_pooling = keras.layers.GlobalAveragePooling2D()(base_model.output)
output = keras.layers.Dense(num_classes, activation='sigmoid')(global_avg_pooling)
face_classifier = keras.models.Model(inputs=base_model.input,
outputs=output,
name='ResNet50')
face_classifier.summary()
# ModelCheckpoint to save model in case of interrupting the learning process
checkpoint = ModelCheckpoint("models/face_classifier.h5",
monitor="val_loss",
mode="min",
save_best_only=True,
verbose=1)
# EarlyStopping to find best model with a large number of epochs
earlystop = EarlyStopping(monitor='val_loss',
restore_best_weights=True,
patience=3, # number of epochs with no improvement after which training will be stopped
verbose=1)
callbacks = [earlystop, checkpoint]
face_classifier.compile(loss='categorical_crossentropy',
optimizer=keras.optimizers.Adam(learning_rate=0.01),
metrics=['accuracy'])
"""
## Training
"""
epochs = 5
history = face_classifier.fit(
train_ds,
epochs=epochs,
callbacks=callbacks,
validation_data=val_ds)
face_classifier.save("models/face_classifier.h5")