<jupyter_start><jupyter_text>Facial emotion recognition- This is an ipynb file created in Kaggle environment.- CNN Dataset- MMA FACIAL EXPRESSION, https://www.kaggle.com/mahmoudima/mma-facial-expression  0. Import Packages<jupyter_code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import tensorflow as tf
from tensorflow.keras.applications import Xception
from tensorflow.keras.applications.xception import preprocess_input
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Conv2D, Dense, BatchNormalization, Activation, Dropout, MaxPooling2D, Flatten
from tensorflow.keras import Model, regularizers
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from tensorflow.keras.models import load_model
import os<jupyter_output><empty_output><jupyter_text>1. Make dataset<jupyter_code>batch_size = 128
img_height = 64
img_width = 64
preprocessed_training = []
preprocessed_validation = []
train_datagen = ImageDataGenerator(
        preprocessing_function = preprocess_input,  ### change
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)
validation_datagen = ImageDataGenerator(rescale=1./255, preprocessing_function=preprocess_input)    
test_datagen = ImageDataGenerator(rescale=1./255, preprocessing_function=preprocess_input)
train_generator = train_datagen.flow_from_directory("/kaggle/input/mma-facial-expression/MMAFEDB/train",
                                                      target_size=(img_width, img_height),
                                                      batch_size=batch_size,
                                                      class_mode='categorical')
validation_generator = validation_datagen.flow_from_directory("/kaggle/input/mma-facial-expression/MMAFEDB/valid",
                                                      target_size=(img_width, img_height),
                                                      batch_size=batch_size,
                                                      class_mode='categorical')
test_generator = test_datagen.flow_from_directory("/kaggle/input/mma-facial-expression/MMAFEDB/test",
                                                      target_size=(img_width, img_height),
                                                      batch_size=batch_size,
                                                      class_mode='categorical')<jupyter_output>Found 92968 images belonging to 7 classes.
Found 17356 images belonging to 7 classes.
Found 17356 images belonging to 7 classes.<jupyter_text>2. Model (CNN)<jupyter_code># params
classes = 7
nb_epoch = 50
num_train = 92968
num_val = 17356
model = tf.keras.models.Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu', input_shape = (img_width, img_height,3)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'))
model.add(BatchNormalization())
model.add(MaxPooling2D(2, 2))
model.add(Dropout(0.25))

model.add(Conv2D(128, kernel_size=(3, 3), activation='relu', padding='same', kernel_regularizer=regularizers.l2(0.01)))
model.add(Conv2D(256, kernel_size=(3, 3), activation='relu', kernel_regularizer=regularizers.l2(0.01)))
model.add(BatchNormalization())
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(classes, activation='softmax'))

model.summary()
model.compile(optimizer='sgd',
              loss='categorical_crossentropy',
              metrics=['accuracy'])<jupyter_output><empty_output><jupyter_text>3. Training<jupyter_code>hist = model.fit(
    train_generator,
    epochs = nb_epoch,
    steps_per_epoch = num_train//batch_size,
    validation_data = validation_generator,
    validation_steps = num_val//batch_size)
# Save model
model.save("/kaggle/working/my_model.h5")
# model.save_weigths("/kaggle/working/xception_weights.h5")

my_model_json = model.to_json()

with open("/kaggle/working/my_model.json", "w") as json_file:
    json_file.write(my_model_json)
model = load_model('/kaggle/working/my_model.h5')
plt.plot(hist.history['accuracy'][3:50])
plt.plot(hist.history['val_accuracy'][3:50])
plt.title('model accuracy')
plt.ylabel('acc')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()<jupyter_output><empty_output><jupyter_text>4. Evaluation<jupyter_code>print("-- Evaluate --")
scores = model.evaluate(test_generator, steps=num_val//batch_size)
print("%s: %.2f%%" %(model.metrics_names[1], scores[1]*100))
print("-- Predict --")
pred = model.predict(test_generator, steps=num_val//batch_size)
np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)})
print(test_generator.class_indices)
print(pred)
prediction = np.argmax(pred, axis=1)
test_generator.class_indices
img, label = test_generator.next()
print(np.shape(img), np.shape(label))<jupyter_output>(128, 64, 64, 3) (128, 7)
{'fraction_non_alphanumeric': 0.12171646280328854, 'fraction_numerical': 0.02827351112893523, 'mean_word_length': 3.796153846153846, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '589280', 'license': 'MIT', 'n_tokens_mistral': 1645, 'n_tokens_neox': 1554, 'n_words': 261, 'path': 'FER_using_CNN.ipynb', 'repo_name': 'OH-Seoyoung/Facial_Emotion_Recognition', 'size': '4987'}