{"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-17T19:06:39.370921Z","iopub.execute_input":"2023-09-17T19:06:39.371322Z","iopub.status.idle":"2023-09-17T19:06:39.745270Z","shell.execute_reply.started":"2023-09-17T19:06:39.371293Z","shell.execute_reply":"2023-09-17T19:06:39.744261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2023-09-17T19:06:44.032038Z","iopub.execute_input":"2023-09-17T19:06:44.032519Z","iopub.status.idle":"2023-09-17T19:07:01.749154Z","shell.execute_reply.started":"2023-09-17T19:06:44.032487Z","shell.execute_reply":"2023-09-17T19:07:01.748015Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from py7zr import unpack_7zarchive\nimport shutil\nshutil.register_unpack_format('7zip',['.7z'],unpack_7zarchive)","metadata":{"execution":{"iopub.status.busy":"2023-09-17T19:07:07.714337Z","iopub.execute_input":"2023-09-17T19:07:07.714743Z","iopub.status.idle":"2023-09-17T19:07:07.915238Z","shell.execute_reply.started":"2023-09-17T19:07:07.714710Z","shell.execute_reply":"2023-09-17T19:07:07.914276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unpack_archive('../input/cifar-10/train.7z', '/kaggle/temp/')","metadata":{"execution":{"iopub.status.busy":"2023-09-17T19:07:10.914442Z","iopub.execute_input":"2023-09-17T19:07:10.915361Z","iopub.status.idle":"2023-09-17T19:08:09.424399Z","shell.execute_reply.started":"2023-09-17T19:07:10.915316Z","shell.execute_reply":"2023-09-17T19:08:09.423171Z"},"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-17T19:08:13.337184Z","iopub.execute_input":"2023-09-17T19:08:13.337538Z","iopub.status.idle":"2023-09-17T19:08:13.401491Z","shell.execute_reply.started":"2023-09-17T19:08:13.337508Z","shell.execute_reply":"2023-09-17T19:08:13.400400Z"},"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-17T19:08:16.117393Z","iopub.execute_input":"2023-09-17T19:08:16.118132Z","iopub.status.idle":"2023-09-17T19:08:21.947726Z","shell.execute_reply.started":"2023-09-17T19:08:16.118087Z","shell.execute_reply":"2023-09-17T19:08:21.946770Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install keras\nfrom tensorflow import keras \nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nimport os\nimport numpy as np\nimport seaborn as sns\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix, classification_report\nimport itertools\nimport os\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.layers import Dense, Dropout, Activation,Flatten,Conv2D, MaxPooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.datasets import cifar10 ","metadata":{"execution":{"iopub.status.busy":"2023-09-17T19:08:25.303487Z","iopub.execute_input":"2023-09-17T19:08:25.303887Z","iopub.status.idle":"2023-09-17T19:08:52.639686Z","shell.execute_reply.started":"2023-09-17T19:08:25.303857Z","shell.execute_reply":"2023-09-17T19:08:52.638294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models\n\n# Detect GPUs, if available\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n    try:\n        # Currently, memory growth needs to be the same across GPUs\n        for gpu in gpus:\n            tf.config.experimental.set_memory_growth(gpu, True)\n        logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n        print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n    except RuntimeError as e:\n        print(e)\n\n# Create and compile the model\ndef create_model():\n    model = models.Sequential([\n        layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),\n        layers.MaxPooling2D((2, 2)),\n        layers.Conv2D(64, (3, 3), activation='relu'),\n        layers.MaxPooling2D((2, 2)),\n        layers.Conv2D(64, (3, 3), activation='relu'),\n        layers.Flatten(),\n        layers.Dense(64, activation='relu'),\n        layers.Dense(10)\n    ])\n    return model\n\n# Define the MirroredStrategy for two GPUs\nstrategy = tf.distribute.MirroredStrategy(devices=['/GPU:0', '/GPU:1'])\n\nprint(\"Number of devices: {}\".format(strategy.num_replicas_in_sync))\n\n# Create and compile the model within the MirroredStrategy scope\nwith strategy.scope():\n    model = create_model()\n    model.compile(optimizer='adam',\n                  loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),\n                  metrics=['accuracy'])\n    \ntrain_datagen = ImageDataGenerator(featurewise_center=False,\n                             samplewise_center=False,\n                             featurewise_std_normalization=False,\n                             samplewise_std_normalization=False,\n                             zca_whitening=False,\n                             rotation_range=10,\n                             zoom_range=0.1,\n                             width_shift_range=0.1,\n                             height_shift_range=0.1,\n                             horizontal_flip=False,\n                             vertical_flip=False,\n                             rescale=1./255)\nvalid_datagen = ImageDataGenerator()\n\ntrain_generator = train_datagen.flow_from_directory(directory='/kaggle/temp/train/', shuffle=True, target_size=(32,32),batch_size=256)\nvalid_generator = valid_datagen.flow_from_directory(directory='/kaggle/temp/valid/', shuffle=True, target_size=(32,32),batch_size=256)\n\n# Train the model using MirroredStrategy\nmodel.fit(train_generator,epochs=20, validation_data=valid_generator,steps_per_epoch=train_generator.n//train_generator.batch_size,\n         validation_steps= valid_generator.n//valid_generator.batch_size,workers=8,use_multiprocessing=True)\n\n# Save the model\nmodel.save('/kaggle/working/my_model.h5')\n","metadata":{"execution":{"iopub.status.busy":"2023-09-17T19:09:00.680788Z","iopub.execute_input":"2023-09-17T19:09:00.681379Z","iopub.status.idle":"2023-09-17T19:26:04.553236Z","shell.execute_reply.started":"2023-09-17T19:09:00.681347Z","shell.execute_reply":"2023-09-17T19:26:04.552062Z"},"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-17T19:26:13.272472Z","iopub.execute_input":"2023-09-17T19:26:13.273651Z","iopub.status.idle":"2023-09-17T19:46:15.719618Z","shell.execute_reply.started":"2023-09-17T19:26:13.273602Z","shell.execute_reply":"2023-09-17T19:46:15.718526Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2023-09-17T19:46:32.018494Z","iopub.execute_input":"2023-09-17T19:46:32.019189Z","iopub.status.idle":"2023-09-17T19:46:40.067022Z","shell.execute_reply.started":"2023-09-17T19:46:32.019157Z","shell.execute_reply":"2023-09-17T19:46:40.066004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_gen.reset()\npredictions_vecs = model.predict(test_gen)\n\npredictions_final = np.argmax(predictions_vecs, axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-09-17T19:46:57.885863Z","iopub.execute_input":"2023-09-17T19:46:57.886218Z","iopub.status.idle":"2023-09-17T19:49:15.087681Z","shell.execute_reply.started":"2023-09-17T19:46:57.886186Z","shell.execute_reply":"2023-09-17T19:49:15.085856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(type(train_generator.class_indices))\nprint(train_generator.class_indices)\n\nclasses = {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-17T19:49:18.595050Z","iopub.execute_input":"2023-09-17T19:49:18.595420Z","iopub.status.idle":"2023-09-17T19:49:19.156404Z","shell.execute_reply.started":"2023-09-17T19:49:18.595388Z","shell.execute_reply":"2023-09-17T19:49:19.155292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv('../input/cifar-10/sampleSubmission.csv',header='infer')\nsub.info()\nsub['label'] = predicted_classes_final\nsub.to_csv('submission.csv',index=False)\nsub","metadata":{"execution":{"iopub.status.busy":"2023-09-17T19:49:24.511264Z","iopub.execute_input":"2023-09-17T19:49:24.511694Z","iopub.status.idle":"2023-09-17T19:49:25.693705Z","shell.execute_reply.started":"2023-09-17T19:49:24.511658Z","shell.execute_reply":"2023-09-17T19:49:25.692512Z"},"trusted":true},"execution_count":null,"outputs":[]}]}