-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_traning.py
More file actions
66 lines (54 loc) · 2.47 KB
/
Copy pathmodel_traning.py
File metadata and controls
66 lines (54 loc) · 2.47 KB
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
import pandas as pd
import numpy as np
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Flatten, Dense, Dropout, GlobalAveragePooling2D
from keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import ModelCheckpoint
train_dir = "/media/asmany/Drive_D/liveness/dataset/train"
valid_dir = "/media/asmany/Drive_D/liveness/dataset/test"
img_width, img_height = 224, 224 # Default input size for VGG16
conv_base = tf.keras.applications.VGG16(weights='imagenet',
include_top=False,
input_shape=(img_width, img_height, 3))
# Show architecture
#conv_base.summary()
datagen = ImageDataGenerator(rescale=1./255)
batch_size = 32
def extract_features(directory, sample_count):
features = np.zeros(shape=(sample_count, 7, 7, 512)) # Must be equal to the output of the convolutional base
labels = np.zeros(shape=(sample_count,2))
# Preprocess data
generator = datagen.flow_from_directory(directory,
target_size=(img_width,img_height),
batch_size = batch_size,
class_mode='categorical')
# Pass data through convolutional base
i = 0
for inputs_batch, labels_batch in generator:
features_batch = conv_base.predict(inputs_batch)
features[i * batch_size: (i + 1) * batch_size] = features_batch
labels[i * batch_size: (i + 1) * batch_size] = labels_batch
i += 1
if i * batch_size >= sample_count:
break
return features, labels
train_features, train_labels = extract_features(train_dir, 8895)
validation_features, validation_labels = extract_features(valid_dir, 3719)
epochs = 150
model = Sequential()
model.add(GlobalAveragePooling2D(input_shape=(7,7,512)))
model.add(Dense(2, activation='softmax'))
model.summary()
checkpoint = ModelCheckpoint('model-{epoch:03d}-{acc:03f}-{val_acc:03f}.h5', verbose=1, monitor='val_loss',save_best_only=True, mode='auto')
# Compile model
from tensorflow.keras.optimizers import Adam
model.compile(optimizer=Adam(),
loss='categorical_crossentropy',
metrics=['acc'])
# Train model
history = model.fit(train_features, train_labels,
epochs=epochs,
batch_size=batch_size,
callbacks=[checkpoint],
validation_data=(validation_features, validation_labels))