{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"},{"sourceId":9587591,"sourceType":"datasetVersion","datasetId":5847039}],"dockerImageVersionId":30787,"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,"execution":{"iopub.status.busy":"2024-10-19T20:03:49.719855Z","iopub.execute_input":"2024-10-19T20:03:49.720843Z","iopub.status.idle":"2024-10-19T20:03:49.730556Z","shell.execute_reply.started":"2024-10-19T20:03:49.720794Z","shell.execute_reply":"2024-10-19T20:03:49.729689Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport tensorflow as tf\nimport math\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nfrom pathlib import Path\nimport pandas as pd\n\n# Constants\nIMG_HEIGHT = 32\nIMG_WIDTH = 32\nN_CLASSES = 10\nBATCH_SIZE = 64\nEPOCHS = 100\n\n# Data Loading\nimages_folder = Path('/kaggle/input/extracted')\ninput_folder = Path('/kaggle/input/cifar-10')\n\nlabels_dat = pd.read_csv(input_folder/'trainLabels.csv', index_col=['id']).iloc[:, 0]\nlabel_encoder = LabelEncoder().fit(labels_dat)\nclasses = label_encoder.classes_\n\ndef load_data_from_npz(filepath: Path):\n    npz_out = np.load(filepath)\n    return npz_out['images'], npz_out['ids']\n\nimages, ids = load_data_from_npz(images_folder/'train.npz')\nlabels = label_encoder.transform(labels_dat.loc[ids])\n\n# Data Preprocessing\ndef preprocess_images(images: np.ndarray):\n    images = images.astype(np.float32)\n    return tf.keras.applications.efficientnet.preprocess_input(images)\n\nX = preprocess_images(images)\n\n# Data Augmentation (CutMix, MixUp, CutOut)\ndef random_cutout(image, mask_size=8):\n    if image.ndim == 2:\n        image = np.stack((image,) * 3, axis=-1)\n    height, width = image.shape[0], image.shape[1]\n    mask_size = min(mask_size, height, width)\n    \n    top = np.random.randint(0, height - mask_size + 1)\n    left = np.random.randint(0, width - mask_size + 1)\n    \n    bottom = np.clip(top + mask_size, 0, height)\n    right = np.clip(left + mask_size, 0, width)\n\n    image[top:bottom, left:right, :] = image.mean()\n    return image\n\ndef cutmix(images, labels, alpha=1.0):\n    lam = np.random.beta(alpha, alpha)\n    batch_size = images.shape[0]\n    index = np.random.permutation(batch_size)\n    \n    shuffled_images = images[index]\n    shuffled_labels = labels[index]\n    \n    bbx1, bby1, bbx2, bby2 = rand_bbox(images.shape, lam)\n    images[:, bbx1:bbx2, bby1:bby2, :] = shuffled_images[:, bbx1:bbx2, bby1:bby2, :]\n    \n    lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (images.shape[1] * images.shape[2]))\n    return images, lam * labels + (1 - lam) * shuffled_labels\n\ndef mixup(images, labels, alpha=1.0):\n    lam = np.random.beta(alpha, alpha)\n    batch_size = images.shape[0]\n    index = np.random.permutation(batch_size)\n    \n    mixed_images = lam * images + (1 - lam) * images[index, :, :, :]\n    labels = lam * labels + (1 - lam) * labels[index]\n    return mixed_images, labels\n\ndef augment(images, labels):\n    images, labels = cutmix(images, labels)\n    images, labels = mixup(images, labels)\n    return images, labels\n\ndef rand_bbox(size, lam):\n    W = size[1]\n    H = size[2]\n    cut_rat = np.sqrt(1. - lam)\n    cut_w = np.int(W * cut_rat)\n    cut_h = np.int(H * cut_rat)\n\n    cx = np.random.randint(W)\n    cy = np.random.randint(H)\n\n    bbx1 = np.clip(cx - cut_w // 2, 0, W)\n    bby1 = np.clip(cy - cut_h // 2, 0, H)\n    bbx2 = np.clip(cx + cut_w // 2, 0, W)\n    bby2 = np.clip(cy + cut_h // 2, 0, H)\n\n    return bbx1, bby1, bbx2, bby2\n\n# Model Construction (EfficientNetB0)\ndef construct_model():\n    inputs = tf.keras.Input(shape=(IMG_WIDTH, IMG_HEIGHT, 3))\n    resize = tf.keras.layers.UpSampling2D(size=(7, 7))(inputs)\n    \n    efficientnet_features = EfficientNetB0(\n        input_shape=(224, 224, 3),\n        include_top=False,\n        weights=None\n    )(resize)\n    \n    x = tf.keras.layers.GlobalAveragePooling2D()(efficientnet_features)\n    x = tf.keras.layers.Dense(1024, activation=\"relu\")(x)\n    x = tf.keras.layers.Dropout(0.5)(x)\n    x = tf.keras.layers.Dense(512, activation=\"relu\")(x)\n    x = tf.keras.layers.Dropout(0.5)(x)\n    classification_output = tf.keras.layers.Dense(N_CLASSES, activation=\"softmax\")(x)\n    \n    model = tf.keras.Model(inputs=inputs, outputs=classification_output)\n    \n    optimizer = tf.keras.optimizers.AdamW(\n        learning_rate=1e-3,\n        weight_decay=1e-4\n    )\n    \n    # Compile the model using CategoricalCrossentropy with label smoothing\n    model.compile(\n        optimizer=optimizer,\n        loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1),  # Using label smoothing\n        metrics=['accuracy']\n    )\n    \n    return model\n\n# Cosine Annealing with Warmup Learning Rate\ndef cosine_annealing_with_warmup(epoch, lr):\n    warmup_epochs = 5\n    if epoch < warmup_epochs:\n        return lr * (epoch + 1) / warmup_epochs\n    else:\n        total_epochs = EPOCHS\n        return 0.5 * lr * (1 + math.cos(math.pi * (epoch - warmup_epochs) / (total_epochs - warmup_epochs)))\n\n# Train-validation split\nX_train, X_val, y_train, y_val = train_test_split(\n    X, labels, test_size=0.1, random_state=1, stratify=labels\n)\n\n# One-hot encode the labels\ny_train_one_hot = tf.keras.utils.to_categorical(y_train, num_classes=N_CLASSES)\ny_val_one_hot = tf.keras.utils.to_categorical(y_val, num_classes=N_CLASSES)\n\n# Create the model\ntf.keras.backend.clear_session()\nmodel = construct_model()\n\n# Learning rate scheduler\nlr_scheduler = tf.keras.callbacks.LearningRateScheduler(cosine_annealing_with_warmup)\n\n# Train the model with one-hot encoded labels\nhistory = model.fit(\n    X_train, y_train_one_hot,  # Use one-hot encoded labels here\n    validation_data=(X_val, y_val_one_hot),  # Also one-hot encode validation labels\n    epochs=EPOCHS,\n    batch_size=BATCH_SIZE,\n    callbacks=[lr_scheduler],\n    verbose=1\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-10-19T20:03:49.757191Z","iopub.execute_input":"2024-10-19T20:03:49.757515Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def test_time_augmentation(model, test_images):\n    tta_steps = 5\n    predictions = np.zeros((test_images.shape[0], N_CLASSES))\n    \n    # Create test_datagen without augmentation, only rescaling\n    test_datagen = tf.keras.preprocessing.image.ImageDataGenerator()  # No augmentation, just rescaling\n    \n    for _ in range(tta_steps):\n        aug_images = test_datagen.flow(test_images, batch_size=BATCH_SIZE, shuffle=False)\n        predictions += model.predict(aug_images)\n    \n    return predictions / tta_steps","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load test images\ntest_images, test_ids = load_data_from_npz(images_folder/'test.npz')\ntest_images = preprocess_images(test_images)\n\n# Apply test-time augmentation and predict\npredictions = test_time_augmentation(model, test_images)\ntest_preds = predictions.argmax(axis=1)\n\n# Create submission file\nsubmission = pd.DataFrame({\n    'id': test_ids,\n    'label': label_encoder.inverse_transform(test_preds)\n})\nsubmission.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}