Skip to main content

2-C .Understanding and Using ANN : Identifying age group of an actor

 AIM:  Design Artificial Neural Networks for Identifying and Classifying an actor using Kaggle Dataset.

Link to download Model file:

https://drive.google.com/file/d/12lsyOHe5QifEaiW_d9K8BLLy5PeCEWsf/view?usp=sharing


Link to Images to test:

https://drive.google.com/drive/folders/1xhQJSzL_OL72YXBgdQD10_JmYpHPngLu?usp=sharing


Program to predict Face Image's Age group:

from tensorflow.keras.models import load_model
from PIL import Image
import numpy as np


# Define the input image dimensions
image_height = 128
image_width = 128
num_channels = 3

# Load the trained model
model = load_model('/content/drive/MyDrive/trained_model_C_Dataset.h5') # Replace 'your_trained_model.h5' with the actual file name

# Read the new face image
new_face_path = '/content/drive/MyDrive/2_Predict/old.jpeg'  # Replace 'path_to_new_face.jpg' with the actual file path
new_face = Image.open(new_face_path)
display(new_face)
# Preprocess the image
new_face = new_face.resize((image_width, image_height))
#new_face.show()
print('path ',new_face_path )
new_face = np.array(new_face)
#new_face = new_face.astype('float32') / 255.0
new_face = np.expand_dims(new_face, axis=0)  # Add a batch dimension

# Perform prediction
predictions = model.predict(new_face)
predicted_age_group = np.argmax(predictions)
print("predictions are ",predictions)
print("Predicted Age Group:", predicted_age_group)

# Map the predicted age group index to the actual label
age_mapping = {0: 'YOUNG', 1: 'MIDDLE', 2: 'OLD'}  # Update with your age group labels mapping
predicted_age_group_label = age_mapping[predicted_age_group]

print("Predicted Age Group:", predicted_age_group_label)

O/p:

WARNING:absl:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until you train or evaluate the model.
path  /content/drive/MyDrive/2_Predict/a.jpg
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 152ms/step
predictions are  [[0.43104544 0.16487518 0.40407938]]
Predicted Age Group: 0
Predicted Age Group: YOUNG


Program to build Model:


#@title
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from keras.utils import to_categorical
from PIL import Image
from sklearn.preprocessing import LabelEncoder

# Load the dataset
dataset = pd.read_csv('/content/drive/MyDrive/2_2_Dataset/train.csv')  # Replace 'kaggle_dataset.csv' with the actual dataset file

# Preprocess the dataset
# Assuming the dataset has 'image_path' column for image file paths and 'age_group' column for age group labels


# Define the input image dimensions
image_height = 128
image_width = 128
num_channels = 3

# Load and preprocess images
X = []
for image_path in '/content/drive/MyDrive/2_2_Dataset/'+dataset['ID']:
    print(image_path)
    img = Image.open(image_path)
    #img.show()
    img = img.resize((image_width, image_height))
    img = np.array(img)
    X.append(img)

# Split dataset into images and labels
X = np.array(X)

y = np.array(dataset['Class'])

# Encode labels to integers
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(y)

# Split into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Define the number of classes
num_classes = len(label_encoder.classes_)


# Convert labels to one-hot encoding
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)

# Define the input image dimensions
image_height = 128
image_width = 128
num_channels = 3

# Define the model architecture
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(image_height, image_width, num_channels)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))

# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# Data augmentation
datagen = ImageDataGenerator(rotation_range=20, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)

# Train the model
batch_size = 32
epochs = 20
steps_per_epoch = len(X_train) // batch_size
model.fit(datagen.flow(X_train, y_train, batch_size=batch_size), steps_per_epoch=steps_per_epoch, epochs=epochs)

# Evaluate the model
accuracy = model.evaluate(X_test, y_test)[1]
print("Accuracy:", accuracy)


# Save the trained model
model.save('/content/drive/MyDrive/trained_model_C_Dataset.h5')

O/p:

Streaming output truncated to the last 5000 lines. /content/drive/MyDrive/2_2_Dataset/11430.jpg /content/drive/MyDrive/2_2_Dataset/14976.jpg /content/drive/MyDrive/2_2_Dataset/8698.jpg /content/drive/MyDrive/2_2_Dataset/7492.jpg /content/drive/MyDrive/2_2_Dataset/6134.jpg /content/drive/MyDrive/2_2_Dataset/13508.jpg
---
---
---
---
---
/usr/local/lib/python3.11/dist-packages/keras/src/layers/convolutional/base_conv.py:107: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead.
  super().__init__(activity_regularizer=activity_regularizer, **kwargs)
/usr/local/lib/python3.11/dist-packages/keras/src/trainers/data_adapters/py_dataset_adapter.py:121: UserWarning: Your `PyDataset` class should call `super().__init__(**kwargs)` in its constructor. `**kwargs` can include `workers`, `use_multiprocessing`, `max_queue_size`. Do not pass these arguments to `fit()`, as they will be ignored.
  self._warn_if_super_not_called()
Epoch 1/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 68s 128ms/step - accuracy: 0.5384 - loss: 47.1915
Epoch 2/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 0s 39us/step - accuracy: 0.5000 - loss: 0.9528   
Epoch 3/20
/usr/local/lib/python3.11/dist-packages/keras/src/trainers/epoch_iterator.py:107: UserWarning: Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches. You may need to use the `.repeat()` function when building your dataset.
  self._interrupted_warning()
497/497 ━━━━━━━━━━━━━━━━━━━━ 79s 129ms/step - accuracy: 0.5732 - loss: 0.9334
Epoch 4/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 0s 27us/step - accuracy: 0.6250 - loss: 0.8409   
Epoch 5/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 64s 128ms/step - accuracy: 0.5641 - loss: 0.9466
Epoch 6/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 0s 26us/step - accuracy: 0.7500 - loss: 0.7550   
Epoch 7/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 82s 128ms/step - accuracy: 0.5776 - loss: 0.9314
Epoch 8/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 0s 47us/step - accuracy: 0.7188 - loss: 0.7428   
Epoch 9/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 81s 128ms/step - accuracy: 0.5702 - loss: 0.9321
Epoch 10/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 0s 25us/step - accuracy: 0.6250 - loss: 0.9372  
Epoch 11/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 63s 128ms/step - accuracy: 0.5738 - loss: 0.9334
Epoch 12/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 0s 35us/step - accuracy: 0.6250 - loss: 0.8514   
Epoch 13/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 83s 129ms/step - accuracy: 0.5807 - loss: 0.9264
Epoch 14/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 0s 28us/step - accuracy: 0.5312 - loss: 0.8849 
Epoch 15/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 82s 129ms/step - accuracy: 0.5750 - loss: 0.9312
Epoch 16/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 0s 24us/step - accuracy: 0.5938 - loss: 0.8832  
Epoch 17/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 80s 126ms/step - accuracy: 0.5702 - loss: 0.9422
Epoch 18/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 0s 26us/step - accuracy: 0.7188 - loss: 0.7283  
Epoch 19/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 65s 131ms/step - accuracy: 0.5709 - loss: 0.9336
Epoch 20/20
497/497 ━━━━━━━━━━━━━━━━━━━━ 0s 25us/step - accuracy: 0.4688 - loss: 1.0196  
125/125 ━━━━━━━━━━━━━━━━━━━━ 2s 9ms/step - accuracy: 0.5840 - loss: 0.9143
WARNING:absl:You are saving your model as an HDF5 file via `model.save()` or `keras.saving.save_model(model)`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')` or `keras.saving.save_model(model, 'my_model.keras')`. 
Accuracy: 0.5858864784240723




Comments

Popular posts from this blog

11. List of Capstone Projects for SOC - Deep Learning

8. Advanced CNN (Build AlexNet using Advanced CNN)