{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":3557332,"sourceType":"datasetVersion","datasetId":2138237}],"dockerImageVersionId":30919,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\nfor 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},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D\nfrom tensorflow.keras import layers, Model\nfrom tensorflow.keras.optimizers import Adam\nimport os\nimport shutil\nimport random","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-04T08:02:03.150421Z","iopub.execute_input":"2025-04-04T08:02:03.150751Z","iopub.status.idle":"2025-04-04T08:02:03.155058Z","shell.execute_reply.started":"2025-04-04T08:02:03.150726Z","shell.execute_reply":"2025-04-04T08:02:03.154201Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define dataset paths\ntrain_dir = \"/kaggle/input/vggface2/train\"\nval_dir = \"/kaggle/working/subset_val\"\nos.makedirs(val_dir, exist_ok=True)\n\n#VAL_DATA_DIR = os.path.join(DATASET_DIR, \"val\")\n\n# Image Parameters\nIMG_SIZE = (224, 224)  # ResNet50 input size\nBATCH_SIZE = 32\n\nfor identity in os.listdir(train_dir):\n    train_path = os.path.join(train_dir, identity)\n    val_path = os.path.join(val_dir, identity)\n    if not os.path.exists(val_path):  # Avoid re-copying if already exists\n        os.makedirs(val_path, exist_ok=True)\n        images = os.listdir(train_path)\n        val_size = max(1, len(images) // 10)  # 10% of images\n        val_images = random.sample(images, val_size)\n        for img in val_images:\n            shutil.copy(os.path.join(train_path, img), val_path)\n\n# Data generators\ntrain_datagen = ImageDataGenerator(rescale=1./255, horizontal_flip=True)\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(train_dir, target_size=IMG_SIZE, batch_size=BATCH_SIZE, class_mode='categorical')\nval_generator = val_datagen.flow_from_directory(val_dir, target_size=IMG_SIZE, batch_size=BATCH_SIZE, class_mode='categorical')\n\nNUM_CLASSES = len(train_generator.class_indices)\nprint(f\"Train classes: {NUM_CLASSES}, Val classes: {len(val_generator.class_indices)}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-04T07:43:50.434343Z","iopub.execute_input":"2025-04-04T07:43:50.434663Z","iopub.status.idle":"2025-04-04T07:55:56.144980Z","shell.execute_reply.started":"2025-04-04T07:43:50.434639Z","shell.execute_reply":"2025-04-04T07:55:56.144317Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Model\ndef create_model(num_classes):\n    base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\n    base_model.trainable = False\n    inputs = tf.keras.Input(shape=(224, 224, 3))\n    x = base_model(inputs, training=False)\n    x = layers.GlobalAveragePooling2D()(x)\n    x = layers.Dropout(0.2)(x)\n    x = layers.Dense(256, activation='relu')(x)\n    x = layers.Dropout(0.2)(x)\n    outputs = layers.Dense(num_classes, activation='softmax')(x)\n    return Model(inputs, outputs)\n\nmodel = create_model(NUM_CLASSES)\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\nhistory = model.fit(train_generator, validation_data=val_generator, epochs=10, verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-04T08:02:08.950863Z","iopub.execute_input":"2025-04-04T08:02:08.951150Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}