Commit 4bf1d2e1 authored by Hasini Piumika Alwis's avatar Hasini Piumika Alwis

model_training.py file

parent 48bad758
import cv2
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Initialize image data generator with rescaling
train = ImageDataGenerator(rescale=1. / 255)
validation = ImageDataGenerator(rescale=1. / 255)
# Preprocess all test images
trainGen = train.flow_from_directory(
'data/train',
target_size=(48, 48),
batch_size=64,
color_mode="grayscale",
class_mode='categorical')
# Preprocess all train images
valGen = validation.flow_from_directory(
'data/test',
target_size=(48, 48),
batch_size=64,
color_mode="grayscale",
class_mode='categorical')
# create model structure
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48, 48, 1)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(7, activation='softmax'))
cv2.ocl.setUseOpenCL(False)
model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.0001, decay=1e-6), metrics=['accuracy'])
# Train the neural network/model
model_info = model.fit_generator(
trainGen,
steps_per_epoch=28709 // 64,
epochs=5,
validation_data=valGen,
validation_steps=7178 // 64)
# save model structure in jason file
model_json = model.to_json()
with open("emotion_model.json", "w") as json_file:
json_file.write(model_json)
# save trained model weight in .h5 file
model.save_weights('emotion_model.h5')
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment