{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"colab":{"provenance":[],"collapsed_sections":["Qw7qc1lGyka3","IKJa6fTNy9-X","qrM5DPrVzCcJ"],"machine_shape":"hm","gpuType":"L4"},"accelerator":"GPU","kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":70905,"databundleVersionId":7746452,"sourceType":"competition"}],"dockerImageVersionId":31011,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# AGE PREDICTION\n\n## INTRODUCTION\n\nThis project focuses on developing an AI system to estimate human age from facial images. Age prediction from faces has applications in healthcare, marketing, and security.\n\n## AIM\n\nTo build a deep learning model using Convolutional Neural Networks (CNNs) that accurately predicts age from facial images. The model will be trained on labeled face datasets to recognize age-related features and generalize to new images.\n","metadata":{"id":"8w1V1OLswOo6"}},{"cell_type":"markdown","source":"### IMPORTS","metadata":{"id":"Qw7qc1lGyka3"}},{"cell_type":"code","source":"#pip install opencv-python","metadata":{"id":"kKDRAgkAyo6z"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#!pip install scikit-learn","metadata":{"id":"v4HIIJd5yn1_"},"outputs":[],"execution_count":null},{"cell_type":"code","source":" # !pip install --upgrade tensorflow","metadata":{"id":"dvv3eeRGymbw","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:25:59.924383Z","iopub.execute_input":"2025-04-21T18:25:59.924986Z","iopub.status.idle":"2025-04-21T18:25:59.929037Z","shell.execute_reply.started":"2025-04-21T18:25:59.924962Z","shell.execute_reply":"2025-04-21T18:25:59.928215Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nimport warnings\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport re\nfrom sklearn.model_selection import train_test_split\n#from IPython.display import Image\n\nfrom keras.models import Sequential, Model, load_model\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Input, BatchNormalization, Reshape, GlobalAveragePooling2D,Activation\nfrom keras.regularizers import l2\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions\n\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)","metadata":{"id":"XEiNYUvgwNyL","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:26:15.490120Z","iopub.execute_input":"2025-04-21T18:26:15.490685Z","iopub.status.idle":"2025-04-21T18:26:15.495659Z","shell.execute_reply.started":"2025-04-21T18:26:15.490664Z","shell.execute_reply":"2025-04-21T18:26:15.494955Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### READING DATA","metadata":{"id":"IKJa6fTNy9-X"}},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/applications-of-deep-learning-wustl-spring-2024/faces-age/train.csv\")\ndf.head()","metadata":{"id":"a8uOIOviy5Gw","outputId":"de5e24f2-ba0b-40c4-a5e5-e47335c4c54d","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:27:42.547571Z","iopub.execute_input":"2025-04-21T18:27:42.548220Z","iopub.status.idle":"2025-04-21T18:27:42.569050Z","shell.execute_reply.started":"2025-04-21T18:27:42.548195Z","shell.execute_reply":"2025-04-21T18:27:42.568492Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_path = \"/kaggle/input/applications-of-deep-learning-wustl-spring-2024/faces-age/\"\ndf['filename'] = df['filename'].apply(lambda x: img_path + x)","metadata":{"id":"u7Bal_sWLE1O","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:27:48.910555Z","iopub.execute_input":"2025-04-21T18:27:48.911544Z","iopub.status.idle":"2025-04-21T18:27:48.921979Z","shell.execute_reply.started":"2025-04-21T18:27:48.911510Z","shell.execute_reply":"2025-04-21T18:27:48.921106Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.rename(columns={'filename': 'img'}, inplace=True)","metadata":{"id":"4HxhmvnZMeMo","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:27:52.067167Z","iopub.execute_input":"2025-04-21T18:27:52.067434Z","iopub.status.idle":"2025-04-21T18:27:52.071670Z","shell.execute_reply.started":"2025-04-21T18:27:52.067414Z","shell.execute_reply":"2025-04-21T18:27:52.070989Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.img[0]","metadata":{"id":"qA5lPA6pYP-x","outputId":"0fec7c68-06a9-400a-a597-81d26881715b","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:27:54.063432Z","iopub.execute_input":"2025-04-21T18:27:54.064000Z","iopub.status.idle":"2025-04-21T18:27:54.068481Z","shell.execute_reply.started":"2025-04-21T18:27:54.063977Z","shell.execute_reply":"2025-04-21T18:27:54.067941Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### EDA","metadata":{"id":"pODuDeh3zyOw"}},{"cell_type":"code","source":"selected_images = df.groupby('age', as_index=False).apply(lambda x: x.sample(n=1, random_state=2)).reset_index(drop=True)\n\nsns.set(style='whitegrid')\nfig, axes = plt.subplots(5, 10, figsize=(15, 8))\n\naxes = axes.flatten()\n\nfor ax, (img_path, label) in zip(axes, zip(selected_images['img'], selected_images['age'])):\n    img = Image.open(img_path)\n    ax.imshow(img)\n    ax.axis('off')\n    ax.set_title(label, fontsize=14)\n\nplt.tight_layout()\nplt.show()","metadata":{"id":"JBhnT2_szfM8","outputId":"05f0c3af-c066-43f2-febc-82f1b6884135","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:27:57.083498Z","iopub.execute_input":"2025-04-21T18:27:57.083775Z","iopub.status.idle":"2025-04-21T18:28:03.531224Z","shell.execute_reply.started":"2025-04-21T18:27:57.083755Z","shell.execute_reply":"2025-04-21T18:28:03.530272Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(10, 6))\nsns.histplot(df['age'], bins=10, kde=True, color='skyblue', stat='density')\nplt.title('Age Distribution', fontsize=16)\nplt.xlabel('Age', fontsize=14)\nplt.ylabel('Density', fontsize=14)\nplt.grid(axis='y')\nplt.show()","metadata":{"id":"VGDF9uhtcaL2","outputId":"24c66c13-f553-45b4-fc5b-d3f3cac8ac97"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label_values = df['age'].value_counts().reset_index()\nlabel_values.columns = ['Age', 'Count']\n\n# Create a bar plot with a suitable palette\nplt.figure(figsize=(15, 6))\nsns.barplot(data=label_values, x='Age', y='Count')\nplt.xlabel('Age')\nplt.ylabel('Count')\nplt.title('Age Distribution')\nplt.xticks(rotation=90)\nplt.show()","metadata":{"id":"rLOhgjmu1Gki","outputId":"d40d1eb9-7cda-4b0f-aca8-1922371c0fc3","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:29:17.146899Z","iopub.execute_input":"2025-04-21T18:29:17.147617Z","iopub.status.idle":"2025-04-21T18:29:17.907622Z","shell.execute_reply.started":"2025-04-21T18:29:17.147595Z","shell.execute_reply":"2025-04-21T18:29:17.906787Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### PREPARING TEST DATA","metadata":{"id":"H6V08sBD0DgA"}},{"cell_type":"code","source":"img_width, img_height = 128, 128","metadata":{"id":"weAn5b770HJ5"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = []\ny = []\n\nfor img_path, label in zip(df['img'], df['age']):\n    img = cv2.imread(img_path)\n    if img is None:\n        continue\n\n    img = cv2.resize(img, (img_width, img_height))\n    img = img / 255.0\n    x.append(img)\n    y.append(label)","metadata":{"id":"JWqZxPbK0Jol"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = np.array(x)\ny = np.array(y)","metadata":{"id":"52zZ7jRr0K_h"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=42)","metadata":{"id":"C6EXsB8M0MV_"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## CNN","metadata":{"id":"whi4JmAI2-PR"}},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Input(shape=(img_width, img_height, 3)))\n\nmodel.add(Conv2D(32, kernel_size=(3,3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Conv2D(64, kernel_size=(3,3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Conv2D(128, kernel_size=(3,3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Conv2D(256, kernel_size=(3,3), activation='relu', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(64, activation='relu'))\n\nmodel.add(Dense(1) )\n\nmodel.compile(optimizer='adam', loss='mse', metrics=['mae', 'mse'])","metadata":{"id":"QZ1TpezR6gxG"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"early_stopping = EarlyStopping(monitor='mse', patience=5)\n\nhistory = model.fit(x_train, y_train, epochs=30, validation_data=(x_test, y_test), verbose=1, callbacks=[early_stopping])","metadata":{"id":"rJw6eI_N3Hdb","outputId":"80b90c04-9c4e-490a-f4e9-7f600a1a0efe"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"id":"3AKOwpEV_bfb","outputId":"ec6cde11-8198-43d9-ad9a-48a4f7cea6aa"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history_df = pd.DataFrame(history.history)\nhistory_df","metadata":{"id":"CvsXZn7X_3TQ","outputId":"3ae407b7-423f-4fb2-fbd1-307be6760b50"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(10, 5))\n\nplt.subplot(1, 2, 1)\nplt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss (MSE)\")\nplt.title(\"Training vs Validation Loss\")\nplt.legend()\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['mae'], label='Training MAE')\nplt.plot(history.history['val_mae'], label='Validation MAE')\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Mean Absolute Error\")\nplt.title(\"Training vs Validation MAE\")\nplt.legend()\n\nplt.tight_layout()\nplt.show()","metadata":{"id":"IXw7ZyK6r-9M","outputId":"d4256296-2c2d-4688-fa05-27ba6c2f8a1d"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"unique_ages_array_sorted = np.sort(np.array(df['age'].unique()))","metadata":{"id":"N_KJgKdPswsD"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('age_prediction.keras')","metadata":{"id":"A52Rq4EB_JuC"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# MODEL TESTING","metadata":{"id":"HeAMXhwJmwVp"}},{"cell_type":"markdown","source":"## READING TEST DATA","metadata":{"id":"KixLPMqcnXLr"}},{"cell_type":"code","source":"img_path= '/kaggle/input/applications-of-deep-learning-wustl-spring-2024/faces-age/'\ndf_test = pd.read_csv('/kaggle/input/applications-of-deep-learning-wustl-spring-2024/faces-age/test.csv')\ndf_test.head()","metadata":{"id":"lr2fvL3RnZ1j","outputId":"ad266cff-3304-4e06-fe75-46015f5f8420","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:29:53.908277Z","iopub.execute_input":"2025-04-21T18:29:53.908568Z","iopub.status.idle":"2025-04-21T18:29:53.921366Z","shell.execute_reply.started":"2025-04-21T18:29:53.908546Z","shell.execute_reply":"2025-04-21T18:29:53.920823Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test['filename'] = df_test['filename'].apply(lambda x: img_path + x)","metadata":{"id":"z7BKw6iDOvuh","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:29:57.086368Z","iopub.execute_input":"2025-04-21T18:29:57.087037Z","iopub.status.idle":"2025-04-21T18:29:57.091268Z","shell.execute_reply.started":"2025-04-21T18:29:57.087014Z","shell.execute_reply":"2025-04-21T18:29:57.090586Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test.rename(columns={'filename': 'img'}, inplace=True)","metadata":{"id":"AjhogmesO58d","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:30:00.252792Z","iopub.execute_input":"2025-04-21T18:30:00.253028Z","iopub.status.idle":"2025-04-21T18:30:00.257258Z","shell.execute_reply.started":"2025-04-21T18:30:00.253012Z","shell.execute_reply":"2025-04-21T18:30:00.256519Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test.head()","metadata":{"id":"tyZ4oZjcPInC","outputId":"9b1c4844-4f07-4869-c1d7-fe4d6eecc426","trusted":true,"execution":{"iopub.status.busy":"2025-04-21T18:30:02.360045Z","iopub.execute_input":"2025-04-21T18:30:02.360539Z","iopub.status.idle":"2025-04-21T18:30:02.367409Z","shell.execute_reply.started":"2025-04-21T18:30:02.360514Z","shell.execute_reply":"2025-04-21T18:30:02.366726Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## PREDICT IMAGES","metadata":{"id":"JiYaelEVqCH7"}},{"cell_type":"code","source":"img_width, img_height = 128, 128","metadata":{"id":"c7cY_uU6qBdB"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = []\n\nfor img_path in df_test['img']:\n    img = cv2.imread(img_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    if img is None:\n        continue\n\n    img = cv2.resize(img, (img_width, img_height))\n    img = img / 255.0\n    x.append(img)","metadata":{"id":"xlMvqzHoqGqN"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_test = np.array(x)","metadata":{"id":"XPT_LlTdq4Rh"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions=model.predict(x_test)\npredictions=np.round(predictions).astype(int)\npredictions=predictions.flatten()","metadata":{"id":"ZZxYoWzbq7CB","outputId":"e13c769c-687a-47d6-8a5e-7ee6e18668c8"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# SUBMIT MODEL","metadata":{"id":"6EG4YqXfmg2V"}},{"cell_type":"code","source":"submission=pd.DataFrame({\n    'id':df_test['id'],\n    'age':predictions\n})","metadata":{"id":"Cf2WRuBUmghB"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.head()","metadata":{"id":"I4w-RAuMq_Za","outputId":"606f14df-a2d6-4fb2-b8aa-a85a15720b07"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.to_csv('submission.csv',index=False)","metadata":{"id":"Rc0-cVl8rAqh"},"outputs":[],"execution_count":null}]}