{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"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)\nimport time\nfrom PIL import Image\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Input, Conv2D, BatchNormalization, Activation, Add, AveragePooling2D, Flatten, Dense\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.callbacks import LearningRateScheduler\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.keras import layers, Sequential\nfrom tensorflow.keras.models import Sequential, load_model\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D\n! pip install py7zr\nfrom tensorflow.keras import layers, models\nimport py7zr\nimport shutil\nfrom fastai.vision.all import *\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","execution":{"iopub.status.busy":"2023-10-14T18:55:17.713906Z","iopub.execute_input":"2023-10-14T18:55:17.714268Z","iopub.status.idle":"2023-10-14T18:55:42.554501Z","shell.execute_reply.started":"2023-10-14T18:55:17.714245Z","shell.execute_reply":"2023-10-14T18:55:42.553459Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from py7zr import unpack_7zarchive\n\n# Set directories\nINPUT_DIR = '/kaggle/input'\nTEMP_DIR = '/kaggle/temp'\nWORK_DIR = '/kaggle/working'\n","metadata":{"execution":{"iopub.status.busy":"2023-10-14T18:55:42.556438Z","iopub.execute_input":"2023-10-14T18:55:42.556758Z","iopub.status.idle":"2023-10-14T18:55:42.561193Z","shell.execute_reply.started":"2023-10-14T18:55:42.556728Z","shell.execute_reply":"2023-10-14T18:55:42.560214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check and configure GPU\nif tf.config.list_physical_devices('GPU'):\n    print(\"GPU is available\")\n    tf.config.experimental.set_memory_growth(tf.config.list_physical_devices('GPU')[0], True)\nelse:\n    print(\"GPU is not available\")","metadata":{"execution":{"iopub.status.busy":"2023-10-14T18:55:42.562404Z","iopub.execute_input":"2023-10-14T18:55:42.562943Z","iopub.status.idle":"2023-10-14T18:55:42.616406Z","shell.execute_reply.started":"2023-10-14T18:55:42.562902Z","shell.execute_reply":"2023-10-14T18:55:42.615506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Extract training data from 7z file\nshutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive)\nshutil.unpack_archive(os.path.join(INPUT_DIR, 'cifar-10/train.7z'), TEMP_DIR)","metadata":{"execution":{"iopub.status.busy":"2023-10-14T18:55:42.618829Z","iopub.execute_input":"2023-10-14T18:55:42.619368Z","iopub.status.idle":"2023-10-14T18:56:25.347915Z","shell.execute_reply.started":"2023-10-14T18:55:42.619338Z","shell.execute_reply":"2023-10-14T18:56:25.346982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load and preprocess data\ntrain_lbls = pd.read_csv(os.path.join(INPUT_DIR, \"cifar-10/trainLabels.csv\"))\nunique_classes = train_lbls['label'].unique()","metadata":{"execution":{"iopub.status.busy":"2023-10-14T18:56:25.349339Z","iopub.execute_input":"2023-10-14T18:56:25.349717Z","iopub.status.idle":"2023-10-14T18:56:25.410826Z","shell.execute_reply.started":"2023-10-14T18:56:25.349685Z","shell.execute_reply":"2023-10-14T18:56:25.409564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create directories for each class in train and valid folders\nfor subset in ['train', 'valid']:\n    subset_path = os.path.join(TEMP_DIR, subset)\n    if not os.path.exists(subset_path): os.mkdir(subset_path)\n    for class_name in unique_classes:\n        class_path = os.path.join(subset_path, class_name)\n        if not os.path.exists(class_path): os.mkdir(class_path)","metadata":{"execution":{"iopub.status.busy":"2023-10-14T18:56:25.413109Z","iopub.execute_input":"2023-10-14T18:56:25.413436Z","iopub.status.idle":"2023-10-14T18:56:25.948075Z","shell.execute_reply.started":"2023-10-14T18:56:25.413396Z","shell.execute_reply":"2023-10-14T18:56:25.946989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Distribute images into class-specific folders\nfor _, row in train_lbls.iterrows():\n    source_path = os.path.join(TEMP_DIR, 'train', f\"{row['id']}.png\")\n    target_folder = 'train' if np.random.random() <= 0.8 else 'valid'\n    target_path = os.path.join(TEMP_DIR, target_folder, row['label'], f\"{row['id']}.png\")\n    os.replace(source_path, target_path)","metadata":{"execution":{"iopub.status.busy":"2023-10-14T18:56:25.950057Z","iopub.execute_input":"2023-10-14T18:56:25.951449Z","iopub.status.idle":"2023-10-14T18:56:30.276782Z","shell.execute_reply.started":"2023-10-14T18:56:25.951406Z","shell.execute_reply":"2023-10-14T18:56:30.275849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load data, initialize and train the model\nfrom fastai.vision.all import aug_transforms\n\ndls = ImageDataLoaders.from_folder(\n    path=TEMP_DIR, \n    train='train', \n    valid='valid', \n    item_tfms=Resize(224), \n    #################################################\n    batch_tfms=[*aug_transforms(size=224, min_scale=0.75), Normalize.from_stats(*imagenet_stats)], # Adding augmentation and normalization\n    bs=64\n)\n################################\nlearn = cnn_learner(dls, resnet152, metrics=accuracy, cbs=EarlyStoppingCallback(monitor='valid_loss', min_delta=0.01, patience=3))\n\nlearn.fit_one_cycle(3, 3e-3)\nlearn.unfreeze()\nlearn.fit_one_cycle(5, lr_max=slice(1e-6, 3e-5))\n\nfrom fastai.vision.all import *\nimport matplotlib.pyplot as plt\n\n\n# Plot training and validation loss\nlearn.recorder.plot_loss()\n\n\n# Get values\nlosses = learn.recorder.losses\nvalues = learn.recorder.values\n\n# Plot loss\nplt.figure(figsize=(10,5))\nplt.plot(losses, label='Training Loss')\nplt.title('Training Loss')\nplt.xlabel('Batches Processed')\nplt.ylabel('Loss')\nplt.show()\n\n# Plot accuracy\nplt.figure(figsize=(10,5))\nplt.plot(values, label='Validation Accuracy')\nplt.title('Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.show()\n\n","metadata":{"execution":{"iopub.status.busy":"2023-10-14T18:56:30.278267Z","iopub.execute_input":"2023-10-14T18:56:30.278977Z","iopub.status.idle":"2023-10-14T20:01:10.392733Z","shell.execute_reply.started":"2023-10-14T18:56:30.278945Z","shell.execute_reply":"2023-10-14T20:01:10.391508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Print model summaryw\nfrom fastai.vision.all import *\n\nprint(learn.summary())","metadata":{"execution":{"iopub.status.busy":"2023-10-14T20:01:10.397172Z","iopub.execute_input":"2023-10-14T20:01:10.399332Z","iopub.status.idle":"2023-10-14T20:01:10.920978Z","shell.execute_reply.started":"2023-10-14T20:01:10.399296Z","shell.execute_reply":"2023-10-14T20:01:10.920088Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save the model \n#learn.save(os.path.join(WORK_DIR, 'vision_model'))\nlearn.save('/kaggle/working/cifar10_model_0.h5')","metadata":{"execution":{"iopub.status.busy":"2023-10-14T20:01:10.926662Z","iopub.execute_input":"2023-10-14T20:01:10.928739Z","iopub.status.idle":"2023-10-14T20:01:12.786730Z","shell.execute_reply.started":"2023-10-14T20:01:10.928704Z","shell.execute_reply":"2023-10-14T20:01:12.785809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Extract test data from 7z file\nshutil.unpack_archive(os.path.join(INPUT_DIR, 'cifar-10/test.7z'), TEMP_DIR)\n","metadata":{"execution":{"iopub.status.busy":"2023-10-14T20:01:12.790728Z","iopub.execute_input":"2023-10-14T20:01:12.792914Z","iopub.status.idle":"2023-10-14T20:17:45.120861Z","shell.execute_reply.started":"2023-10-14T20:01:12.792880Z","shell.execute_reply":"2023-10-14T20:17:45.119809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Make predictions on test set and prepare submission\ntest_path = os.path.join(TEMP_DIR, 'test')\ntest_files = [os.path.join(test_path, f) for f in os.listdir(test_path)]\ntest_dl = learn.dls.test_dl(test_files)\npreds, _ = learn.get_preds(dl=test_dl)\npredicted_classes = [learn.dls.vocab[i] for i in preds.argmax(dim=-1)]\n","metadata":{"execution":{"iopub.status.busy":"2023-10-14T20:17:45.122117Z","iopub.execute_input":"2023-10-14T20:17:45.122757Z","iopub.status.idle":"2023-10-14T20:36:48.101787Z","shell.execute_reply.started":"2023-10-14T20:17:45.122724Z","shell.execute_reply":"2023-10-14T20:36:48.100648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Create submission file\nsubmission = pd.DataFrame({'id': [int(f.split('/')[-1].split('.')[0]) for f in test_files], 'label': predicted_classes})\nsubmission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-10-14T20:36:48.104321Z","iopub.execute_input":"2023-10-14T20:36:48.105038Z","iopub.status.idle":"2023-10-14T20:36:48.661394Z","shell.execute_reply.started":"2023-10-14T20:36:48.105001Z","shell.execute_reply":"2023-10-14T20:36:48.660449Z"},"trusted":true},"execution_count":null,"outputs":[]}]}