a-1
a-1
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
import imghdr
import tensorflow as tf
from PIL import Image
import seaborn as sns
# Path to the directory containing image classes and possibly other nested
subdirectories
data_dir = 'archive\train'
try:
# Check the file type of the current file
file_type = imghdr.what(file_path)
except Exception as e:
# Print out the issue and the path of the problematic file
print(f'Issue with file {file_path}. Error: {e}')
# Optionally, remove files that cause exceptions
os.remove(file_path)
if os.path.isdir(item_path):
counts[item] = len(os.listdir(item_path))
df = pd.DataFrame(counts, index=[set_name])
return df
train_dir = 'archive/train'
test_dir = 'archive/test'
train_count.transpose()
train_count.transpose().plot(kind='bar')
test_count.transpose().plot(kind='bar')
emotions = os.listdir(train_dir)
plt.figure(figsize=(15,10))
# If there are fewer images than requested, we'll just show them all
if len(image_filenames) < num_images:
print(f"Only found {len(image_filenames)} images in {directory_path},
displaying them all.")
num_images = len(image_filenames)
plt.tight_layout()
plt.show()
# Placeholder for the directory path
angry_directory_path = 'archive/train/angry' # Replace with your directory path
plot_images_from_directory(angry_directory_path, class_name = 'Angry')
image = 'archive/train/angry/Training_10118481.jpg'
import cv2
image_path = 'archive/train/angry/Training_10118481.jpg'
test_preprocessor = ImageDataGenerator(
rescale = 1 / 255.,
)
# Automatically retrieve images and their classes for train and validation sets
train_generator = data_generator.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical',
color_mode='rgb',
subset='training',
shuffle = True)
test_generator = test_preprocessor.flow_from_directory(
test_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical',
color_mode='rgb',)
# subset='validation')
# Accessing class labels for the training data
train_class_labels = train_generator.class_indices
print("Training class labels:", train_class_labels)
# Load the VGG16 base model, excluding its top (fully connected) layers
vgg = VGG16(input_shape=(224, 224, 3), include_top=False, weights='imagenet')
vgg.summary()
# Make the specified layers non-trainable
for layer in vgg.layers[:-3]:
layer.trainable = False
vgg.summary()
classes
# Flattening the layer and adding custom Dense layers
x = Flatten()(vgg.output)
# Adding a fully connected layer with ReLU activation and He normal initializer
x = Dense(1024, activation='relu', kernel_initializer='he_normal')(x)
x = Dropout(0.5)(x) # Adding dropout for regularization
model.save('model_vgg1.keras', save_format='keras')
model = tf.keras.models.load_model('model_vgg1.keras')
test_preprocessor = ImageDataGenerator(
rescale = 1 / 255.,
)
# Automatically retrieve images and their classes for train and validation sets
train_generator = data_generator.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical',
color_mode='rgb',
subset='training',
shuffle = True)
test_generator = test_preprocessor.flow_from_directory(
test_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical',
color_mode='rgb',)
# subset='validation')
# Extract class labels for all instances in the training dataset
classes = np.array(train_generator.classes)
ResNet50V2.trainable = True
model = Sequential([
ResNet50V2,
Dropout(0.25),
BatchNormalization(),
Flatten(),
Dense(64, activation='relu'),
BatchNormalization(),
Dropout(0.5),
Dense(7,activation='softmax')
])
return model
model = Create_ResNet50V2_Model()
model.summary()
model.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
# File path for the model checkpoint
cnn_path = 'Emotion_Detection/ResNet50_Transfer_Learning'
name = 'ResNet50_Transfer_Learning.keras'
chk_path = os.path.join(cnn_path, name)
model = tf.keras.models.load_model('ResNet50_Transfer_Learning.keras')
true_classes = test_generator.classes
predicted_classes = np.argmax(model.predict(test_generator,
steps=np.ceil(test_generator.samples/test_generator.batch_size)), axis=1)
class_labels = list(test_generator.class_indices.keys())