{"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 matplotlib.pyplot as plt\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-23T15:06:13.442641Z","iopub.execute_input":"2022-09-23T15:06:13.443076Z","iopub.status.idle":"2022-09-23T15:06:18.416033Z","shell.execute_reply.started":"2022-09-23T15:06:13.443038Z","shell.execute_reply":"2022-09-23T15:06:18.415080Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2022-09-23T15:07:01.581196Z","iopub.execute_input":"2022-09-23T15:07:01.581565Z","iopub.status.idle":"2022-09-23T15:07:11.329331Z","shell.execute_reply.started":"2022-09-23T15:07:01.581534Z","shell.execute_reply":"2022-09-23T15:07:11.328183Z"},"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-09-23T15:07:19.101513Z","iopub.execute_input":"2022-09-23T15:07:19.101904Z","iopub.status.idle":"2022-09-23T15:07:19.137514Z","shell.execute_reply.started":"2022-09-23T15:07:19.101870Z","shell.execute_reply":"2022-09-23T15:07:19.136271Z"},"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-09-23T15:07:30.909299Z","iopub.execute_input":"2022-09-23T15:07:30.910211Z","iopub.status.idle":"2022-09-23T15:08:15.224907Z","shell.execute_reply.started":"2022-09-23T15:07:30.910177Z","shell.execute_reply":"2022-09-23T15:08:15.223913Z"},"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-23T15:11:50.371932Z","iopub.execute_input":"2022-09-23T15:11:50.372336Z","iopub.status.idle":"2022-09-23T15:11:50.417882Z","shell.execute_reply.started":"2022-09-23T15:11:50.372302Z","shell.execute_reply":"2022-09-23T15:11:50.416787Z"},"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-23T15:12:05.432938Z","iopub.execute_input":"2022-09-23T15:12:05.433464Z","iopub.status.idle":"2022-09-23T15:12:10.251475Z","shell.execute_reply.started":"2022-09-23T15:12:05.433423Z","shell.execute_reply":"2022-09-23T15:12:10.250490Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(32, 32, 3)))\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(256, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(Conv2D(256, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(BatchNormalization()) # make artificial neural networks faster and more stable through normalization of the input layer by re-centering and re-scaling.\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\nmodel.add(Dense(10, activation='softmax'))\n\n# Checking the model summary\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-09-23T15:12:14.751139Z","iopub.execute_input":"2022-09-23T15:12:14.751506Z","iopub.status.idle":"2022-09-23T15:12:17.738144Z","shell.execute_reply.started":"2022-09-23T15:12:14.751475Z","shell.execute_reply":"2022-09-23T15:12:17.737198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optim = tf.keras.optimizers.SGD(momentum=0.9, learning_rate=0.002)\nmodel.compile(optimizer= optim, loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-09-23T16:04:43.226613Z","iopub.execute_input":"2022-09-23T16:04:43.227036Z","iopub.status.idle":"2022-09-23T16:04:43.242140Z","shell.execute_reply.started":"2022-09-23T16:04:43.226996Z","shell.execute_reply":"2022-09-23T16:04:43.241166Z"},"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)\nvalid_datagen = ImageDataGenerator()\n\ntrain_generator = train_datagen.flow_from_directory(directory='/kaggle/temp/train/', shuffle=True, target_size=(32,32),batch_size=256)\nvalid_generator = valid_datagen.flow_from_directory(directory='/kaggle/temp/valid/', shuffle=True, target_size=(32,32),batch_size=256)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T16:04:46.468739Z","iopub.execute_input":"2022-09-23T16:04:46.469088Z","iopub.status.idle":"2022-09-23T16:04:47.476253Z","shell.execute_reply.started":"2022-09-23T16:04:46.469059Z","shell.execute_reply":"2022-09-23T16:04:47.475182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_generator,epochs=100, validation_data=valid_generator,steps_per_epoch=train_generator.n//train_generator.batch_size,\n         validation_steps= valid_generator.n//valid_generator.batch_size,workers=8,use_multiprocessing=True)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T16:04:57.427937Z","iopub.execute_input":"2022-09-23T16:04:57.428684Z","iopub.status.idle":"2022-09-23T17:02:56.548070Z","shell.execute_reply.started":"2022-09-23T16:04:57.428646Z","shell.execute_reply":"2022-09-23T17:02:56.546465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(history.history.keys())","metadata":{"execution":{"iopub.status.busy":"2022-09-23T17:03:00.534266Z","iopub.execute_input":"2022-09-23T17:03:00.535323Z","iopub.status.idle":"2022-09-23T17:03:00.542340Z","shell.execute_reply.started":"2022-09-23T17:03:00.535282Z","shell.execute_reply":"2022-09-23T17:03:00.541223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Loss curve\nplt.figure(figsize=[6,4])\nplt.plot(history.history['loss'], 'black', linewidth=2.0)\nplt.plot(history.history['val_loss'], 'green', linewidth=2.0)\nplt.legend(['Training Loss', 'Validation Loss'], fontsize=14)\nplt.xlabel('Epochs', fontsize=10)\nplt.ylabel('Loss', fontsize=10)\nplt.title('Loss Curves', fontsize=12)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T17:03:03.986620Z","iopub.execute_input":"2022-09-23T17:03:03.987001Z","iopub.status.idle":"2022-09-23T17:03:04.279215Z","shell.execute_reply.started":"2022-09-23T17:03:03.986970Z","shell.execute_reply":"2022-09-23T17:03:04.278292Z"},"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-09-23T17:03:21.034251Z","iopub.execute_input":"2022-09-23T17:03:21.034937Z","iopub.status.idle":"2022-09-23T17:16:48.332941Z","shell.execute_reply.started":"2022-09-23T17:03:21.034901Z","shell.execute_reply":"2022-09-23T17:16:48.331922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unregister_unpack_format('7zip')","metadata":{"execution":{"iopub.status.busy":"2022-09-23T17:16:56.671737Z","iopub.execute_input":"2022-09-23T17:16:56.672277Z","iopub.status.idle":"2022-09-23T17:16:56.682948Z","shell.execute_reply.started":"2022-09-23T17:16:56.672227Z","shell.execute_reply":"2022-09-23T17:16:56.679065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_gen = test_datagen.flow_from_directory(directory='/kaggle/temp/test',target_size=(32,32),batch_size=256,class_mode=None,shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T17:17:01.886787Z","iopub.execute_input":"2022-09-23T17:17:01.887177Z","iopub.status.idle":"2022-09-23T17:17:07.066758Z","shell.execute_reply.started":"2022-09-23T17:17:01.887145Z","shell.execute_reply":"2022-09-23T17:17:07.065797Z"},"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-23T17:17:09.932348Z","iopub.execute_input":"2022-09-23T17:17:09.933102Z","iopub.status.idle":"2022-09-23T17:18:27.773743Z","shell.execute_reply.started":"2022-09-23T17:17:09.933067Z","shell.execute_reply":"2022-09-23T17:18:27.772669Z"},"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-23T17:18:32.998760Z","iopub.execute_input":"2022-09-23T17:18:32.999105Z","iopub.status.idle":"2022-09-23T17:18:33.429318Z","shell.execute_reply.started":"2022-09-23T17:18:32.999077Z","shell.execute_reply":"2022-09-23T17:18:33.428408Z"},"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-23T17:18:39.153920Z","iopub.execute_input":"2022-09-23T17:18:39.154271Z","iopub.status.idle":"2022-09-23T17:18:39.279109Z","shell.execute_reply.started":"2022-09-23T17:18:39.154239Z","shell.execute_reply":"2022-09-23T17:18:39.278145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['label'] = predicted_classes_final\nsub.to_csv('Cifar_Challenge-210045452.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T17:18:44.893458Z","iopub.execute_input":"2022-09-23T17:18:44.893835Z","iopub.status.idle":"2022-09-23T17:18:45.366652Z","shell.execute_reply.started":"2022-09-23T17:18:44.893806Z","shell.execute_reply":"2022-09-23T17:18:45.365551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('cifar10_Challenge-210045452')","metadata":{"execution":{"iopub.status.busy":"2022-09-23T17:18:52.882257Z","iopub.execute_input":"2022-09-23T17:18:52.882645Z","iopub.status.idle":"2022-09-23T17:18:54.857860Z","shell.execute_reply.started":"2022-09-23T17:18:52.882612Z","shell.execute_reply":"2022-09-23T17:18:54.856899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}