0% found this document useful (0 votes)
3 views

import numpy as np

The document outlines a Python script for building and training a Convolutional Neural Network (CNN) to classify emotions from the FER2013 dataset. It includes steps for data preprocessing, model architecture definition, training with image augmentation, and evaluation of the model's performance. Additionally, it provides functionality for uploading an image to predict the emotion displayed in it.

Uploaded by

ngocthanh040204
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

import numpy as np

The document outlines a Python script for building and training a Convolutional Neural Network (CNN) to classify emotions from the FER2013 dataset. It includes steps for data preprocessing, model architecture definition, training with image augmentation, and evaluation of the model's performance. Additionally, it provides functionality for uploading an image to predict the emotion displayed in it.

Uploaded by

ngocthanh040204
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

import numpy as np

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout,
BatchNormalization
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping
from sklearn.model_selection import train_test_split
import cv2
import os
from google.colab import files

# Tải dataset FER2013


!pip install kaggle
files.upload()
!mkdir ~/.kaggle
!mv kaggle.json ~/.kaggle/
!chmod 600 ~/.kaggle/kaggle.json
!kaggle datasets download -d msambare/fer2013
!unzip fer2013.zip -d fer2013
df = pd.read_csv("fer2013.csv")

def process_fer_data(df):
images, labels = [], []
for _, row in df.iterrows():
pixels = np.array(row['pixels'].split(), dtype=np.uint8).reshape(48, 48, 1)
images.append(pixels)
labels.append(row['emotion'])
return np.array(images) / 255.0, np.array(labels)

X, y = process_fer_data(df)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
y_train = keras.utils.to_categorical(y_train, num_classes=7)
y_test = keras.utils.to_categorical(y_test, num_classes=7)

print(f"Dữ liệu đã xử lý xong! Train: {X_train.shape[0]}, Test: {X_test.shape[0]}")

# Xây dựng mô hình CNN


model = Sequential([
Conv2D(32, (3,3), activation='relu', input_shape=(48,48,1)),
BatchNormalization(),
MaxPooling2D(pool_size=(2,2)),

Conv2D(64, (3,3), activation='relu'),


BatchNormalization(),
MaxPooling2D(pool_size=(2,2)),

Conv2D(128, (3,3), activation='relu'),


BatchNormalization(),
MaxPooling2D(pool_size=(2,2)),

Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(64, activation='relu'),
Dropout(0.5),
Dense(7, activation='softmax')
])

# Compile model
model.compile(optimizer=Adam(learning_rate=0.001), loss='categorical_crossentropy',
metrics=['accuracy'])
model.summary()

# Image augmentation
datagen = ImageDataGenerator(
rotation_range=10,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True
)

# Callbacks
lr_scheduler = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5,
verbose=1)
early_stopping = EarlyStopping(monitor='val_loss', patience=10,
restore_best_weights=True)

# Train model
batch_size = 64
epochs = 100
history = model.fit(datagen.flow(X_train, y_train, batch_size=batch_size),
validation_data=(X_test, y_test),
epochs=epochs,
callbacks=[lr_scheduler, early_stopping],
verbose=1)

# Evaluate model
loss, acc = model.evaluate(X_test, y_test, verbose=0)
print(f"Accuracy on test set: {acc*100:.2f}%")

# Plot results
plt.figure(figsize=(12, 5))
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.title('Accuracy Over Epochs')

plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('Loss Over Epochs')
plt.show()

def upload_and_predict():
uploaded = files.upload()
for filename in uploaded.keys():
img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (48, 48))
img = np.expand_dims(img, axis=[0, -1]) / 255.0
prediction = model.predict(img)
emotion_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise',
'Neutral']
predicted_emotion = emotion_labels[np.argmax(prediction)]
plt.imshow(img.squeeze(), cmap='gray')
plt.title(f"Predicted: {predicted_emotion}")
plt.axis('off')
plt.show()

# Gọi hàm dự đoán


upload_and_predict()

You might also like