{"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 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-09-02T08:00:54.782256Z","iopub.execute_input":"2022-09-02T08:00:54.782764Z","iopub.status.idle":"2022-09-02T08:01:00.622030Z","shell.execute_reply.started":"2022-09-02T08:00:54.782682Z","shell.execute_reply":"2022-09-02T08:01:00.620862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2022-09-02T08:01:00.624205Z","iopub.execute_input":"2022-09-02T08:01:00.624861Z","iopub.status.idle":"2022-09-02T08:01:14.308660Z","shell.execute_reply.started":"2022-09-02T08:01:00.624821Z","shell.execute_reply":"2022-09-02T08:01:14.307302Z"},"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-09-02T08:01:14.311284Z","iopub.execute_input":"2022-09-02T08:01:14.311944Z","iopub.status.idle":"2022-09-02T08:02:00.340617Z","shell.execute_reply.started":"2022-09-02T08:01:14.311894Z","shell.execute_reply":"2022-09-02T08:02:00.339195Z"},"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-09-02T08:02:00.343542Z","iopub.execute_input":"2022-09-02T08:02:00.344128Z","iopub.status.idle":"2022-09-02T08:02:00.451518Z","shell.execute_reply.started":"2022-09-02T08:02:00.344074Z","shell.execute_reply":"2022-09-02T08:02:00.450448Z"},"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":"2022-09-02T08:02:00.456291Z","iopub.execute_input":"2022-09-02T08:02:00.457518Z","iopub.status.idle":"2022-09-02T08:02:10.538334Z","shell.execute_reply.started":"2022-09-02T08:02:00.457449Z","shell.execute_reply":"2022-09-02T08:02:10.537167Z"},"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-09-02T08:02:10.544089Z","iopub.execute_input":"2022-09-02T08:02:10.546968Z","iopub.status.idle":"2022-09-02T08:02:13.000895Z","shell.execute_reply.started":"2022-09-02T08:02:10.546924Z","shell.execute_reply":"2022-09-02T08:02:12.999474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from 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-09-02T08:02:13.004730Z","iopub.execute_input":"2022-09-02T08:02:13.005177Z","iopub.status.idle":"2022-09-02T08:02:15.831071Z","shell.execute_reply.started":"2022-09-02T08:02:13.005130Z","shell.execute_reply":"2022-09-02T08:02:15.829849Z"},"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\ndef define_model():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation='relu', padding='same', input_shape=(32, 32, 3)))\n\n    model.add(BatchNormalization())\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    model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))\n    model.add(BatchNormalization())\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    model.add(Conv2D(128, (3, 3), activation='relu',  padding='same'))\n    model.add(BatchNormalization())\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    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'))\n\n    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n    return model\n\nmodel = define_model()\nprint (\"Model Done\")","metadata":{"execution":{"iopub.status.busy":"2022-09-02T08:02:15.836488Z","iopub.execute_input":"2022-09-02T08:02:15.839350Z","iopub.status.idle":"2022-09-02T08:02:19.730856Z","shell.execute_reply.started":"2022-09-02T08:02:15.839308Z","shell.execute_reply":"2022-09-02T08:02:19.729745Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(train_generator, epochs=20, validation_data=valid_generator,workers=8,use_multiprocessing=True,verbose=2)","metadata":{"execution":{"iopub.status.busy":"2022-09-02T08:02:19.732572Z","iopub.execute_input":"2022-09-02T08:02:19.732930Z","iopub.status.idle":"2022-09-02T08:07:58.836725Z","shell.execute_reply.started":"2022-09-02T08:02:19.732886Z","shell.execute_reply":"2022-09-02T08:07:58.835418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-09-02T08:07:58.841058Z","iopub.execute_input":"2022-09-02T08:07:58.841399Z","iopub.status.idle":"2022-09-02T08:07:58.850157Z","shell.execute_reply.started":"2022-09-02T08:07:58.841369Z","shell.execute_reply":"2022-09-02T08:07:58.849151Z"},"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-09-02T08:07:58.851449Z","iopub.execute_input":"2022-09-02T08:07:58.852199Z","iopub.status.idle":"2022-09-02T08:22:35.965464Z","shell.execute_reply.started":"2022-09-02T08:07:58.852161Z","shell.execute_reply":"2022-09-02T08:22:35.964186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_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-09-02T08:22:35.967423Z","iopub.execute_input":"2022-09-02T08:22:35.967969Z","iopub.status.idle":"2022-09-02T08:22:47.500586Z","shell.execute_reply.started":"2022-09-02T08:22:35.967922Z","shell.execute_reply":"2022-09-02T08:22:47.499576Z"},"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-09-02T08:22:47.502203Z","iopub.execute_input":"2022-09-02T08:22:47.502590Z","iopub.status.idle":"2022-09-02T08:24:05.519562Z","shell.execute_reply.started":"2022-09-02T08:22:47.502554Z","shell.execute_reply":"2022-09-02T08:24:05.518216Z"},"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-09-02T08:24:05.521707Z","iopub.execute_input":"2022-09-02T08:24:05.523033Z","iopub.status.idle":"2022-09-02T08:24:06.176700Z","shell.execute_reply.started":"2022-09-02T08:24:05.522966Z","shell.execute_reply":"2022-09-02T08:24:06.175694Z"},"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-09-02T08:24:06.178293Z","iopub.execute_input":"2022-09-02T08:24:06.178652Z","iopub.status.idle":"2022-09-02T08:24:06.292744Z","shell.execute_reply.started":"2022-09-02T08:24:06.178616Z","shell.execute_reply":"2022-09-02T08:24:06.291793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['label'] = predicted_classes_final\nsub.to_csv('submission.csv',index=False)\nsub","metadata":{"execution":{"iopub.status.busy":"2022-09-02T08:24:06.294352Z","iopub.execute_input":"2022-09-02T08:24:06.294768Z","iopub.status.idle":"2022-09-02T08:24:06.644178Z","shell.execute_reply.started":"2022-09-02T08:24:06.294730Z","shell.execute_reply":"2022-09-02T08:24:06.643138Z"},"trusted":true},"execution_count":null,"outputs":[]}]}