-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmooddetection.py
116 lines (88 loc) · 3.42 KB
/
mooddetection.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
# -*- coding: utf-8 -*-
"""MoodDetection.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1OcR_u9n7rcWFKhNn569o2xyg7fngDIwv
# MOOD DETECTION
"""
#import libraries
import tensorflow as tf
from tensorflow.keras.preprocessing.image import img_to_array, array_to_img
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
#import dataset's zip file
zip_file_path = '/content/drive/MyDrive/Kaggle/fer2013.zip'
extracted_dir = '/content/fer2013/'
os.makedirs(extracted_dir, exist_ok=True)
#extract zip file
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
zip_ref.extractall(extracted_dir)
extracted_files = os.listdir(extracted_dir)
print(extracted_files)
TRAIN_DIR = "/content/fer2013/train"
TEST_DIR = "/content/fer2013/test"
BATCH_SIZE=64
# Function to load and preprocess the dataset
def load_and_preprocess_data(directory):
images = []
labels = [] #store preprocessed images and corresponding labels.
label_encoder = LabelEncoder()
for i, emotion_folder in enumerate(os.listdir(directory)):
emotion_path = os.path.join(directory, emotion_folder)
for filename in os.listdir(emotion_path):
img_path = os.path.join(emotion_path, filename)
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (48, 48))
img = img / 255.0 # normalize to [0,1]
images.append(img)
labels.append(i) # Use the numerical label from label_encoder
return np.array(images), np.array(labels)
# Load and preprocess training and testing data
X_train, y_train = load_and_preprocess_data(TRAIN_DIR)
X_test, y_test = load_and_preprocess_data(TEST_DIR)
#Reshape and normalize the data(/255.0)
X_train = X_train.reshape(-1, 48, 48, 1)
X_test = X_test.reshape(-1, 48, 48, 1)
#Convert labels to one-hot encoding (represent categorical labels as binary vectors)
y_train = to_categorical(y_train, num_classes=7) # 7 classes for emotions
y_test = to_categorical(y_test, num_classes=7)
plt.imshow(X_train[0].reshape(48, 48), cmap='gray')
plt.title(f'Class: {np.argmax(y_train[0])}')
plt.show()
model = keras.Sequential([
keras.layers.Dense(100, input_shape=(48, 48, 1), activation='relu'),
keras.layers.Flatten(),
keras.layers.Dense(7, activation='softmax') # Change the number of units to 7
])
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy', # Use categorical crossentropy
metrics=['accuracy'])
#checking no of samples
print(X_train.shape)
print(y_train.shape)
# Train the model
model.fit(X_train, y_train, epochs=5)
# Evaluate the model on the test set
model.evaluate(X_test, y_test)
# Make predictions on the test set
y_predicted = model.predict(X_test)
y_predicted_labels = [np.argmax(i) for i in y_predicted]
plt.imshow(X_test[1].reshape(48, 48), cmap='gray')
plt.title(f'Predicted Label: {y_predicted_labels[1]}')
plt.show()
y_test_labels = np.argmax(y_test, axis=1)
if len(y_test_labels) == len(y_predicted_labels):
cm = tf.math.confusion_matrix(labels=y_test_labels, predictions=y_predicted_labels)
cm
import seaborn as sn
plt.figure(figsize=(10, 7))
sn.heatmap(cm, annot=True, fmt='d')
plt.xlabel('Predicted')
plt.ylabel('Truth')
plt.show()