{"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":"2022-09-01T08:00:41.696739Z","iopub.execute_input":"2022-09-01T08:00:41.697088Z","iopub.status.idle":"2022-09-01T08:00:41.731085Z","shell.execute_reply.started":"2022-09-01T08:00:41.697004Z","shell.execute_reply":"2022-09-01T08:00:41.730027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Importing libraries","metadata":{}},{"cell_type":"code","source":"\nimport os\n\nimport itertools\nimport os\n","metadata":{"execution":{"iopub.status.busy":"2022-09-01T08:00:41.734122Z","iopub.execute_input":"2022-09-01T08:00:41.735039Z","iopub.status.idle":"2022-09-01T08:00:41.740289Z","shell.execute_reply.started":"2022-09-01T08:00:41.734986Z","shell.execute_reply":"2022-09-01T08:00:41.738928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr\n","metadata":{"execution":{"iopub.status.busy":"2022-09-01T08:00:41.742072Z","iopub.execute_input":"2022-09-01T08:00:41.742571Z","iopub.status.idle":"2022-09-01T08:00:58.775747Z","shell.execute_reply.started":"2022-09-01T08:00:41.742525Z","shell.execute_reply":"2022-09-01T08:00:58.774346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Extracting training images","metadata":{}},{"cell_type":"code","source":"from py7zr import unpack_7zarchive\nimport shutil\nshutil.register_unpack_format('7zip',['.7z'],unpack_7zarchive)\nshutil.unpack_archive('../input/cifar-10/train.7z', '/kaggle/temp/')\n","metadata":{"execution":{"iopub.status.busy":"2022-09-01T08:00:58.779674Z","iopub.execute_input":"2022-09-01T08:00:58.780297Z","iopub.status.idle":"2022-09-01T08:01:46.844411Z","shell.execute_reply.started":"2022-09-01T08:00:58.780252Z","shell.execute_reply":"2022-09-01T08:01:46.843323Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels=pd.read_csv('/kaggle/input/cifar-10/trainLabels.csv')\nlabels","metadata":{"execution":{"iopub.status.busy":"2022-09-01T08:01:46.858055Z","iopub.execute_input":"2022-09-01T08:01:46.858689Z","iopub.status.idle":"2022-09-01T08:01:46.949817Z","shell.execute_reply.started":"2022-09-01T08:01:46.858651Z","shell.execute_reply":"2022-09-01T08:01:46.948320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels.describe(include='all')","metadata":{"execution":{"iopub.status.busy":"2022-09-01T08:01:46.963251Z","iopub.execute_input":"2022-09-01T08:01:46.964476Z","iopub.status.idle":"2022-09-01T08:01:47.006505Z","shell.execute_reply.started":"2022-09-01T08:01:46.964439Z","shell.execute_reply":"2022-09-01T08:01:47.005380Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(os.listdir('/kaggle/temp/'))\n","metadata":{"execution":{"iopub.status.busy":"2022-09-01T08:01:47.008215Z","iopub.execute_input":"2022-09-01T08:01:47.009523Z","iopub.status.idle":"2022-09-01T08:01:47.016587Z","shell.execute_reply.started":"2022-09-01T08:01:47.009478Z","shell.execute_reply":"2022-09-01T08:01:47.015328Z"},"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-01T08:01:47.018454Z","iopub.execute_input":"2022-09-01T08:01:47.019336Z","iopub.status.idle":"2022-09-01T08:01:47.054390Z","shell.execute_reply.started":"2022-09-01T08:01:47.019295Z","shell.execute_reply":"2022-09-01T08:01:47.053016Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from 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","metadata":{"execution":{"iopub.status.busy":"2022-09-01T08:06:42.564655Z","iopub.execute_input":"2022-09-01T08:06:42.565300Z","iopub.status.idle":"2022-09-01T08:06:48.243260Z","shell.execute_reply.started":"2022-09-01T08:06:42.565264Z","shell.execute_reply":"2022-09-01T08:06:48.242076Z"},"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\"\n# parent_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-01T08:01:47.056196Z","iopub.execute_input":"2022-09-01T08:01:47.057435Z","iopub.status.idle":"2022-09-01T08:01:55.174920Z","shell.execute_reply.started":"2022-09-01T08:01:47.057387Z","shell.execute_reply":"2022-09-01T08:01:55.173558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator()\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)\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":"2022-09-01T08:06:48.245300Z","iopub.execute_input":"2022-09-01T08:06:48.245849Z","iopub.status.idle":"2022-09-01T08:06:49.610515Z","shell.execute_reply.started":"2022-09-01T08:06:48.245820Z","shell.execute_reply":"2022-09-01T08:06:49.609427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model5 = Sequential()\nmodel5.add(Conv2D(32, (3, 3), activation='relu', padding='same', input_shape=(32, 32, 3)))\n\nmodel5.add(BatchNormalization())\nmodel5.add(Conv2D(32, (3, 3), activation='relu', padding='same'))\nmodel5.add(BatchNormalization())\nmodel5.add(MaxPool2D((2, 2)))\nmodel5.add(Dropout(0.2))\nmodel5.add(Conv2D(64, (3, 3), activation='relu', padding='same'))\nmodel5.add(BatchNormalization())\nmodel5.add(Conv2D(64, (3, 3), activation='relu',padding='same'))\nmodel5.add(BatchNormalization())\nmodel5.add(MaxPool2D((2, 2)))\nmodel5.add(Dropout(0.3))\nmodel5.add(Conv2D(128, (3, 3), activation='relu',  padding='same'))\nmodel5.add(BatchNormalization())\nmodel5.add(Conv2D(128, (3, 3), activation='relu', padding='same'))\nmodel5.add(BatchNormalization())\nmodel5.add(MaxPool2D((2, 2)))\nmodel5.add(Dropout(0.4))\nmodel5.add(Flatten())\nmodel5.add(Dense(128, activation='relu'))\nmodel5.add(BatchNormalization())\nmodel5.add(Dropout(0.5))\nmodel5.add(Dense(10, activation='softmax'))\n\nmodel5.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n","metadata":{"execution":{"iopub.status.busy":"2022-09-01T08:06:59.283517Z","iopub.execute_input":"2022-09-01T08:06:59.284117Z","iopub.status.idle":"2022-09-01T08:07:02.614671Z","shell.execute_reply.started":"2022-09-01T08:06:59.284075Z","shell.execute_reply":"2022-09-01T08:07:02.613622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model5.fit(train_generator, epochs=20, validation_data=valid_generator,workers=8,use_multiprocessing=True,verbose=2)\n\n","metadata":{"execution":{"iopub.status.busy":"2022-09-01T08:07:05.170849Z","iopub.execute_input":"2022-09-01T08:07:05.171274Z","iopub.status.idle":"2022-09-01T08:07:36.936712Z","shell.execute_reply.started":"2022-09-01T08:07:05.171237Z","shell.execute_reply":"2022-09-01T08:07:36.934162Z"},"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":"2022-09-01T08:01:55.407212Z","iopub.status.idle":"2022-09-01T08:01:55.407813Z","shell.execute_reply.started":"2022-09-01T08:01:55.407468Z","shell.execute_reply":"2022-09-01T08:01:55.407494Z"},"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-01T08:01:55.415893Z","iopub.status.idle":"2022-09-01T08:01:55.416503Z","shell.execute_reply.started":"2022-09-01T08:01:55.416170Z","shell.execute_reply":"2022-09-01T08:01:55.416195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_gen.reset()\npredictions_vecs = model5.predict(test_gen)\n\npredictions_final = np.argmax(predictions_vecs, axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-09-01T08:01:55.418057Z","iopub.status.idle":"2022-09-01T08:01:55.418668Z","shell.execute_reply.started":"2022-09-01T08:01:55.418352Z","shell.execute_reply":"2022-09-01T08:01:55.418382Z"},"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-01T08:01:55.422284Z","iopub.status.idle":"2022-09-01T08:01:55.422880Z","shell.execute_reply.started":"2022-09-01T08:01:55.422545Z","shell.execute_reply":"2022-09-01T08:01:55.422571Z"},"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":"2022-09-01T08:01:55.426639Z","iopub.status.idle":"2022-09-01T08:01:55.427293Z","shell.execute_reply.started":"2022-09-01T08:01:55.426954Z","shell.execute_reply":"2022-09-01T08:01:55.426983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}