{"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, GlobalAveragePooling2D,Dropout\nfrom keras.utils.np_utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.applications.xception import Xception, preprocess_input","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-03-25T18:13:13.914683Z","iopub.execute_input":"2022-03-25T18:13:13.914937Z","iopub.status.idle":"2022-03-25T18:13:13.921365Z","shell.execute_reply.started":"2022-03-25T18:13:13.914908Z","shell.execute_reply":"2022-03-25T18:13:13.920359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:13.923073Z","iopub.execute_input":"2022-03-25T18:13:13.923886Z","iopub.status.idle":"2022-03-25T18:13:22.535509Z","shell.execute_reply.started":"2022-03-25T18:13:13.923846Z","shell.execute_reply":"2022-03-25T18:13:22.534527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from py7zr import unpack_7zarchive\nimport shutil\n\nshutil.register_unpack_format('7zip',['.7z'],unpack_7zarchive) #Run for first time only","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:22.537769Z","iopub.execute_input":"2022-03-25T18:13:22.538219Z","iopub.status.idle":"2022-03-25T18:13:22.576625Z","shell.execute_reply.started":"2022-03-25T18:13:22.538181Z","shell.execute_reply":"2022-03-25T18:13:22.574154Z"},"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":"2022-03-25T18:13:22.577993Z","iopub.status.idle":"2022-03-25T18:13:22.578754Z","shell.execute_reply.started":"2022-03-25T18:13:22.578485Z","shell.execute_reply":"2022-03-25T18:13:22.578512Z"},"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-03-25T18:13:22.580167Z","iopub.status.idle":"2022-03-25T18:13:22.580923Z","shell.execute_reply.started":"2022-03-25T18:13:22.580632Z","shell.execute_reply":"2022-03-25T18:13:22.58066Z"},"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-03-25T18:13:22.582355Z","iopub.status.idle":"2022-03-25T18:13:22.583094Z","shell.execute_reply.started":"2022-03-25T18:13:22.582843Z","shell.execute_reply":"2022-03-25T18:13:22.58287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /kaggle/temp/valid\n!ls /kaggle/temp/train","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:22.584468Z","iopub.status.idle":"2022-03-25T18:13:22.585211Z","shell.execute_reply.started":"2022-03-25T18:13:22.584936Z","shell.execute_reply":"2022-03-25T18:13:22.584962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xception_wo_top=Xception(include_top=False, input_shape=(291,291,3), weights='imagenet')\nxception_wo_top.summary()\n\nfor layer in xception_wo_top.layers:\n    layer.trainable=True","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:22.586609Z","iopub.status.idle":"2022-03-25T18:13:22.587393Z","shell.execute_reply.started":"2022-03-25T18:13:22.587139Z","shell.execute_reply":"2022-03-25T18:13:22.587166Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classifier = Sequential()\nclassifier.add(xception_wo_top)\nclassifier.add(GlobalAveragePooling2D())\nclassifier.add(Dropout(0.3))\nclassifier.add(Dense(10,activation='softmax'))\n\nclassifier.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nclassifier.summary()\n\nfor i in classifier.layers:\n    print(i.trainable)","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:22.588826Z","iopub.status.idle":"2022-03-25T18:13:22.589611Z","shell.execute_reply.started":"2022-03-25T18:13:22.589329Z","shell.execute_reply":"2022-03-25T18:13:22.589356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"reduceLROnPlateau=ReduceLROnPlateau(monitor='val_acc', patience=3, verbose=1, factor=0.5, min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:22.591051Z","iopub.status.idle":"2022-03-25T18:13:22.59183Z","shell.execute_reply.started":"2022-03-25T18:13:22.59155Z","shell.execute_reply":"2022-03-25T18:13:22.591578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_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                             preprocessing_function=preprocess_input,\n                             rescale=None)\n\nvalid_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\n\n\ntrain_generator = train_datagen.flow_from_directory(directory='/kaggle/temp/train/', \n                                                    shuffle=True, target_size=(192,192),\n                                                    batch_size=128)\nvalid_generator = valid_datagen.flow_from_directory(directory='/kaggle/temp/valid/',\n                                                    shuffle=True, target_size=(192,192),\n                                                    batch_size=128)","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:22.593338Z","iopub.status.idle":"2022-03-25T18:13:22.594098Z","shell.execute_reply.started":"2022-03-25T18:13:22.59383Z","shell.execute_reply":"2022-03-25T18:13:22.593857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classifier.fit(train_generator,\n               epochs=8, \n               validation_data=valid_generator,\n               callbacks=[reduceLROnPlateau],\n               steps_per_epoch=train_generator.n//train_generator.batch_size,\n               validation_steps= valid_generator.n//valid_generator.batch_size,\n               workers=8,\n               use_multiprocessing=True)","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:22.595634Z","iopub.status.idle":"2022-03-25T18:13:22.596409Z","shell.execute_reply.started":"2022-03-25T18:13:22.596145Z","shell.execute_reply":"2022-03-25T18:13:22.596174Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unpack_archive('/kaggle/input/cifar-10/test.7z','/kaggle/temp/test')","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:22.597837Z","iopub.status.idle":"2022-03-25T18:13:22.598575Z","shell.execute_reply.started":"2022-03-25T18:13:22.598308Z","shell.execute_reply":"2022-03-25T18:13:22.598334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unregister_unpack_format('7zip')","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:33.465378Z","iopub.execute_input":"2022-03-25T18:13:33.465886Z","iopub.status.idle":"2022-03-25T18:13:33.470734Z","shell.execute_reply.started":"2022-03-25T18:13:33.465847Z","shell.execute_reply":"2022-03-25T18:13:33.46979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\n\ntest_gen = test_datagen.flow_from_directory(directory='/kaggle/temp/test',target_size=(192,192),batch_size=64,class_mode=None,shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:38.509503Z","iopub.execute_input":"2022-03-25T18:13:38.509791Z","iopub.status.idle":"2022-03-25T18:13:45.037938Z","shell.execute_reply.started":"2022-03-25T18:13:38.509759Z","shell.execute_reply":"2022-03-25T18:13:45.03718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_gen.reset()\npredictions_vecs = classifier.predict(test_gen)\n\npredictions_final = np.argmax(predictions_vecs, axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:57:18.820624Z","iopub.execute_input":"2022-03-25T18:57:18.821116Z","iopub.status.idle":"2022-03-25T18:57:18.836099Z","shell.execute_reply.started":"2022-03-25T18:57:18.821078Z","shell.execute_reply":"2022-03-25T18:57:18.835164Z"},"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-03-25T18:57:11.926256Z","iopub.execute_input":"2022-03-25T18:57:11.926866Z","iopub.status.idle":"2022-03-25T18:57:12.013879Z","shell.execute_reply.started":"2022-03-25T18:57:11.926768Z","shell.execute_reply":"2022-03-25T18:57:12.012588Z"},"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-03-25T18:13:22.60859Z","iopub.status.idle":"2022-03-25T18:13:22.609305Z","shell.execute_reply.started":"2022-03-25T18:13:22.609031Z","shell.execute_reply":"2022-03-25T18:13:22.609057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['label'] = predicted_classes_final\nsub.to_csv('19BCE226_submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-03-25T18:13:22.610654Z","iopub.status.idle":"2022-03-25T18:13:22.611394Z","shell.execute_reply.started":"2022-03-25T18:13:22.611143Z","shell.execute_reply":"2022-03-25T18:13:22.61117Z"},"trusted":true},"execution_count":null,"outputs":[]}]}