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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Created on Thu Feb 29 15:05:30 2024
|
| 4 |
+
|
| 5 |
+
@author: Dhrumit Patel
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
Dataset: UTKFace
|
| 10 |
+
https://www.kaggle.com/datasets/jangedoo/utkface-new?resource=download
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import pandas as pd
|
| 14 |
+
import numpy as np
|
| 15 |
+
import tensorflow as tf
|
| 16 |
+
import os
|
| 17 |
+
import matplotlib.pyplot as plt
|
| 18 |
+
import cv2
|
| 19 |
+
from keras.models import Sequential, Model, load_model
|
| 20 |
+
from keras.layers import Conv2D, MaxPool2D, Dense, Dropout, BatchNormalization, Flatten, Input
|
| 21 |
+
from sklearn.model_selection import train_test_split
|
| 22 |
+
|
| 23 |
+
path = 'data/UTKFace'
|
| 24 |
+
|
| 25 |
+
images = []
|
| 26 |
+
age = []
|
| 27 |
+
gender = []
|
| 28 |
+
|
| 29 |
+
for img in os.listdir(path):
|
| 30 |
+
ages = img.split("_")[0]
|
| 31 |
+
genders = img.split("_")[1]
|
| 32 |
+
img = cv2.imread(str(path) + "/" + str(img))
|
| 33 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 34 |
+
images.append(np.array(img))
|
| 35 |
+
age.append(np.array(ages))
|
| 36 |
+
gender.append(np.array(genders))
|
| 37 |
+
|
| 38 |
+
images = np.array(images)
|
| 39 |
+
|
| 40 |
+
images = images / 255.0
|
| 41 |
+
age = np.array(age, dtype=np.int64)
|
| 42 |
+
gender = np.array(gender, dtype=np.int64)
|
| 43 |
+
|
| 44 |
+
# np.save('preprocessed_data/images.npy', images)
|
| 45 |
+
# np.save('preprocessed_data/age.npy', age)
|
| 46 |
+
# np.save('preprocessed_data/gender.npy', gender)
|
| 47 |
+
|
| 48 |
+
# images = np.load('preprocessed_data/images.npy')
|
| 49 |
+
# age = np.load('preprocessed_data/age.npy')
|
| 50 |
+
# gender = np.load('preprocessed_data/gender.npy')
|
| 51 |
+
|
| 52 |
+
X_train_age, X_test_age, y_train_age, y_test_age = train_test_split(images, age, random_state=42)
|
| 53 |
+
X_train_gender, X_test_gender, y_train_gender, y_test_gender = train_test_split(images, gender, random_state=42)
|
| 54 |
+
|
| 55 |
+
# Define the model - For Age
|
| 56 |
+
age_model = Sequential()
|
| 57 |
+
age_model.add(Conv2D(128, kernel_size=3, activation='relu', input_shape=(200,200,3)))
|
| 58 |
+
age_model.add(MaxPool2D(pool_size=3, strides=2))
|
| 59 |
+
|
| 60 |
+
age_model.add(Conv2D(128, kernel_size=3, activation='relu'))
|
| 61 |
+
age_model.add(MaxPool2D(pool_size=3, strides=2))
|
| 62 |
+
|
| 63 |
+
age_model.add(Conv2D(256, kernel_size=3, activation='relu'))
|
| 64 |
+
age_model.add(MaxPool2D(pool_size=3, strides=2))
|
| 65 |
+
|
| 66 |
+
age_model.add(Conv2D(512, kernel_size=3, activation='relu'))
|
| 67 |
+
age_model.add(MaxPool2D(pool_size=3, strides=2))
|
| 68 |
+
|
| 69 |
+
age_model.add(Flatten())
|
| 70 |
+
age_model.add(Dropout(0.2))
|
| 71 |
+
age_model.add(Dense(512, activation='relu'))
|
| 72 |
+
|
| 73 |
+
age_model.add(Dense(1, activation='linear', name='age'))
|
| 74 |
+
|
| 75 |
+
age_model.compile(optimizer='adam', loss='mse', metrics=['mae'])
|
| 76 |
+
|
| 77 |
+
age_model.summary()
|
| 78 |
+
|
| 79 |
+
# TODO: Fit for 10 epochs
|
| 80 |
+
with tf.device('/CPU:0'):
|
| 81 |
+
history_age = age_model.fit(X_train_age, y_train_age,
|
| 82 |
+
epochs=10,
|
| 83 |
+
validation_data=(X_test_age, y_test_age))
|
| 84 |
+
|
| 85 |
+
age_model.save('models/age_model_10epochs.h5')
|
| 86 |
+
|
| 87 |
+
# Define the model - For Gender
|
| 88 |
+
gender_model = Sequential()
|
| 89 |
+
|
| 90 |
+
gender_model.add(Conv2D(36, kernel_size=3, activation='relu', input_shape=(200,200,3)))
|
| 91 |
+
|
| 92 |
+
gender_model.add(MaxPool2D(pool_size=3, strides=2))
|
| 93 |
+
gender_model.add(Conv2D(64, kernel_size=3, activation='relu'))
|
| 94 |
+
gender_model.add(MaxPool2D(pool_size=3, strides=2))
|
| 95 |
+
|
| 96 |
+
gender_model.add(Conv2D(128, kernel_size=3, activation='relu'))
|
| 97 |
+
gender_model.add(MaxPool2D(pool_size=3, strides=2))
|
| 98 |
+
|
| 99 |
+
gender_model.add(Conv2D(256, kernel_size=3, activation='relu'))
|
| 100 |
+
gender_model.add(MaxPool2D(pool_size=3, strides=2))
|
| 101 |
+
|
| 102 |
+
gender_model.add(Conv2D(512, kernel_size=3, activation='relu'))
|
| 103 |
+
gender_model.add(MaxPool2D(pool_size=3, strides=2))
|
| 104 |
+
|
| 105 |
+
gender_model.add(Flatten())
|
| 106 |
+
gender_model.add(Dropout(0.2))
|
| 107 |
+
gender_model.add(Dense(512, activation='relu'))
|
| 108 |
+
gender_model.add(Dense(1, activation='sigmoid', name='gender'))
|
| 109 |
+
|
| 110 |
+
gender_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
|
| 111 |
+
|
| 112 |
+
gender_model.summary()
|
| 113 |
+
|
| 114 |
+
# TODO: Fit for 10 epochs
|
| 115 |
+
with tf.device('/CPU:0'):
|
| 116 |
+
history_gender = gender_model.fit(X_train_gender, y_train_gender,
|
| 117 |
+
epochs=10,
|
| 118 |
+
validation_data=(X_test_gender, y_test_gender))
|
| 119 |
+
|
| 120 |
+
gender_model.save('models/gender_model_10epochs.h5')
|
| 121 |
+
|
| 122 |
+
# Plot the training and validation accuracy and loss at each epoch - For Age model
|
| 123 |
+
loss = history_age.history['loss']
|
| 124 |
+
val_loss = history_age.history['val_loss']
|
| 125 |
+
epochs = range(1, len(loss) + 1)
|
| 126 |
+
plt.plot(epochs, loss, 'y', label='Training loss')
|
| 127 |
+
plt.plot(epochs, val_loss, 'r', label='Validation loss')
|
| 128 |
+
plt.title('Training and validation loss for Age model')
|
| 129 |
+
plt.xlabel('Epochs')
|
| 130 |
+
plt.ylabel('Loss')
|
| 131 |
+
plt.legend()
|
| 132 |
+
plt.show()
|
| 133 |
+
|
| 134 |
+
acc = history_age.history['accuracy']
|
| 135 |
+
val_acc = history_age.history['val_accuracy']
|
| 136 |
+
plt.plot(epochs, acc, 'y', label='Training Accuracy')
|
| 137 |
+
plt.plot(epochs, val_acc, 'r', label='Validation Accuracy')
|
| 138 |
+
plt.title('Training and validation accuracy for Age model')
|
| 139 |
+
plt.xlabel('Epochs')
|
| 140 |
+
plt.ylabel('Accuracy')
|
| 141 |
+
plt.legend()
|
| 142 |
+
plt.show()
|
| 143 |
+
|
| 144 |
+
# Plot the training and validation accuracy and loss at each epoch - For Gender model
|
| 145 |
+
loss = history_gender.history['loss']
|
| 146 |
+
val_loss = history_gender.history['val_loss']
|
| 147 |
+
epochs = range(1, len(loss) + 1)
|
| 148 |
+
plt.plot(epochs, loss, 'y', label='Training loss')
|
| 149 |
+
plt.plot(epochs, val_loss, 'r', label='Validation loss')
|
| 150 |
+
plt.title('Training and validation loss for Gender model')
|
| 151 |
+
plt.xlabel('Epochs')
|
| 152 |
+
plt.ylabel('Loss')
|
| 153 |
+
plt.legend()
|
| 154 |
+
plt.show()
|
| 155 |
+
|
| 156 |
+
acc = history_gender.history['accuracy']
|
| 157 |
+
val_acc = history_gender.history['val_accuracy']
|
| 158 |
+
plt.plot(epochs, acc, 'y', label='Training Accuracy')
|
| 159 |
+
plt.plot(epochs, val_acc, 'r', label='Validation Accuracy')
|
| 160 |
+
plt.title('Training and validation accuracy for Gender model')
|
| 161 |
+
plt.xlabel('Epochs')
|
| 162 |
+
plt.ylabel('Accuracy')
|
| 163 |
+
plt.legend()
|
| 164 |
+
plt.show()
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# Test the model - Gender Model
|
| 168 |
+
my_model_gender = load_model('models/gender_model_3epochs.h5')
|
| 169 |
+
with tf.device('/CPU:0'):
|
| 170 |
+
predictions = my_model_gender.predict(X_test_gender)
|
| 171 |
+
y_pred = (predictions >= 0.5).astype(int)[:, 0]
|
| 172 |
+
|
| 173 |
+
from sklearn.metrics import accuracy_score, confusion_matrix
|
| 174 |
+
import seaborn as sns
|
| 175 |
+
|
| 176 |
+
print(f"Accuracy: {accuracy_score(y_true=y_test_gender, y_pred=y_pred)}")
|
| 177 |
+
|
| 178 |
+
# Confusion matrix
|
| 179 |
+
cm = confusion_matrix(y_true=y_test_gender, y_pred=y_pred)
|
| 180 |
+
sns.heatmap(cm, annot=True, fmt='d')
|
| 181 |
+
|
| 182 |
+
# Test the model - Age Model
|
| 183 |
+
|
| 184 |
+
# Saving the models to huggingface
|
| 185 |
+
from transformers import TFAutoModel
|
| 186 |
+
import tensorflow as tf
|
| 187 |
+
|
| 188 |
+
# Load your TensorFlow model from the .h5 file
|
| 189 |
+
age_model = tf.keras.models.load_model('models/age_model_3epochs.h5')
|
| 190 |
+
gender_model = tf.keras.models.load_model('models/gender_model_3epochs.h5')
|
| 191 |
+
|
| 192 |
+
# Save the model weights
|
| 193 |
+
age_model.save_weights('age_model_weights.h5')
|
| 194 |
+
gender_model.save_weights('gender_model_weights.h5')
|
| 195 |
+
|
| 196 |
+
# Load the architecture of the Hugging Face model you want to use
|
| 197 |
+
# For example, if you're using BERT, you would use TFBertModel
|
| 198 |
+
hf_model_age = TFAutoModel.from_pretrained('bert-base-uncased')
|
| 199 |
+
hf_model_gender = TFAutoModel.from_pretrained('bert-base-uncased')
|
| 200 |
+
|
| 201 |
+
# Load the weights into the Hugging Face model
|
| 202 |
+
hf_model_age.load_weights('age_model_weights.h5')
|
| 203 |
+
hf_model_gender.load_weights('gender_model_weights.h5')
|
| 204 |
+
|
| 205 |
+
# Save the Hugging Face model
|
| 206 |
+
hf_model_age.save_pretrained('hf_age_model')
|
| 207 |
+
hf_model_gender.save_pretrained('hf_gender_model')
|
age_model_3epochs.h5
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:62190e322612ef0631205e2d1b9a97ef0f328ee807385cddca465b3d680cd07d
|
| 3 |
+
size 274399416
|
gender_model_3epochs.h5
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6bb2821e39ea29aaaa4f2ad8d0d06a0cc10282e3de90d81b566012341e558695
|
| 3 |
+
size 47248096
|