{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":127713,"databundleVersionId":15291341,"sourceType":"competition"}],"dockerImageVersionId":31236,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Binary Classification with Artificial Neural Network\n\nThis notebook implements a Convolutional Neural Network (CNN) for a binary classification task (Masculine vs. Feminine) using TensorFlow and Keras.","metadata":{}},{"cell_type":"code","source":"!pip install --upgrade --force-reinstall protobuf==3.20.3\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-15T15:30:50.871209Z","iopub.execute_input":"2026-01-15T15:30:50.871965Z","iopub.status.idle":"2026-01-15T15:30:57.013033Z","shell.execute_reply.started":"2026-01-15T15:30:50.871932Z","shell.execute_reply":"2026-01-15T15:30:57.012247Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Input\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport os\nimport matplotlib.pyplot as plt","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-15T15:30:57.014602Z","iopub.execute_input":"2026-01-15T15:30:57.014866Z","iopub.status.idle":"2026-01-15T15:31:20.998416Z","shell.execute_reply.started":"2026-01-15T15:30:57.014838Z","shell.execute_reply":"2026-01-15T15:31:20.997614Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 1. Configuration and Data Loading","metadata":{}},{"cell_type":"code","source":"# Configuration\nIMAGE_SIZE = (128, 128)\nBATCH_SIZE = 32\nEPOCHS = 15\n\n# Paths\nBASE_DIR = '/kaggle/input/anime-gender-classification/dataset'\nTRAIN_CSV = os.path.join(BASE_DIR, 'train.csv')\nVAL_CSV = os.path.join(BASE_DIR, 'val.csv')\nSUBMISSION_FORMAT = os.path.join(BASE_DIR, 'submission_format.csv')\nTRAIN_DIR = os.path.join(BASE_DIR, 'train_images')\nVAL_DIR = os.path.join(BASE_DIR, 'val_images')\nTEST_DIR = os.path.join(BASE_DIR, 'test_images')\n\n# Load csv files\ntrain_df = pd.read_csv(TRAIN_CSV)\nval_df = pd.read_csv(VAL_CSV)\n\n# Ensure labels are strings for binary class mode\ntrain_df['label'] = train_df['label'].astype(str)\nval_df['label'] = val_df['label'].astype(str)\n\nprint(f\"Training set size: {len(train_df)}\")\nprint(f\"Validation set size: {len(val_df)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-15T15:31:20.999467Z","iopub.execute_input":"2026-01-15T15:31:21.000114Z","iopub.status.idle":"2026-01-15T15:31:21.050583Z","shell.execute_reply.started":"2026-01-15T15:31:21.000075Z","shell.execute_reply":"2026-01-15T15:31:21.049770Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Data Generators\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest'\n)\n\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe=train_df,\n    directory=TRAIN_DIR,\n    x_col='id',\n    y_col='label',\n    target_size=IMAGE_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode='binary'\n)\n\nval_generator = val_datagen.flow_from_dataframe(\n    dataframe=val_df,\n    directory=VAL_DIR,\n    x_col='id',\n    y_col='label',\n    target_size=IMAGE_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode='binary',\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-15T15:31:21.052350Z","iopub.execute_input":"2026-01-15T15:31:21.052646Z","iopub.status.idle":"2026-01-15T15:31:38.734134Z","shell.execute_reply.started":"2026-01-15T15:31:21.052624Z","shell.execute_reply":"2026-01-15T15:31:38.733293Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2. Model Construction","metadata":{}},{"cell_type":"code","source":"def build_model():\n    model = Sequential([\n        Input(shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3)),\n        Conv2D(32, (3, 3), activation='relu'),\n        MaxPooling2D(2, 2),\n        \n        Conv2D(64, (3, 3), activation='relu'),\n        MaxPooling2D(2, 2),\n        \n        Conv2D(128, (3, 3), activation='relu'),\n        MaxPooling2D(2, 2),\n        \n        Flatten(),\n        Dense(128, activation='relu'),\n        Dropout(0.5),\n        Dense(1, activation='sigmoid')\n    ])\n    \n    model.compile(optimizer='adam',\n                  loss='binary_crossentropy',\n                  metrics=['accuracy'])\n    return model\n\nmodel = build_model()\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-15T15:31:38.735121Z","iopub.execute_input":"2026-01-15T15:31:38.735432Z","iopub.status.idle":"2026-01-15T15:31:41.623853Z","shell.execute_reply.started":"2026-01-15T15:31:38.735407Z","shell.execute_reply":"2026-01-15T15:31:41.623254Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 3. Training","metadata":{}},{"cell_type":"code","source":"history = model.fit(\n    train_generator,\n    steps_per_epoch=max(1, len(train_df) // BATCH_SIZE),\n    epochs=EPOCHS,\n    validation_data=val_generator,\n    validation_steps=max(1, len(val_df) // BATCH_SIZE)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-15T15:31:41.624824Z","iopub.execute_input":"2026-01-15T15:31:41.625075Z","iopub.status.idle":"2026-01-15T15:40:31.501494Z","shell.execute_reply.started":"2026-01-15T15:31:41.625052Z","shell.execute_reply":"2026-01-15T15:40:31.500628Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 4. Evaluation","metadata":{}},{"cell_type":"code","source":"acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(len(acc))\n\nplt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-15T15:40:31.502665Z","iopub.execute_input":"2026-01-15T15:40:31.503428Z","iopub.status.idle":"2026-01-15T15:40:31.810926Z","shell.execute_reply.started":"2026-01-15T15:40:31.503392Z","shell.execute_reply":"2026-01-15T15:40:31.810227Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Submission ","metadata":{}},{"cell_type":"code","source":"# Load sample submission to get test IDs\nsubmission_df = pd.read_csv(SUBMISSION_FORMAT)\ntest_filenames = submission_df['id'].tolist()\n\n# Create Test DataFrame\ntest_df = pd.DataFrame({'id': test_filenames})\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe=test_df,\n    directory=TEST_DIR,\n    x_col='id',\n    y_col=None,\n    target_size=IMAGE_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode=None,\n    shuffle=False\n)\n\n# Predict\npredictions = model.predict(test_generator)\npredicted_classes = (predictions > 0.5).astype(int).flatten()\n\n# Create submission file\nsubmission = pd.DataFrame({\n    'id': test_df['id'],\n    'label': predicted_classes\n})\n\nsubmission.to_csv('submission.csv', index=False)\nprint(\"Submission file 'submission.csv' created successfully.\")\nsubmission.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-15T15:40:31.811819Z","iopub.execute_input":"2026-01-15T15:40:31.812041Z","iopub.status.idle":"2026-01-15T15:40:40.636612Z","shell.execute_reply.started":"2026-01-15T15:40:31.812009Z","shell.execute_reply":"2026-01-15T15:40:40.635807Z"}},"outputs":[],"execution_count":null}]}