{"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)\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","execution":{"iopub.status.busy":"2023-09-19T02:45:16.006817Z","iopub.execute_input":"2023-09-19T02:45:16.007200Z","iopub.status.idle":"2023-09-19T02:45:16.373258Z","shell.execute_reply.started":"2023-09-19T02:45:16.007173Z","shell.execute_reply":"2023-09-19T02:45:16.372027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T02:45:16.375715Z","iopub.execute_input":"2023-09-19T02:45:16.376215Z","iopub.status.idle":"2023-09-19T02:45:34.178642Z","shell.execute_reply.started":"2023-09-19T02:45:16.376180Z","shell.execute_reply":"2023-09-19T02:45:34.177501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport os\n\nimport itertools\nfrom py7zr import unpack_7zarchive\nimport shutil\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D,MaxPool2D,Dense,Flatten,Dropout,Input, AveragePooling2D, Activation,Conv2D, MaxPooling2D, BatchNormalization,Concatenate\nfrom tensorflow.keras.callbacks import EarlyStopping, TensorBoard\nfrom tensorflow.keras import regularizers, optimizers\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T02:45:34.181632Z","iopub.execute_input":"2023-09-19T02:45:34.182029Z","iopub.status.idle":"2023-09-19T02:45:43.058343Z","shell.execute_reply.started":"2023-09-19T02:45:34.181992Z","shell.execute_reply":"2023-09-19T02:45:43.057297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.register_unpack_format('7zip',['.7z'],unpack_7zarchive)\nshutil.unpack_archive('../input/cifar-10/train.7z', '/kaggle/temp/')","metadata":{"execution":{"iopub.status.busy":"2023-09-19T02:45:43.061332Z","iopub.execute_input":"2023-09-19T02:45:43.062171Z","iopub.status.idle":"2023-09-19T02:46:43.121904Z","shell.execute_reply.started":"2023-09-19T02:45:43.062132Z","shell.execute_reply":"2023-09-19T02:46:43.120833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_labels = pd.read_csv(\"../input/cifar-10/trainLabels.csv\", header=\"infer\")\n\nclasses = train_labels['label'].unique()\nprint(classes)","metadata":{"execution":{"iopub.status.busy":"2023-09-19T02:46:43.123598Z","iopub.execute_input":"2023-09-19T02:46:43.123973Z","iopub.status.idle":"2023-09-19T02:46:43.192500Z","shell.execute_reply.started":"2023-09-19T02:46:43.123940Z","shell.execute_reply":"2023-09-19T02:46:43.191307Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if not os.path.exists(\"/kaggle/temp/valid\"):\n    os.mkdir(\"/kaggle/temp/valid\")\n    \nparent_path_train = \"/kaggle/temp/train\"\nparent_path_valid = \"/kaggle/temp/valid\"\nparent_path_test = \"/kaggle/temp/test\"\n\nfor class1 in classes:\n    path_train = os.path.join(parent_path_train,class1)\n    if not os.path.exists(path_train):\n        os.mkdir(path_train)\n    path_valid = os.path.join(parent_path_valid,class1)\n    if not os.path.exists(path_valid):\n        os.mkdir(path_valid)\n        \nfor (int_ind,row) in train_labels.iterrows():\n    id = str(row[\"id\"])+\".png\"\n    source_path = os.path.join(parent_path_train,id)\n    \n    p=np.random.random()\n    if p<=0.8:\n        target_path = os.path.join(parent_path_train,row[\"label\"],id)\n        os.replace(source_path, target_path)\n    else:\n        target_path = os.path.join(parent_path_valid,row[\"label\"],id)\n        os.replace(source_path, target_path)","metadata":{"execution":{"iopub.status.busy":"2023-09-19T02:46:43.197472Z","iopub.execute_input":"2023-09-19T02:46:43.197914Z","iopub.status.idle":"2023-09-19T02:46:49.205861Z","shell.execute_reply.started":"2023-09-19T02:46:43.197873Z","shell.execute_reply":"2023-09-19T02:46:49.204719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Import necessary libraries for distributed training with TensorFlow\nimport numpy as np\nimport pandas as pd\nimport os\nimport tensorflow as tf  # Added TensorFlow import\n\n# Check available GPUs\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n    try:\n        for gpu in gpus:\n            tf.config.experimental.set_memory_growth(gpu, True)\n    except RuntimeError as e:\n        print(e)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T02:46:49.207536Z","iopub.execute_input":"2023-09-19T02:46:49.207937Z","iopub.status.idle":"2023-09-19T02:46:49.690923Z","shell.execute_reply.started":"2023-09-19T02:46:49.207901Z","shell.execute_reply":"2023-09-19T02:46:49.689723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a MirroredStrategy for two GPUs\nstrategy = tf.distribute.MirroredStrategy(devices=['/GPU:0', '/GPU:1'])\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T02:46:49.692390Z","iopub.execute_input":"2023-09-19T02:46:49.693087Z","iopub.status.idle":"2023-09-19T02:46:53.491940Z","shell.execute_reply.started":"2023-09-19T02:46:49.693049Z","shell.execute_reply":"2023-09-19T02:46:53.490937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    model = Sequential()\n\n    model.add(Conv2D(32, (3, 3), activation='relu', padding='same', input_shape=(32, 32, 3)))\n    model.add(BatchNormalization())\n\n    model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPool2D((2, 2)))\n    model.add(Dropout(0.2))\n\n    model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))\n    model.add(BatchNormalization())\n\n    model.add(Conv2D(64, (3, 3), activation='relu',padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPool2D((2, 2)))\n    model.add(Dropout(0.3))\n\n    model.add(Conv2D(128, (3, 3), activation='relu',  padding='same'))\n    model.add(BatchNormalization())\n\n    model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPool2D((2, 2)))\n    model.add(Dropout(0.4))\n\n    model.add(Flatten())\n    model.add(Dense(128, activation='relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.5))\n    model.add(Dense(10, activation='softmax'))","metadata":{"execution":{"iopub.status.busy":"2023-09-19T02:46:53.493605Z","iopub.execute_input":"2023-09-19T02:46:53.493998Z","iopub.status.idle":"2023-09-19T02:46:54.031639Z","shell.execute_reply.started":"2023-09-19T02:46:53.493963Z","shell.execute_reply":"2023-09-19T02:46:54.030587Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T02:46:54.035676Z","iopub.execute_input":"2023-09-19T02:46:54.036394Z","iopub.status.idle":"2023-09-19T02:46:54.065648Z","shell.execute_reply.started":"2023-09-19T02:46:54.036358Z","shell.execute_reply":"2023-09-19T02:46:54.064769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Data Augementation\ntrain_datagen = ImageDataGenerator(rotation_range=10,horizontal_flip=True,width_shift_range=0.1,height_shift_range=0.1)\n\nvalid_datagen = ImageDataGenerator()\n\ntrain_generator = train_datagen.flow_from_directory(directory='/kaggle/temp/train/', shuffle=True, target_size=(32,32),batch_size=128)\n\nvalid_generator = valid_datagen.flow_from_directory(directory='/kaggle/temp/valid/', shuffle=True, target_size=(32,32),batch_size=128)","metadata":{"execution":{"iopub.status.busy":"2023-09-19T02:46:54.066983Z","iopub.execute_input":"2023-09-19T02:46:54.067315Z","iopub.status.idle":"2023-09-19T02:46:55.403597Z","shell.execute_reply.started":"2023-09-19T02:46:54.067283Z","shell.execute_reply":"2023-09-19T02:46:55.402676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the training history\nhistory = model.fit(train_generator, epochs=25, validation_data=valid_generator, workers=8, use_multiprocessing=True, verbose=2)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T02:46:55.405113Z","iopub.execute_input":"2023-09-19T02:46:55.405490Z","iopub.status.idle":"2023-09-19T03:07:10.792062Z","shell.execute_reply.started":"2023-09-19T02:46:55.405458Z","shell.execute_reply":"2023-09-19T03:07:10.790859Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Plot training and validation loss\nplt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.legend()\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\n\n# Plot training and validation accuracy\nplt.subplot(1, 2, 2)\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.legend()\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-19T03:07:10.795072Z","iopub.execute_input":"2023-09-19T03:07:10.795446Z","iopub.status.idle":"2023-09-19T03:07:11.286330Z","shell.execute_reply.started":"2023-09-19T03:07:10.795410Z","shell.execute_reply":"2023-09-19T03:07:11.285304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('Model.h5')\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T03:07:11.287764Z","iopub.execute_input":"2023-09-19T03:07:11.288807Z","iopub.status.idle":"2023-09-19T03:07:11.455808Z","shell.execute_reply.started":"2023-09-19T03:07:11.288769Z","shell.execute_reply":"2023-09-19T03:07:11.454835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unpack_archive('/kaggle/input/cifar-10/test.7z','/kaggle/temp/test')\nshutil.unregister_unpack_format('7zip')","metadata":{"execution":{"iopub.status.busy":"2023-09-19T03:07:11.457379Z","iopub.execute_input":"2023-09-19T03:07:11.457717Z","iopub.status.idle":"2023-09-19T03:27:15.127565Z","shell.execute_reply.started":"2023-09-19T03:07:11.457686Z","shell.execute_reply":"2023-09-19T03:27:15.126475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_gen = test_datagen.flow_from_directory(directory='/kaggle/temp/test',target_size=(32,32),batch_size=64,class_mode=None,shuffle=False)\n\ntest_gen.reset()\npredictions_vecs = model.predict(test_gen)\npredictions_final = np.argmax(predictions_vecs, axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-09-19T03:27:15.128841Z","iopub.execute_input":"2023-09-19T03:27:15.129178Z","iopub.status.idle":"2023-09-19T03:29:46.461316Z","shell.execute_reply.started":"2023-09-19T03:27:15.129146Z","shell.execute_reply":"2023-09-19T03:29:46.460059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes = {value:key for (key,value) in train_generator.class_indices.items()}\nprint(classes)\n\npredicted_classes=np.empty(shape=300000,dtype=np.dtype('U20'))\n\nind=0\nfor i in predictions_final.tolist():\n    predicted_classes[ind]=classes[i]\n    ind=ind+1\n    \nfilenames_wo_ext = []\nfor fname in test_gen.filenames:\n    filenames_wo_ext.append(int(fname.split(sep=\"/\")[1].split(sep=\".\")[0])-1)\n\npredicted_classes_final = np.empty(shape=300000,dtype=np.dtype('U20'))\npredicted_classes_final[filenames_wo_ext]=predicted_classes","metadata":{"execution":{"iopub.status.busy":"2023-09-19T03:29:46.465126Z","iopub.execute_input":"2023-09-19T03:29:46.465484Z","iopub.status.idle":"2023-09-19T03:29:47.053068Z","shell.execute_reply.started":"2023-09-19T03:29:46.465455Z","shell.execute_reply":"2023-09-19T03:29:47.052005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.read_csv('../input/cifar-10/sampleSubmission.csv',header='infer')\nsubmission.info()\nsubmission['label'] = predicted_classes_final\nsubmission.to_csv('submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2023-09-19T03:29:47.054865Z","iopub.execute_input":"2023-09-19T03:29:47.055555Z","iopub.status.idle":"2023-09-19T03:29:47.937193Z","shell.execute_reply.started":"2023-09-19T03:29:47.055518Z","shell.execute_reply":"2023-09-19T03:29:47.936208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nimport seaborn as sns\n\n# Make predictions on validation data\nvalid_predictions = model.predict(valid_generator)\n\n# Get true labels\ntrue_labels = valid_generator.classes\n\n# Get predicted labels\npredicted_labels = np.argmax(valid_predictions, axis=1)\n\n# Create a confusion matrix\nconfusion_mat = confusion_matrix(true_labels, predicted_labels)\n\n# Plot the confusion matrix using a heatmap\nplt.figure(figsize=(10, 8))\nsns.heatmap(confusion_mat, annot=True, fmt='d', cmap='Blues', xticklabels=classes, yticklabels=classes)\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.title('Confusion Matrix')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-09-19T03:29:47.938682Z","iopub.execute_input":"2023-09-19T03:29:47.939382Z","iopub.status.idle":"2023-09-19T03:29:54.304177Z","shell.execute_reply.started":"2023-09-19T03:29:47.939346Z","shell.execute_reply":"2023-09-19T03:29:54.303181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}