{"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":"markdown","source":"# **Age Prediction**","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"markdown","source":"### Set Up the Environment","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-03-23T20:48:52.674485Z","iopub.execute_input":"2025-03-23T20:48:52.674878Z","iopub.status.idle":"2025-03-23T20:48:52.681827Z","shell.execute_reply.started":"2025-03-23T20:48:52.674842Z","shell.execute_reply":"2025-03-23T20:48:52.680615Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Parameters\nIMG_HEIGHT, IMG_WIDTH = 128, 128\nBATCH_SIZE = 32\nEPOCHS = 20","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-23T19:25:28.008604Z","iopub.execute_input":"2025-03-23T19:25:28.008971Z","iopub.status.idle":"2025-03-23T19:25:28.013272Z","shell.execute_reply.started":"2025-03-23T19:25:28.008942Z","shell.execute_reply":"2025-03-23T19:25:28.012045Z"}},"outputs":[],"execution_count":null},{"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-03-23T19:25:51.698217Z","iopub.execute_input":"2025-03-23T19:25:51.698531Z","iopub.status.idle":"2025-03-23T19:25:51.702305Z","shell.execute_reply.started":"2025-03-23T19:25:51.698508Z","shell.execute_reply":"2025-03-23T19:25:51.701412Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Load the Dataset","metadata":{}},{"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=(IMG_HEIGHT, IMG_WIDTH))\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-03-23T19:26:07.278125Z","iopub.execute_input":"2025-03-23T19:26:07.278447Z","iopub.status.idle":"2025-03-23T19:26:07.284Z","shell.execute_reply.started":"2025-03-23T19:26:07.278422Z","shell.execute_reply":"2025-03-23T19:26:07.282819Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train=pd.read_csv(\"/kaggle/input/applications-of-deep-learning-wustl-spring-2024/faces-age/train.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-23T19:26:45.174163Z","iopub.execute_input":"2025-03-23T19:26:45.174488Z","iopub.status.idle":"2025-03-23T19:26:45.193963Z","shell.execute_reply.started":"2025-03-23T19:26:45.174464Z","shell.execute_reply":"2025-03-23T19:26:45.193031Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-23T19:26:47.593632Z","iopub.execute_input":"2025-03-23T19:26:47.594026Z","iopub.status.idle":"2025-03-23T19:26:47.602712Z","shell.execute_reply.started":"2025-03-23T19:26:47.593985Z","shell.execute_reply":"2025-03-23T19:26:47.601768Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load images and labels\nX, y = load_data(df_train, dataset_dir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-23T19:27:50.201319Z","iopub.execute_input":"2025-03-23T19:27:50.201664Z","iopub.status.idle":"2025-03-23T19:29:42.6749Z","shell.execute_reply.started":"2025-03-23T19:27:50.201634Z","shell.execute_reply":"2025-03-23T19:29:42.674066Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Split the dataset\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-23T19:31:04.724125Z","iopub.execute_input":"2025-03-23T19:31:04.724535Z","iopub.status.idle":"2025-03-23T19:31:05.985503Z","shell.execute_reply.started":"2025-03-23T19:31:04.724491Z","shell.execute_reply":"2025-03-23T19:31:05.984689Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Build the model\nmodel = models.Sequential([\n    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH, 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)  # Output layer for regression\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-23T19:31:19.618873Z","iopub.execute_input":"2025-03-23T19:31:19.619183Z","iopub.status.idle":"2025-03-23T19:31:19.730092Z","shell.execute_reply.started":"2025-03-23T19:31:19.619162Z","shell.execute_reply":"2025-03-23T19:31:19.729119Z"}},"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-03-23T19:31:30.810027Z","iopub.execute_input":"2025-03-23T19:31:30.810364Z","iopub.status.idle":"2025-03-23T19:31:30.824063Z","shell.execute_reply.started":"2025-03-23T19:31:30.810334Z","shell.execute_reply":"2025-03-23T19:31:30.823088Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train the model\nmodel.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=EPOCHS, batch_size=BATCH_SIZE)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-23T19:31:38.905557Z","iopub.execute_input":"2025-03-23T19:31:38.90594Z","iopub.status.idle":"2025-03-23T20:46:19.671775Z","shell.execute_reply.started":"2025-03-23T19:31:38.905911Z","shell.execute_reply":"2025-03-23T20:46:19.669842Z"}},"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-03-23T20:46:43.332057Z","iopub.execute_input":"2025-03-23T20:46:43.332452Z","iopub.status.idle":"2025-03-23T20:46:43.584654Z","shell.execute_reply.started":"2025-03-23T20:46:43.332423Z","shell.execute_reply":"2025-03-23T20:46:43.583149Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Visualize predictions\ny_pred = model.predict(X_val)\nplt.subplot(1, 2, 2)\nplt.scatter(y_val, y_pred)\nplt.xlabel('Actual Ages')\nplt.ylabel('Predicted Ages')\nplt.title('Actual vs Predicted Ages')\nplt.plot([min(y_val), max(y_val)], [min(y_val), max(y_val)], 'r--')  # Diagonal line\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-23T20:48:15.154464Z","iopub.execute_input":"2025-03-23T20:48:15.154876Z","iopub.status.idle":"2025-03-23T20:48:31.714396Z","shell.execute_reply.started":"2025-03-23T20:48:15.154847Z","shell.execute_reply":"2025-03-23T20:48:31.713228Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Calculate Mean Absolute Error\nmae = mean_absolute_error(y_val, y_pred)\nprint(f'Mean Absolute Error: {mae}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-23T20:49:00.547399Z","iopub.execute_input":"2025-03-23T20:49:00.547772Z","iopub.status.idle":"2025-03-23T20:49:00.554275Z","shell.execute_reply.started":"2025-03-23T20:49:00.547727Z","shell.execute_reply":"2025-03-23T20:49:00.553373Z"}},"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-03-23T20:50:10.490922Z","iopub.execute_input":"2025-03-23T20:50:10.491313Z","iopub.status.idle":"2025-03-23T20:50:10.612431Z","shell.execute_reply.started":"2025-03-23T20:50:10.491283Z","shell.execute_reply":"2025-03-23T20:50:10.611522Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}