{"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-03-27T12:53:02.330744Z","iopub.execute_input":"2022-03-27T12:53:02.331058Z","iopub.status.idle":"2022-03-27T12:53:02.362276Z","shell.execute_reply.started":"2022-03-27T12:53:02.330979Z","shell.execute_reply":"2022-03-27T12:53:02.361591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\nfrom keras.utils.np_utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:53:02.363838Z","iopub.execute_input":"2022-03-27T12:53:02.364346Z","iopub.status.idle":"2022-03-27T12:53:07.311034Z","shell.execute_reply.started":"2022-03-27T12:53:02.364309Z","shell.execute_reply":"2022-03-27T12:53:07.310285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:53:07.312657Z","iopub.execute_input":"2022-03-27T12:53:07.312884Z","iopub.status.idle":"2022-03-27T12:53:19.698233Z","shell.execute_reply.started":"2022-03-27T12:53:07.312849Z","shell.execute_reply":"2022-03-27T12:53:19.697417Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:53:19.699781Z","iopub.execute_input":"2022-03-27T12:53:19.700027Z","iopub.status.idle":"2022-03-27T12:53:19.845713Z","shell.execute_reply.started":"2022-03-27T12:53:19.699991Z","shell.execute_reply":"2022-03-27T12:53:19.845028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unpack_archive('/kaggle/input/cifar-10/train.7z','/kaggle/temp')","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:53:19.847932Z","iopub.execute_input":"2022-03-27T12:53:19.848210Z","iopub.status.idle":"2022-03-27T12:54:00.551546Z","shell.execute_reply.started":"2022-03-27T12:53:19.848172Z","shell.execute_reply":"2022-03-27T12:54:00.550777Z"},"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-27T12:54:00.552804Z","iopub.execute_input":"2022-03-27T12:54:00.553058Z","iopub.status.idle":"2022-03-27T12:54:00.610778Z","shell.execute_reply.started":"2022-03-27T12:54:00.553023Z","shell.execute_reply":"2022-03-27T12:54:00.610033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if not os.path.exists(\"/kaggle/temp/validation/\"):\n    os.mkdir(\"/kaggle/temp/validation/\")","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:54:00.612914Z","iopub.execute_input":"2022-03-27T12:54:00.613276Z","iopub.status.idle":"2022-03-27T12:54:00.657316Z","shell.execute_reply.started":"2022-03-27T12:54:00.613238Z","shell.execute_reply":"2022-03-27T12:54:00.656551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"parent_path_train = \"/kaggle/temp/train/\"\nparent_path_validation = \"/kaggle/temp/validation/\"\nparent_path_test = \"/kaggle/temp/test/\"\n\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        \n    path_validation = os.path.join(parent_path_validation,class1)\n    if not os.path.exists(path_validation):\n        os.mkdir(path_validation)\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.80:\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_validation,row[\"label\"],id)\n        os.replace(source_path,target_path)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:54:00.659156Z","iopub.execute_input":"2022-03-27T12:54:00.660634Z","iopub.status.idle":"2022-03-27T12:54:05.020152Z","shell.execute_reply.started":"2022-03-27T12:54:00.660603Z","shell.execute_reply":"2022-03-27T12:54:05.019432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install tensorflow","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:54:05.021317Z","iopub.execute_input":"2022-03-27T12:54:05.022403Z","iopub.status.idle":"2022-03-27T12:54:35.280097Z","shell.execute_reply.started":"2022-03-27T12:54:05.022370Z","shell.execute_reply":"2022-03-27T12:54:35.279288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras import Sequential\nfrom keras.layers import Dense,Conv2D,MaxPooling2D,Activation,BatchNormalization,GlobalAveragePooling2D,Flatten\nfrom keras.utils.np_utils import to_categorical\nfrom keras.callbacks import ReduceLROnPlateau\n\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:54:35.281700Z","iopub.execute_input":"2022-03-27T12:54:35.282409Z","iopub.status.idle":"2022-03-27T12:54:35.287350Z","shell.execute_reply.started":"2022-03-27T12:54:35.282363Z","shell.execute_reply":"2022-03-27T12:54:35.286679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(filters=32,kernel_size=(3,3),strides=(1,1),padding='valid',activation=None,use_bias=False,input_shape=(32,32,3)))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\n\nmodel.add(Conv2D(filters=64, kernel_size=(3,3), strides=(1,1), padding='valid', activation=None, use_bias=False))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\n\nmodel.add(Conv2D(filters=96, kernel_size=(3,3), strides=(1,1), padding='valid', activation=None, use_bias=False))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\n\nmodel.add(Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='valid', activation=None, use_bias=False))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\n\nmodel.add(Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), padding='valid', activation=None, use_bias=False))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\n\nmodel.add(Flatten())\nmodel.add(Dense(units=10))\nmodel.add(BatchNormalization())\nmodel.add(Activation('softmax'))","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:54:35.290344Z","iopub.execute_input":"2022-03-27T12:54:35.290843Z","iopub.status.idle":"2022-03-27T12:54:37.824418Z","shell.execute_reply.started":"2022-03-27T12:54:35.290808Z","shell.execute_reply":"2022-03-27T12:54:37.823657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T15:18:09.339483Z","iopub.execute_input":"2022-03-27T15:18:09.339865Z","iopub.status.idle":"2022-03-27T15:18:09.398168Z","shell.execute_reply.started":"2022-03-27T15:18:09.339832Z","shell.execute_reply":"2022-03-27T15:18:09.397411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"reduceLROnPlateau = ReduceLROnPlateau(monitor='val_accuracy',\n                                      patience=3,\n                                     verbose=1,\n                                     factor=0.5,\n                                     min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:54:37.825549Z","iopub.execute_input":"2022-03-27T12:54:37.826160Z","iopub.status.idle":"2022-03-27T12:54:37.831157Z","shell.execute_reply.started":"2022-03-27T12:54:37.826117Z","shell.execute_reply":"2022-03-27T12:54:37.830121Z"},"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                                  rescale=1./255\n                                  )","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:54:37.832276Z","iopub.execute_input":"2022-03-27T12:54:37.833676Z","iopub.status.idle":"2022-03-27T12:54:37.840920Z","shell.execute_reply.started":"2022-03-27T12:54:37.833636Z","shell.execute_reply":"2022-03-27T12:54:37.840120Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_gen = train_datagen.flow_from_directory(directory='/kaggle/temp/train/',target_size=(32,32),batch_size=128)\nvalidation_datagen = ImageDataGenerator(rescale=1./255)\nvalid_gen = validation_datagen.flow_from_directory(directory='/kaggle/temp/validation/',target_size=(32,32),batch_size=128)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:54:37.842002Z","iopub.execute_input":"2022-03-27T12:54:37.842594Z","iopub.status.idle":"2022-03-27T12:54:39.387521Z","shell.execute_reply.started":"2022-03-27T12:54:37.842556Z","shell.execute_reply":"2022-03-27T12:54:39.386771Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    loss='categorical_crossentropy', \n    optimizer='Adam',               \n    metrics=['accuracy']\n)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:54:39.388638Z","iopub.execute_input":"2022-03-27T12:54:39.389065Z","iopub.status.idle":"2022-03-27T12:54:39.399436Z","shell.execute_reply.started":"2022-03-27T12:54:39.389025Z","shell.execute_reply":"2022-03-27T12:54:39.398765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history=model.fit(train_gen,epochs=150,callbacks=[reduceLROnPlateau],validation_data=valid_gen,steps_per_epoch=train_gen.n//train_gen.batch_size,\n         validation_steps= valid_gen.n//valid_gen.batch_size,workers=8,use_multiprocessing=True)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:54:39.400349Z","iopub.execute_input":"2022-03-27T12:54:39.400595Z","iopub.status.idle":"2022-03-27T14:25:36.013116Z","shell.execute_reply.started":"2022-03-27T12:54:39.400562Z","shell.execute_reply":"2022-03-27T14:25:36.012267Z"},"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-27T15:04:08.959738Z","iopub.execute_input":"2022-03-27T15:04:08.959997Z","iopub.status.idle":"2022-03-27T15:18:09.337948Z","shell.execute_reply.started":"2022-03-27T15:04:08.959967Z","shell.execute_reply":"2022-03-27T15:18:09.337112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\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-03-27T15:22:00.169045Z","iopub.execute_input":"2022-03-27T15:22:00.169301Z","iopub.status.idle":"2022-03-27T15:22:06.624223Z","shell.execute_reply.started":"2022-03-27T15:22:00.169274Z","shell.execute_reply":"2022-03-27T15:22:06.623441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_gen.reset()\npredictions_vecs = model.predict(test_gen)\npredictions_final = np.argmax(predictions_vecs, axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T15:22:17.085787Z","iopub.execute_input":"2022-03-27T15:22:17.086438Z","iopub.status.idle":"2022-03-27T15:23:39.218390Z","shell.execute_reply.started":"2022-03-27T15:22:17.086399Z","shell.execute_reply":"2022-03-27T15:23:39.217669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(type(train_gen.class_indices))\nprint(train_gen.class_indices)\n\nclasses = {value:key for (key,value) in train_gen.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-27T15:29:20.005020Z","iopub.execute_input":"2022-03-27T15:29:20.005344Z","iopub.status.idle":"2022-03-27T15:29:20.451272Z","shell.execute_reply.started":"2022-03-27T15:29:20.005293Z","shell.execute_reply":"2022-03-27T15:29:20.450584Z"},"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-27T15:24:30.508610Z","iopub.execute_input":"2022-03-27T15:24:30.508871Z","iopub.status.idle":"2022-03-27T15:24:30.646875Z","shell.execute_reply.started":"2022-03-27T15:24:30.508845Z","shell.execute_reply":"2022-03-27T15:24:30.646132Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_df=pd.DataFrame(history.history)\nhistory_df[['val_loss','loss']].plot()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T15:26:55.999009Z","iopub.execute_input":"2022-03-27T15:26:55.999261Z","iopub.status.idle":"2022-03-27T15:26:56.237364Z","shell.execute_reply.started":"2022-03-27T15:26:55.999232Z","shell.execute_reply":"2022-03-27T15:26:56.236710Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_df[['accuracy','val_accuracy']].plot()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T15:29:40.900701Z","iopub.execute_input":"2022-03-27T15:29:40.900982Z","iopub.status.idle":"2022-03-27T15:29:41.134549Z","shell.execute_reply.started":"2022-03-27T15:29:40.900954Z","shell.execute_reply":"2022-03-27T15:29:41.133834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub","metadata":{"execution":{"iopub.status.busy":"2022-03-27T15:30:18.899680Z","iopub.execute_input":"2022-03-27T15:30:18.900128Z","iopub.status.idle":"2022-03-27T15:30:18.920271Z","shell.execute_reply.started":"2022-03-27T15:30:18.900093Z","shell.execute_reply":"2022-03-27T15:30:18.919345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_df","metadata":{"execution":{"iopub.status.busy":"2022-03-27T15:27:48.387822Z","iopub.execute_input":"2022-03-27T15:27:48.388270Z","iopub.status.idle":"2022-03-27T15:27:48.401432Z","shell.execute_reply.started":"2022-03-27T15:27:48.388234Z","shell.execute_reply":"2022-03-27T15:27:48.400774Z"},"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-03-27T15:47:49.374068Z","iopub.execute_input":"2022-03-27T15:47:49.374350Z","iopub.status.idle":"2022-03-27T15:47:49.888545Z","shell.execute_reply.started":"2022-03-27T15:47:49.374317Z","shell.execute_reply":"2022-03-27T15:47:49.887745Z"},"trusted":true},"execution_count":null,"outputs":[]}]}