{"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":"# !7za x /kaggle/input/cifar-10/test.7z -o/kaggle/working/\n# !7za x /kaggle/input/cifar-10/train.7z -o/kaggle/working/\n# # took ages","metadata":{"execution":{"iopub.status.busy":"2023-10-02T18:58:00.683353Z","iopub.execute_input":"2023-10-02T18:58:00.683701Z","iopub.status.idle":"2023-10-02T18:58:00.689282Z","shell.execute_reply.started":"2023-10-02T18:58:00.683671Z","shell.execute_reply":"2023-10-02T18:58:00.688387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\nimport os\n\n# Delete the test directory\nif os.path.exists(\"/kaggle/working/test/\"):\n    shutil.rmtree(\"/kaggle/working/test/\")\n\n# Delete the train directory\nif os.path.exists(\"/kaggle/working/train/\"):\n    shutil.rmtree(\"/kaggle/working/train/\")\n","metadata":{"execution":{"iopub.status.busy":"2023-10-02T18:58:05.676356Z","iopub.execute_input":"2023-10-02T18:58:05.676975Z","iopub.status.idle":"2023-10-02T18:58:18.942669Z","shell.execute_reply.started":"2023-10-02T18:58:05.676945Z","shell.execute_reply":"2023-10-02T18:58:18.941631Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr\n","metadata":{"execution":{"iopub.status.busy":"2023-10-02T18:58:38.925079Z","iopub.execute_input":"2023-10-02T18:58:38.925398Z","iopub.status.idle":"2023-10-02T18:58:50.996218Z","shell.execute_reply.started":"2023-10-02T18:58:38.925374Z","shell.execute_reply":"2023-10-02T18:58:50.995113Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import py7zr\n\n# with py7zr.SevenZipFile('/kaggle/input/cifar-10/test.7z', mode='r') as z:\n#     z.extractall(path=\"/kaggle/working/\")\n\n# with py7zr.SevenZipFile('/kaggle/input/cifar-10/train.7z', mode='r') as z:\n#     z.extractall(path=\"/kaggle/working/\")\n\n","metadata":{"execution":{"iopub.status.busy":"2023-10-02T18:59:02.134074Z","iopub.execute_input":"2023-10-02T18:59:02.134417Z","iopub.status.idle":"2023-10-02T19:12:41.500552Z","shell.execute_reply.started":"2023-10-02T18:59:02.134387Z","shell.execute_reply":"2023-10-02T19:12:41.499565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install numpy==1.22.0\n","metadata":{"execution":{"iopub.status.busy":"2023-10-03T04:29:19.973143Z","iopub.execute_input":"2023-10-03T04:29:19.973493Z","iopub.status.idle":"2023-10-03T04:29:35.851468Z","shell.execute_reply.started":"2023-10-03T04:29:19.973465Z","shell.execute_reply":"2023-10-03T04:29:35.850052Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\n# from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\n# why keras only\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom keras.optimizers import Adam\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau\n\n","metadata":{"execution":{"iopub.status.busy":"2023-10-04T02:39:09.711958Z","iopub.execute_input":"2023-10-04T02:39:09.712628Z","iopub.status.idle":"2023-10-04T02:39:09.719635Z","shell.execute_reply.started":"2023-10-04T02:39:09.712597Z","shell.execute_reply":"2023-10-04T02:39:09.718747Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"strategy = tf.distribute.MirroredStrategy()\n","metadata":{"execution":{"iopub.status.busy":"2023-10-04T02:39:15.042125Z","iopub.execute_input":"2023-10-04T02:39:15.042497Z","iopub.status.idle":"2023-10-04T02:39:15.051101Z","shell.execute_reply.started":"2023-10-04T02:39:15.042467Z","shell.execute_reply":"2023-10-04T02:39:15.049984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Number of devices: {}\".format(strategy.num_replicas_in_sync))","metadata":{"execution":{"iopub.status.busy":"2023-10-04T02:39:17.077888Z","iopub.execute_input":"2023-10-04T02:39:17.078240Z","iopub.status.idle":"2023-10-04T02:39:17.083641Z","shell.execute_reply.started":"2023-10-04T02:39:17.078212Z","shell.execute_reply":"2023-10-04T02:39:17.082627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = \"/kaggle/working/train/\"\ntest_dir = \"/kaggle/working/test/\"\n# df_train['id'] = df_train['id'].astype(str) + '.png'\n\n","metadata":{"execution":{"iopub.status.busy":"2023-10-04T02:39:22.936077Z","iopub.execute_input":"2023-10-04T02:39:22.936764Z","iopub.status.idle":"2023-10-04T02:39:22.941192Z","shell.execute_reply.started":"2023-10-04T02:39:22.936723Z","shell.execute_reply":"2023-10-04T02:39:22.939968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n# Load images using Keras's ImageDataGenerator\n\n# Data Augmentation\ndatagen = ImageDataGenerator(\n    rescale=1./255,          # Rescale pixel values to [0, 1]\n    validation_split=0.2,    # Reserve some data for validation\n    horizontal_flip=True,    # Random horizontal flip\n    width_shift_range=0.1,   # Horizontal shift\n    height_shift_range=0.1,  # Vertical shift\n    rotation_range=20,       # Random rotation between -20 to 20 degrees\n    zoom_range=0.15,         # Random zoom in the range [0.85, 1.15]\n    shear_range=0.15         # Shear Intensity\n)\n","metadata":{"execution":{"iopub.status.busy":"2023-10-03T04:30:06.879198Z","iopub.execute_input":"2023-10-03T04:30:06.879588Z","iopub.status.idle":"2023-10-03T04:30:06.884915Z","shell.execute_reply.started":"2023-10-03T04:30:06.879560Z","shell.execute_reply":"2023-10-03T04:30:06.883894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.read_csv('/kaggle/input/cifar-10/trainLabels.csv')\n\ndf_train['id'] = df_train['id'].astype(str) + '.png'\n\n\ntrain_generator = datagen.flow_from_dataframe(\n    df_train,\n    directory=train_dir,\n    x_col='id',\n    y_col='label',\n    target_size=(32, 32),\n    class_mode='categorical',\n    batch_size=64,\n    subset='training'\n)\n\nvalidation_generator = datagen.flow_from_dataframe(\n    df_train,\n    directory=train_dir,\n    x_col='id',\n    y_col='label',\n    target_size=(32, 32),\n    class_mode='categorical',\n    batch_size=64,\n    subset='validation'\n)\n","metadata":{"execution":{"iopub.status.busy":"2023-10-04T02:39:32.183623Z","iopub.execute_input":"2023-10-04T02:39:32.184033Z","iopub.status.idle":"2023-10-04T02:39:32.989679Z","shell.execute_reply.started":"2023-10-04T02:39:32.183987Z","shell.execute_reply":"2023-10-04T02:39:32.988853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# for memory\nimport gc\ndel df_train\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-10-03T04:30:14.659498Z","iopub.execute_input":"2023-10-03T04:30:14.660256Z","iopub.status.idle":"2023-10-03T04:30:14.883268Z","shell.execute_reply.started":"2023-10-03T04:30:14.660216Z","shell.execute_reply":"2023-10-03T04:30:14.882256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, BatchNormalization, MaxPooling2D, Dropout, Flatten, Dense\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.optimizers.schedules import ExponentialDecay\nfrom tensorflow.keras.regularizers import l2\n\nstrategy = tf.distribute.MirroredStrategy()\nprint('Number of devices: {}'.format(strategy.num_replicas_in_sync))\n\nwith strategy.scope():\n    model = Sequential([\n        # First block\n        Conv2D(32, (3,3), activation='relu', padding='same', input_shape=(32, 32, 3)),\n        BatchNormalization(),\n        Conv2D(32, (3,3), activation='relu', padding='same'),\n        BatchNormalization(),\n        MaxPooling2D(2,2),\n        Dropout(0.2),\n\n        # Second block\n        Conv2D(64, (3,3), activation='relu', padding='same'),\n        BatchNormalization(),\n        Conv2D(64, (3,3), activation='relu', padding='same'),\n        BatchNormalization(),\n        MaxPooling2D(2,2),\n        Dropout(0.3),\n\n        # Third block\n        Conv2D(128, (3,3), activation='relu', padding='same'),\n        BatchNormalization(),\n        Conv2D(128, (3,3), activation='relu', padding='same'),\n        BatchNormalization(),\n        MaxPooling2D(2,2),\n        Dropout(0.4),\n\n        # Fourth block\n        Conv2D(256, (3,3), activation='relu', padding='same'),\n        BatchNormalization(),\n        Conv2D(256, (3,3), activation='relu', padding='same'),\n        BatchNormalization(),\n        MaxPooling2D(2,2),\n        Dropout(0.4),\n\n        # Fully connected layers\n        Flatten(),\n        Dense(1024, activation='relu', kernel_regularizer=l2(0.01)),  # Increased to 1024 neurons\n        Dropout(0.5),\n        Dense(512, activation='relu', kernel_regularizer=l2(0.01)),\n        Dropout(0.5),\n        Dense(10, activation='softmax')\n    ])\n\n    # Model Summary\n    model.summary()\n\n    # Learning rate schedule\n    lr_schedule = ExponentialDecay(initial_learning_rate=0.003, decay_steps=10000, decay_rate=0.9)\n    optimizer = Adam(learning_rate=lr_schedule)\n\n    model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n\n","metadata":{"execution":{"iopub.status.busy":"2023-10-04T02:40:09.450210Z","iopub.execute_input":"2023-10-04T02:40:09.450534Z","iopub.status.idle":"2023-10-04T02:40:09.933255Z","shell.execute_reply.started":"2023-10-04T02:40:09.450509Z","shell.execute_reply":"2023-10-04T02:40:09.932418Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import ModelCheckpoint\n\n# Specify where you want to save the model weights\ncheckpoint_filepath = '/kaggle/working/best_weightshigh4blockFifteen.h5'\n\ncheckpoint = ModelCheckpoint(filepath=checkpoint_filepath, \n                             monitor='val_accuracy', \n                             verbose=1, \n                             save_best_only=True, \n                             mode='max')\n#","metadata":{"execution":{"iopub.status.busy":"2023-10-04T02:27:32.084113Z","iopub.execute_input":"2023-10-04T02:27:32.084448Z","iopub.status.idle":"2023-10-04T02:27:32.090403Z","shell.execute_reply.started":"2023-10-04T02:27:32.084420Z","shell.execute_reply":"2023-10-04T02:27:32.089524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Here, I statred with 50 epochs and run the trainig in different sessions untill i reach 0.9","metadata":{}},{"cell_type":"code","source":"model.load_weights(\"/kaggle/working/best_weightshigh4block.h5\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_generator,  \n                    validation_data=validation_generator, \n                    epochs=30, # run for additianl 30 epoch\n                    callbacks=[checkpoint])\n#50 #20 #10 #10 #10 #10 #10 #10 #10 #20 #10 #15 #20 ---- #20 #30","metadata":{"execution":{"iopub.status.busy":"2023-10-03T22:44:35.541424Z","iopub.execute_input":"2023-10-03T22:44:35.541777Z","iopub.status.idle":"2023-10-03T23:12:17.121078Z","shell.execute_reply.started":"2023-10-03T22:44:35.541753Z","shell.execute_reply":"2023-10-03T23:12:17.120128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clear Memory\ndel train_generator, validation_generator\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-10-03T04:30:38.353069Z","iopub.execute_input":"2023-10-03T04:30:38.353410Z","iopub.status.idle":"2023-10-03T04:30:38.540985Z","shell.execute_reply.started":"2023-10-03T04:30:38.353383Z","shell.execute_reply":"2023-10-03T04:30:38.539794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nmodel.load_weights(\"/kaggle/working/best_weightshigh4blockTHIRTEEN.h5\")","metadata":{"execution":{"iopub.status.busy":"2023-10-04T02:40:20.638640Z","iopub.execute_input":"2023-10-04T02:40:20.639736Z","iopub.status.idle":"2023-10-04T02:40:20.788438Z","shell.execute_reply.started":"2023-10-04T02:40:20.639674Z","shell.execute_reply":"2023-10-04T02:40:20.787518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n###############################################################\nimport os\n# Predict on Test Data in Batches\ntest_files = os.listdir(test_dir)\n\n# batch_size = 1024\nbatch_size = 8192\npredicted_classes = []\n\nprint(f\"Total test files: {len(test_files)}\")\n\nfor i in range(0, len(test_files), batch_size):\n    print(f\"Processing images {i} to {i+batch_size}...\")\n    \n    batch_files = test_files[i:i+batch_size]\n    test_images = [load_img(test_dir + fname, target_size=(32,32)) for fname in batch_files]\n    test_array = np.array([img_to_array(img) for img in test_images]) / 255.0\n\n    batch_predictions = model.predict(test_array)\n    batch_labels = np.argmax(batch_predictions, axis=1)\n    predicted_classes.extend(batch_labels)\n                                         ## check\n#     # Freeing up memory\n#     del test_images, test_array, batch_predictions\n#     gc.collect()\n\npredicted_classes = np.array(predicted_classes)\nprint(f\"Total predicted classes: {len(predicted_classes)}\")\n\n# rest of the code \n\n# Assuming these are the class names in the order you trained your model\nclass_names = [\"airplane\", \"automobile\", \"bird\", \"cat\", \"deer\", \"dog\", \"frog\", \"horse\", \"ship\", \"truck\"]\n\n# Map the numerical labels to class names\npredicted_class_names = [class_names[label] for label in predicted_classes]\n\n# Create CSV for Submission\nsubmission_df = pd.DataFrame({\n    'id': [int(fname.split('.')[0]) for fname in test_files],  # Convert to integer to ensure proper format\n    'label': predicted_class_names\n})\n\n# Sort the dataframe by 'id' column for cleaner output\nsubmission_df = submission_df.sort_values(by='id')\n\nsubmission_df.to_csv(\"/kaggle/working/submission024blockTHERTEEN.csv.csv\", index=False)\n","metadata":{"execution":{"iopub.status.busy":"2023-10-04T02:40:25.200899Z","iopub.execute_input":"2023-10-04T02:40:25.201229Z","iopub.status.idle":"2023-10-04T02:42:47.807116Z","shell.execute_reply.started":"2023-10-04T02:40:25.201201Z","shell.execute_reply":"2023-10-04T02:42:47.806132Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nimport random\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\n# from keras.preprocessing.image import load_img\n# from keras.preprocessing import image\n\n# Load submission file\nsubmission_df = pd.read_csv(\"/kaggle/working/submission02.csv\")\n\n# List all images in the test directory\nall_images = os.listdir(\"/kaggle/working/test\")\n# Randomly select an image name\nimage_name = random.choice(all_images)\n\n# Define path\nimage_path = os.path.join(\"/kaggle/working/test\", image_name)\n\n# Display the image\n# img = image.load_img(image_path)\nimg = load_img(image_path)\nplt.imshow(img)\nplt.title(image_name)\nplt.axis('off')\nplt.show()\n\n# Check prediction\n# image_id = os.path.splitext(image_name)[0]\nimage_id = int(os.path.splitext(image_name)[0])\nif image_id in submission_df['id'].values:\n    predicted_class_idx = submission_df[submission_df['id'] == image_id]['label'].values[0]\n    predicted_class_name = class_names[predicted_class_idx]  # assuming you have `class_names` list defined as before\n    print(f\"Predicted class for {image_name} is: {predicted_class_name}\")\nelse:\n    print(f\"Image {image_id} is not in the submission file.\")\n","metadata":{"execution":{"iopub.status.busy":"2023-10-03T04:35:31.997729Z","iopub.execute_input":"2023-10-03T04:35:31.998099Z","iopub.status.idle":"2023-10-03T04:35:32.422932Z","shell.execute_reply.started":"2023-10-03T04:35:31.998072Z","shell.execute_reply":"2023-10-03T04:35:32.421643Z"},"trusted":true},"execution_count":null,"outputs":[]}]}