{"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-04-07T17:49:25.565432Z","iopub.execute_input":"2022-04-07T17:49:25.565756Z","iopub.status.idle":"2022-04-07T17:49:30.401011Z","shell.execute_reply.started":"2022-04-07T17:49:25.56567Z","shell.execute_reply":"2022-04-07T17:49:30.400267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2022-04-07T17:49:30.402843Z","iopub.execute_input":"2022-04-07T17:49:30.403103Z","iopub.status.idle":"2022-04-07T17:49:41.731854Z","shell.execute_reply.started":"2022-04-07T17:49:30.403069Z","shell.execute_reply":"2022-04-07T17:49:41.731019Z"},"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-04-07T17:49:41.734641Z","iopub.execute_input":"2022-04-07T17:49:41.734912Z","iopub.status.idle":"2022-04-07T17:49:41.879543Z","shell.execute_reply.started":"2022-04-07T17:49:41.734872Z","shell.execute_reply":"2022-04-07T17:49:41.878808Z"},"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-04-07T17:49:41.880877Z","iopub.execute_input":"2022-04-07T17:49:41.88112Z","iopub.status.idle":"2022-04-07T17:50:24.469089Z","shell.execute_reply.started":"2022-04-07T17:49:41.881088Z","shell.execute_reply":"2022-04-07T17:50:24.468341Z"},"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-04-07T17:50:24.471563Z","iopub.execute_input":"2022-04-07T17:50:24.471795Z","iopub.status.idle":"2022-04-07T17:50:24.524986Z","shell.execute_reply.started":"2022-04-07T17:50:24.471755Z","shell.execute_reply":"2022-04-07T17:50:24.524248Z"},"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-04-07T17:50:24.52875Z","iopub.execute_input":"2022-04-07T17:50:24.530564Z","iopub.status.idle":"2022-04-07T17:50:31.386642Z","shell.execute_reply.started":"2022-04-07T17:50:24.530527Z","shell.execute_reply":"2022-04-07T17:50:31.385669Z"},"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-04-07T17:50:31.387993Z","iopub.execute_input":"2022-04-07T17:50:31.388367Z","iopub.status.idle":"2022-04-07T17:50:33.062729Z","shell.execute_reply.started":"2022-04-07T17:50:31.38833Z","shell.execute_reply":"2022-04-07T17:50:33.06154Z"},"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-04-07T17:50:33.06603Z","iopub.execute_input":"2022-04-07T17:50:33.066773Z","iopub.status.idle":"2022-04-07T17:50:37.157481Z","shell.execute_reply.started":"2022-04-07T17:50:33.066733Z","shell.execute_reply":"2022-04-07T17:50:37.156653Z"},"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-04-07T17:50:37.159477Z","iopub.execute_input":"2022-04-07T17:50:37.159775Z","iopub.status.idle":"2022-04-07T17:50:37.541932Z","shell.execute_reply.started":"2022-04-07T17:50:37.159733Z","shell.execute_reply":"2022-04-07T17:50:37.541217Z"},"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-04-07T17:50:37.543008Z","iopub.execute_input":"2022-04-07T17:50:37.543324Z","iopub.status.idle":"2022-04-07T17:50:37.550648Z","shell.execute_reply.started":"2022-04-07T17:50:37.543273Z","shell.execute_reply":"2022-04-07T17:50:37.549859Z"},"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-04-07T17:50:37.552702Z","iopub.execute_input":"2022-04-07T17:50:37.552903Z","iopub.status.idle":"2022-04-07T17:50:39.356351Z","shell.execute_reply.started":"2022-04-07T17:50:37.552878Z","shell.execute_reply":"2022-04-07T17:50:39.355571Z"},"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-04-07T17:50:39.357519Z","iopub.execute_input":"2022-04-07T17:50:39.358089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unpack_archive('/kaggle/input/cifar-10/test.7z','/kaggle/temp/test')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unregister_unpack_format('7zip')","metadata":{"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":{"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":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv('../input/cifar-10/sampleSubmission.csv',header='infer')\nsub.info()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['label'] = predicted_classes_final\nsub.to_csv('19BCE226_submission.csv',index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}