{"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":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nfrom tensorflow import keras\nimport tensorflow as tf\nfrom keras import Sequential\nfrom keras.layers import Dense, Conv2D, MaxPooling2D, Activation, BatchNormalization, Flatten, Dropout\nfrom keras.utils.np_utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\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))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-08-25T16:55:30.738876Z","iopub.execute_input":"2022-08-25T16:55:30.739979Z","iopub.status.idle":"2022-08-25T16:55:36.172136Z","shell.execute_reply.started":"2022-08-25T16:55:30.739834Z","shell.execute_reply":"2022-08-25T16:55:36.171196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr\n\n","metadata":{"execution":{"iopub.status.busy":"2022-08-25T16:55:46.261779Z","iopub.execute_input":"2022-08-25T16:55:46.262607Z","iopub.status.idle":"2022-08-25T16:56:00.185794Z","shell.execute_reply.started":"2022-08-25T16:55:46.262566Z","shell.execute_reply":"2022-08-25T16:56:00.184608Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\nfrom py7zr import unpack_7zarchive\nshutil.register_unpack_format('7zip',['.7z'],unpack_7zarchive)\nshutil.unpack_archive('../input/cifar-10/train.7z', '/kaggle/temp/')","metadata":{"execution":{"iopub.status.busy":"2022-08-25T16:56:06.322116Z","iopub.execute_input":"2022-08-25T16:56:06.323127Z","iopub.status.idle":"2022-08-25T16:56:51.737701Z","shell.execute_reply.started":"2022-08-25T16:56:06.323079Z","shell.execute_reply":"2022-08-25T16:56:51.736470Z"},"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":"2022-08-25T16:57:01.427715Z","iopub.execute_input":"2022-08-25T16:57:01.428318Z","iopub.status.idle":"2022-08-25T16:57:01.501424Z","shell.execute_reply.started":"2022-08-25T16:57:01.428269Z","shell.execute_reply":"2022-08-25T16:57:01.498102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Divide the training set into training and validation dataset\n\nif 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":"2022-08-25T16:58:27.264895Z","iopub.execute_input":"2022-08-25T16:58:27.265863Z","iopub.status.idle":"2022-08-25T16:58:32.275866Z","shell.execute_reply.started":"2022-08-25T16:58:27.265829Z","shell.execute_reply":"2022-08-25T16:58:32.274831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /kaggle/temp/valid/airplane/* | wc\n!ls /kaggle/temp/train","metadata":{"execution":{"iopub.status.busy":"2022-08-25T16:59:05.207338Z","iopub.execute_input":"2022-08-25T16:59:05.208015Z","iopub.status.idle":"2022-08-25T16:59:07.200093Z","shell.execute_reply.started":"2022-08-25T16:59:05.207977Z","shell.execute_reply":"2022-08-25T16:59:07.198830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Performing Data Augmentation\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator()\nvalid_datagen = ImageDataGenerator()\n\ntrain_generator = train_datagen.flow_from_directory(directory='/kaggle/temp/train/', shuffle=True, target_size=(32,32),batch_size=64)\nvalid_generator = valid_datagen.flow_from_directory(directory='/kaggle/temp/valid/', shuffle=True, target_size=(32,32),batch_size=64)","metadata":{"execution":{"iopub.status.busy":"2022-08-25T16:59:33.850912Z","iopub.execute_input":"2022-08-25T16:59:33.851344Z","iopub.status.idle":"2022-08-25T16:59:35.377617Z","shell.execute_reply.started":"2022-08-25T16:59:33.851304Z","shell.execute_reply":"2022-08-25T16:59:35.376555Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"type(train_generator)","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:00:01.660359Z","iopub.execute_input":"2022-08-25T17:00:01.661370Z","iopub.status.idle":"2022-08-25T17:00:01.671979Z","shell.execute_reply.started":"2022-08-25T17:00:01.661333Z","shell.execute_reply":"2022-08-25T17:00:01.670609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nimport tensorflow.keras\nfrom tensorflow.keras.layers import Dense, MaxPool2D, Conv2D, Dropout, Flatten, GlobalAveragePooling2D, BatchNormalization, Activation, MaxPooling2D\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.utils import to_categorical\n\n#Defining the model architecture\ndef define_model():\n    model = Sequential()\n    \n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(32, 32, 3)))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D((2, 2)))\n    \n    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D((2, 2)))\n    \n    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D((2, 2)))\n    \n    model.add(Flatten())\n    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dense(10, activation='softmax'))\n    # compile model\n    #opt = SGD(lr=0.001, momentum=0.9,'adam')\n    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n    return model\n\n\nmodel = define_model()\nprint('Code Segment Running: Done')","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:01:12.375061Z","iopub.execute_input":"2022-08-25T17:01:12.375692Z","iopub.status.idle":"2022-08-25T17:01:15.484947Z","shell.execute_reply.started":"2022-08-25T17:01:12.375659Z","shell.execute_reply":"2022-08-25T17:01:15.483966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(train_generator,epochs=10, 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)","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:02:09.778311Z","iopub.execute_input":"2022-08-25T17:02:09.779766Z","iopub.status.idle":"2022-08-25T17:04:55.245176Z","shell.execute_reply.started":"2022-08-25T17:02:09.779720Z","shell.execute_reply":"2022-08-25T17:04:55.243850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:05:49.614410Z","iopub.execute_input":"2022-08-25T17:05:49.614897Z","iopub.status.idle":"2022-08-25T17:05:49.631520Z","shell.execute_reply.started":"2022-08-25T17:05:49.614851Z","shell.execute_reply":"2022-08-25T17:05:49.630278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nmodel_path = \"/kaggle/temp/model\"\nif not os.path.exists(model_path):\n    os.mkdir(model_path)\nmodel.save(model_path)","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:06:19.910869Z","iopub.execute_input":"2022-08-25T17:06:19.911244Z","iopub.status.idle":"2022-08-25T17:06:21.920487Z","shell.execute_reply.started":"2022-08-25T17:06:19.911212Z","shell.execute_reply":"2022-08-25T17:06:21.919504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow import keras\nmodel = keras.models.load_model(model_path)","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:06:50.728056Z","iopub.execute_input":"2022-08-25T17:06:50.729057Z","iopub.status.idle":"2022-08-25T17:06:51.639498Z","shell.execute_reply.started":"2022-08-25T17:06:50.729020Z","shell.execute_reply":"2022-08-25T17:06:51.638525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Unpack the test dataset\nshutil.unpack_archive('/kaggle/input/cifar-10/test.7z','/kaggle/temp/test')\nshutil.unregister_unpack_format('7zip')","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:07:11.623685Z","iopub.execute_input":"2022-08-25T17:07:11.624046Z","iopub.status.idle":"2022-08-25T17:22:03.175579Z","shell.execute_reply.started":"2022-08-25T17:07:11.624015Z","shell.execute_reply":"2022-08-25T17:22:03.174306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /kaggle/temp/test/ |wc -l","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:22:43.824342Z","iopub.execute_input":"2022-08-25T17:22:43.824727Z","iopub.status.idle":"2022-08-25T17:22:44.889016Z","shell.execute_reply.started":"2022-08-25T17:22:43.824695Z","shell.execute_reply":"2022-08-25T17:22:44.887783Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Perform preprocessing on test data\ntest_datagen = ImageDataGenerator()\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":"2022-08-25T17:23:24.441224Z","iopub.execute_input":"2022-08-25T17:23:24.441658Z","iopub.status.idle":"2022-08-25T17:23:30.556538Z","shell.execute_reply.started":"2022-08-25T17:23:24.441616Z","shell.execute_reply":"2022-08-25T17:23:30.555596Z"},"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":"2022-08-25T17:24:00.355086Z","iopub.execute_input":"2022-08-25T17:24:00.355699Z","iopub.status.idle":"2022-08-25T17:25:10.767941Z","shell.execute_reply.started":"2022-08-25T17:24:00.355664Z","shell.execute_reply":"2022-08-25T17:25:10.766937Z"},"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":"2022-08-25T17:26:07.853244Z","iopub.execute_input":"2022-08-25T17:26:07.853631Z","iopub.status.idle":"2022-08-25T17:26:08.240302Z","shell.execute_reply.started":"2022-08-25T17:26:07.853596Z","shell.execute_reply":"2022-08-25T17:26:08.239329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv('../input/cifar-10/sampleSubmission.csv',header='infer')\nsub.info()","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:26:32.715457Z","iopub.execute_input":"2022-08-25T17:26:32.716147Z","iopub.status.idle":"2022-08-25T17:26:32.887667Z","shell.execute_reply.started":"2022-08-25T17:26:32.716101Z","shell.execute_reply":"2022-08-25T17:26:32.886615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['label'] = predicted_classes_final\nsub.to_csv('submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:26:58.861547Z","iopub.execute_input":"2022-08-25T17:26:58.862368Z","iopub.status.idle":"2022-08-25T17:26:59.192369Z","shell.execute_reply.started":"2022-08-25T17:26:58.862328Z","shell.execute_reply":"2022-08-25T17:26:59.190962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.read_csv('submission.csv')\nprint(data)","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:27:39.554583Z","iopub.execute_input":"2022-08-25T17:27:39.555376Z","iopub.status.idle":"2022-08-25T17:27:39.617777Z","shell.execute_reply.started":"2022-08-25T17:27:39.555337Z","shell.execute_reply":"2022-08-25T17:27:39.616579Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predicted_classes_final[1:10]\nmodel.save('model')","metadata":{"execution":{"iopub.status.busy":"2022-08-25T17:27:59.075344Z","iopub.execute_input":"2022-08-25T17:27:59.075722Z","iopub.status.idle":"2022-08-25T17:28:00.992221Z","shell.execute_reply.started":"2022-08-25T17:27:59.075689Z","shell.execute_reply":"2022-08-25T17:28:00.991211Z"},"trusted":true},"execution_count":null,"outputs":[]}]}