{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":70905,"databundleVersionId":7746452,"sourceType":"competition"}],"dockerImageVersionId":30918,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n    #for filename in filenames:\n        #print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-04-05T19:12:56.434612Z","iopub.execute_input":"2025-04-05T19:12:56.435058Z","iopub.status.idle":"2025-04-05T19:12:56.822477Z","shell.execute_reply.started":"2025-04-05T19:12:56.435015Z","shell.execute_reply":"2025-04-05T19:12:56.821396Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Deep Learning Applications - Age Prediction**","metadata":{}},{"cell_type":"markdown","source":"## Introduction","metadata":{}},{"cell_type":"markdown","source":"Age prediction from facial images is a fascinating application of deep learning that intersects fields such as computer vision and biometrics. This project focuses on developing a convolutional neural network (CNN) to accurately predict the age of individuals based on their facial features. Utilizing a dataset of images accompanied by age labels, we implement various preprocessing techniques to prepare the data for training. The goal is to create a robust model capable of generalizing well to unseen data, thereby providing insights into age estimation technology's potential applications in security, marketing, and social media analytics.","metadata":{}},{"cell_type":"markdown","source":"## Requirements","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\nimport numpy as np\nimport cv2\nimport os\nimport seaborn as sns\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\nfrom tensorflow.keras import layers, models\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom keras.layers import Dense, Conv2D, Flatten, Input, MaxPooling2D,Dropout,BatchNormalization,Reshape\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom tensorflow.keras import regularizers\nfrom sklearn.metrics import mean_absolute_error","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T19:12:56.823932Z","iopub.execute_input":"2025-04-05T19:12:56.824495Z","iopub.status.idle":"2025-04-05T19:13:13.128602Z","shell.execute_reply.started":"2025-04-05T19:12:56.824455Z","shell.execute_reply":"2025-04-05T19:13:13.127512Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Data Load","metadata":{}},{"cell_type":"code","source":"dataset_dir='/kaggle/input/applications-of-deep-learning-wustl-spring-2024/faces-age'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T19:13:13.130594Z","iopub.execute_input":"2025-04-05T19:13:13.131339Z","iopub.status.idle":"2025-04-05T19:13:13.135856Z","shell.execute_reply.started":"2025-04-05T19:13:13.131298Z","shell.execute_reply":"2025-04-05T19:13:13.134557Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df=pd.read_csv(\"/kaggle/input/applications-of-deep-learning-wustl-spring-2024/faces-age/train.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T19:13:13.137648Z","iopub.execute_input":"2025-04-05T19:13:13.138091Z","iopub.status.idle":"2025-04-05T19:13:13.219578Z","shell.execute_reply.started":"2025-04-05T19:13:13.138053Z","shell.execute_reply":"2025-04-05T19:13:13.218793Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load dataset\ndef load_data(df, dataset_dir):\n    images = []\n    ages = []\n    \n    for index, row in df.iterrows():\n        img_path = os.path.join(dataset_dir, row['filename'])\n        img = load_img(img_path, target_size=(128, 128))\n        img_array = img_to_array(img) / 255.0  # Normalize the image\n        images.append(img_array)\n        ages.append(row['age'])\n\n    return np.array(images), np.array(ages)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T19:13:13.220527Z","iopub.execute_input":"2025-04-05T19:13:13.220839Z","iopub.status.idle":"2025-04-05T19:13:13.226536Z","shell.execute_reply.started":"2025-04-05T19:13:13.220814Z","shell.execute_reply":"2025-04-05T19:13:13.225484Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load images and labels\nX, y = load_data(df, dataset_dir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T19:13:13.227651Z","iopub.execute_input":"2025-04-05T19:13:13.227972Z","iopub.status.idle":"2025-04-05T19:15:42.107301Z","shell.execute_reply.started":"2025-04-05T19:13:13.227948Z","shell.execute_reply":"2025-04-05T19:15:42.106359Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Modelling","metadata":{}},{"cell_type":"code","source":"# Split the dataset\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T19:15:42.108579Z","iopub.execute_input":"2025-04-05T19:15:42.108877Z","iopub.status.idle":"2025-04-05T19:15:43.597863Z","shell.execute_reply.started":"2025-04-05T19:15:42.108854Z","shell.execute_reply":"2025-04-05T19:15:43.596443Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Build the model\nmodel = models.Sequential([\n    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)),\n    layers.MaxPooling2D(pool_size=(2, 2)),\n    layers.Conv2D(64, (3, 3), activation='relu'),\n    layers.MaxPooling2D(pool_size=(2, 2)),\n    layers.Conv2D(128, (3, 3), activation='relu'),\n    layers.MaxPooling2D(pool_size=(2, 2)),\n    layers.Flatten(),\n    layers.Dense(128, activation='relu'),\n    layers.Dense(1)\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T19:15:43.600765Z","iopub.execute_input":"2025-04-05T19:15:43.601126Z","iopub.status.idle":"2025-04-05T19:15:43.749548Z","shell.execute_reply.started":"2025-04-05T19:15:43.601096Z","shell.execute_reply":"2025-04-05T19:15:43.748627Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer='adam', loss='mean_absolute_error')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T19:15:43.751019Z","iopub.execute_input":"2025-04-05T19:15:43.751423Z","iopub.status.idle":"2025-04-05T19:15:43.767933Z","shell.execute_reply.started":"2025-04-05T19:15:43.751397Z","shell.execute_reply":"2025-04-05T19:15:43.766658Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train the model\nhistory=model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=20, batch_size=32)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T19:15:43.769257Z","iopub.execute_input":"2025-04-05T19:15:43.769629Z","iopub.status.idle":"2025-04-05T20:39:53.624556Z","shell.execute_reply.started":"2025-04-05T19:15:43.769591Z","shell.execute_reply":"2025-04-05T20:39:53.622888Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plot training & validation loss\nplt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['loss'], label='Train Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.title('Model Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T20:39:53.626828Z","iopub.execute_input":"2025-04-05T20:39:53.627249Z","iopub.status.idle":"2025-04-05T20:39:53.952851Z","shell.execute_reply.started":"2025-04-05T20:39:53.627217Z","shell.execute_reply":"2025-04-05T20:39:53.951595Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Visualize predictions\ny_pred = model.predict(X_test)\nplt.subplot(1, 2, 2)\nplt.scatter(y_test, y_pred)\nplt.xlabel('Actual Ages')\nplt.ylabel('Predicted Ages')\nplt.title('Actual vs Predicted Ages')\nplt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--')  # Diagonal line\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T20:39:53.954202Z","iopub.execute_input":"2025-04-05T20:39:53.954481Z","iopub.status.idle":"2025-04-05T20:40:14.121883Z","shell.execute_reply.started":"2025-04-05T20:39:53.954456Z","shell.execute_reply":"2025-04-05T20:40:14.120654Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Calculate Mean Absolute Error\nmae = mean_absolute_error(y_test, y_pred)\nprint(f'Mean Absolute Error: {mae}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T20:40:14.123197Z","iopub.execute_input":"2025-04-05T20:40:14.123609Z","iopub.status.idle":"2025-04-05T20:40:14.130931Z","shell.execute_reply.started":"2025-04-05T20:40:14.123570Z","shell.execute_reply":"2025-04-05T20:40:14.129949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save the model\nmodel.save('age_prediction_model.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-05T20:40:14.131896Z","iopub.execute_input":"2025-04-05T20:40:14.132195Z","iopub.status.idle":"2025-04-05T20:40:14.282818Z","shell.execute_reply.started":"2025-04-05T20:40:14.132167Z","shell.execute_reply":"2025-04-05T20:40:14.281639Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Conclusion\nIn this project, we successfully developed a deep learning model to predict age from facial images using a convolutional neural network. The model achieved a mean absolute error of approximately 8.44 years, demonstrating its effectiveness in age estimation. Through data preprocessing, model architecture design, and training, we showcased the capabilities of deep learning in handling image data for regression tasks. Future work could explore enhancements such as data augmentation, transfer learning from pre-trained models, and fine-tuning hyperparameters to further improve accuracy and robustness. This research highlights the potential of deep learning in applications requiring age estimation, paving the way for innovative solutions across various domains.","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}